diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c93a948911..2a4b5c96e4 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -46,3 +46,5 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `docs/images/pivot.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | | `docs/images/format-chart.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | | `docs/images/page-break.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | +| Core 14 AFM metric numbers in `crates/pdf/src/symbol.rs` (Symbol: character codes and advance widths) and `crates/pdf/src/metrics.rs` (Helvetica, Times and Courier advance widths); no font file | Adobe Systems Incorporated | Adobe's Core 14 AFM font metrics files (`Symbol.afm` 001.008 and the Helvetica, Times and Courier AFMs) | Adobe's Core 14 metrics notice: the files may be used, copied and distributed for any purpose and without charge, provided the notice is kept (quoted in `crates/pdf/src/metrics.rs`) | Numbers only, typed in from the public metrics. PDF export embeds no font: Symbol and the Times faces are base-14 fonts every PDF reader supplies, and text outside WinAnsiEncoding is set in a predefined, non-embedded Adobe-GB1 CID font | +| Unicode values of the Symbol encoding in `crates/pdf/src/symbol.rs` (the code-to-character map; numbers only, no file copied) | Unicode, Inc. | `symbol.txt`, "Adobe Symbol Encoding to Unicode", table version 1.0 (2011-07-12), at unicode.org/Public/MAPPINGS/VENDORS/ADOBE/ | Unicode, Inc.'s notice in the file: "Unicode, Inc. hereby grants the right to freely use the information supplied in this file in the creation of products supporting the Unicode Standard, and to make copies of this file in any form for internal or external distribution as long as this notice remains attached." The file is provided as-is, without warranties | Separate from Adobe's Core 14 notice (previous row), which covers the character codes and widths; the Unicode values come from this table | diff --git a/Cargo.lock b/Cargo.lock index 80cf2de703..e8db558805 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,7 +20,7 @@ dependencies = [ "accesskit", "accesskit_consumer", "atspi-common", - "phf", + "phf 0.14.0", "serde", "zvariant", ] @@ -468,15 +468,30 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" @@ -1495,6 +1510,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fancy-regex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2017,6 +2043,7 @@ dependencies = [ "gridcraft-core", "gridcraft-formula", "gridcraft-functions", + "gridcraft-math", "gridcraft-model", "gridcraft-numfmt", "gridcraft-pdf", @@ -2047,6 +2074,16 @@ dependencies = [ "regex", ] +[[package]] +name = "gridcraft-math" +version = "0.15.0" +dependencies = [ + "ratex-font", + "ratex-layout", + "ratex-parser", + "ratex-types", +] + [[package]] name = "gridcraft-mcp" version = "0.15.0" @@ -2062,6 +2099,7 @@ version = "0.15.0" dependencies = [ "gridcraft-core", "gridcraft-formula", + "gridcraft-math", "serde", "serde_json", "sha2 0.11.1", @@ -2129,6 +2167,7 @@ dependencies = [ "gridcraft-core", "gridcraft-formula", "gridcraft-functions", + "gridcraft-math", "gridcraft-model", "quick-xml 0.41.0", "sha1 0.11.0", @@ -2967,7 +3006,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -3543,17 +3582,37 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.14.0", + "phf_shared 0.14.0", "serde", ] +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.8", +] + [[package]] name = "phf_generator" version = "0.14.0" @@ -3561,7 +3620,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -3570,13 +3642,22 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.14.0" @@ -3852,7 +3933,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash 2.1.3", @@ -3900,6 +3981,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.10.3" @@ -3938,6 +4028,66 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +[[package]] +name = "ratex-font" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7b73531dabe934a3e725ed5c90d18dacf43778b7a208381390943a9a8c24db" +dependencies = [ + "phf 0.11.3", + "ratex-types", +] + +[[package]] +name = "ratex-layout" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1792738e2e36683cd20de742296a5233759565efc8cd03831064a0ccfb1fe0f7" +dependencies = [ + "ratex-font", + "ratex-parser", + "ratex-types", + "serde_json", +] + +[[package]] +name = "ratex-lexer" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f704add86d7bf4c4ecc7767f45ab38a44f1bbfa4b49725b2ae53c32e83b8a61e" +dependencies = [ + "ratex-types", + "serde", + "thiserror 1.0.69", +] + +[[package]] +name = "ratex-parser" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "079ec2e7ac6bc76137a6de093a173d1f901139a51318589ab9ce17139c21a6f0" +dependencies = [ + "fancy-regex", + "ratex-font", + "ratex-lexer", + "ratex-types", + "regex", + "regex-lite", + "serde", + "serde_json", + "thiserror 1.0.69", + "unicode-normalization", +] + +[[package]] +name = "ratex-types" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cf0be3d050525f0f7d37af55a443d7648c222ccc617639950e3de1f8e6f9900" +dependencies = [ + "serde", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4037,6 +4187,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -4617,7 +4773,7 @@ dependencies = [ "const-oid", "der", "hex", - "rand", + "rand 0.10.3", "reqwest", "rustls-pki-types", "rustls-webpki", @@ -5346,6 +5502,15 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-properties" version = "0.1.4" @@ -5786,8 +5951,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.10.0", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -5859,7 +6024,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set", + "bit-set 0.10.0", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", diff --git a/Cargo.toml b/Cargo.toml index 0ce2e8f0be..8aa7ec8e77 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ gridcraft-engine = { path = "crates/engine" } gridcraft-ui-egui = { path = "crates/ui-egui" } gridcraft-mcp = { path = "crates/mcp" } gridcraft-pdf = { path = "crates/pdf" } +gridcraft-math = { path = "crates/math" } # Every craft-libs crate (craft-update and craft-window here, craft-ui in ui-egui, craft-print in # the app) comes from one storytold/craft-libs revision. # craft-update: app-specific pretend versions apply to startup and manual checks. @@ -47,6 +48,13 @@ aes = { version = "0.9", default-features = false } sha1 = { version = "0.11", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } +# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is +# young (0.1.x), and the gate recorded in docs/decisions.md vetted this release. +ratex-parser = "=0.1.14" +ratex-layout = "=0.1.14" +ratex-types = "=0.1.14" +ratex-font = "=0.1.14" + # ui egui = "0.37" egui_extras = { version = "0.37", default-features = false } diff --git a/ROADMAP.md b/ROADMAP.md index 17e5f80cb5..9acd2e13f7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-01 · **Change:** minor (Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-02 · **Change:** minor (Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -22,7 +22,7 @@ This page is the summary. The detail is in: | Number | Value | Kind | |---|---|---| | 2026-10-14 | Editing a cell with text that would read back as a number, boolean, date or formula (entered with a leading apostrophe) shows the apostrophe in the editor and formula bar, so Enter unchanged keeps it text (#1362) | -| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 276 / 292 (94.5%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) | +| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 277 / 292 (94.9%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) | | **Ready for real work** | **~50%** | estimated from written weights (51.6); [target-app-parity.md](docs/target-app-parity.md) | | **Mainstream practitioner** | **~50%** | estimated: typical analyst/finance user, weekly features, × 0.90 interaction × 0.92 stability × 0.88 file exchange; [method](docs/target-app-parity.md#mainstream-practitioner) | | **Essentials user** | **~63%** | estimated: core features only, × 0.92 launch/stability × 0.95 clarity × 0.90 opening sent files; [method](docs/target-app-parity.md#essentials-user) | @@ -135,6 +135,12 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-11-02 | Python mode in the formula bar: Ctrl+Alt+Shift+P, `=PY` then Tab, or editing a Python cell edits its code in the formula bar, with Enter for a new line, Tab to indent and Ctrl+Enter to commit through `python.set`. The code still doesn't run | +| 2026-11-02 | Python cells as data: `python.set` stores code in a cell, Python cells copy, move, fill and undo like formulas, and `.xlsx` reads and writes Python cells as [MS-XLSX] specifies (`_xlfn._xlws.PY(index,0 or 1)`, the code in the workbook's Python part) with cached values and spills, so such workbooks open with their results; nothing runs Python (new code shows `#BLOCKED!`), and opening a file limits code size, result size and spill ranges | +| 2026-11-02 | Equations: Insert › Equation (a split button with a gallery of examples) and an editor with quick-insert buttons, the error underlined at its position and a live preview; `insert.equation` and `equation.edit`; LaTeX laid out by RaTeX inside the new `gridcraft-math` crate, capped and panic-guarded, and cached on the shape so that painting never runs the layout engine; xlsx writes Office Math with a plain-text fallback and the source in `descr`, and reads Office Math back into LaTeX; PDF prints equations with the standard Symbol font and `[?]` for anything else | +| 2026-11-02 | Solver writes a Sensitivity report: Simplex LP shadow prices, reduced costs and allowable ranges from the final tableau; GRG Nonlinear reduced gradients and Lagrange multipliers from difference gradients, at a Karush-Kuhn-Tucker point only; Solver Results offers it where it applies (no score change) | +| 2026-11-02 | Floating objects: charts, pictures, shapes and slicers share one selection with a frame of eight resize handles (each moves only its own edges, also on right-to-left sheets); Delete or Backspace deletes the selected object and Escape drops the selection; slicers follow row and column edits and sorts like the other objects; chart series follow cut-moves and sheet renames and deletes; a copied sheet gives its objects fresh ids; `ui.inspect` reports `selectedObject` and `ui.object.select` selects any object (#190, #213) | +| 2026-11-01 | Chart data tables are available from Chart Design › Add Chart Element and Format Chart Area. Tables follow live source values and number formats, keep blank cells blank, offer legend keys and border settings, and survive XLSX save/reopen; the shared renderer includes them in print and PDF. Readiness estimates unchanged. | | 2026-11-01 | XLSX keeps the first visible workbook window's active sheet and display settings together, falling back to the first view when all are hidden. Tab ratios are normalized to 0–1000 on import and export; invalid numeric text uses 600. Synthetic round trips cover isolated attributes, missing views, and active tabs after sheet deletion/reordering; firstSheet remains separate #2264 work (#3057). | | 2026-10-31 | Esc in File › Info, Print or Options first leaves the text field; the next Esc returns to the sheet (#3035) | | 2026-10-31 | CSV and text open detects each column's date order: a value that reads only day first (`31/05/2026`) makes the column day first, a value that reads only month first (`12/31/2026`) makes it month first, an all-ambiguous column keeps month first with a warning, and a column with both kinds stays text with a warning (#2765) | @@ -250,6 +256,12 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Progress log: Python mode in the formula bar | +| 2026-11-02 | minor | Progress log: Python cells as data | +| 2026-11-02 | minor | Progress log: equations (Insert › Equation, the editor, gridcraft-math) | +| 2026-11-02 | minor | What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear (no score change) | +| 2026-11-02 | minor | Progress log: one selection and eight resize handles for every floating object | +| 2026-11-01 | minor | Chart data tables are available from Chart Design › Add Chart Element and Format Chart Area. Tables follow live source values and number formats, keep blank cells blank, offer legend keys and border settings, and survive XLSX save/reopen; the shared renderer includes them in print and PDF. Readiness estimates unchanged. | | 2026-11-01 | trivial | Workbook views: selected window settings stay together, tab ratios are bounded, and regressions cover isolated settings and sheet edits; readiness estimates unchanged (#3057) | | 2026-10-31 | minor | File-page text fields keep the view open when Esc cancels an edit (#3035) | | 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories | diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index eb11045dbd..63ac533def 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -135,6 +135,10 @@ impl Calc { if cell.value == Value::Error(CellError::Circ) { circ.push((si, c)); } + } else if cell.py.is_some() { + // A Python cell lays out its kept result, so it is calculated like a formula + // that reads nothing: its spill is blocked and unblocked like a formula's. + self.graph.insert((si, c), Node { areas: Vec::new(), dynamic: false }); } } } @@ -206,11 +210,29 @@ impl Calc { let mut cleared: Vec<(usize, RangeRef)> = Vec::new(); for &k in changed { let formula = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.formula.clone()); + let py = wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.py.as_ref()); + let python = py.is_some(); + // A Python cell whose result (if any) is not an array spills nothing. + let spills = py.and_then(|p| p.result_value()).is_some_and(|v| matches!(v, Value::Array(_))); match formula.and_then(|f| f.expr()) { Some(e) => { let (areas, dynamic) = precedents(wb, k.0, &e); self.graph.insert(k, Node { areas, dynamic }); } + // See `rebuild`: its spill is laid out again from its result when it is calculated. + None if python => { + self.graph.insert(k, Node { areas: Vec::new(), dynamic: false }); + // New code has no result yet: the spill the cell had (its old result's, or a + // formula's) goes, and what read it is recalculated, as for a formula + // replaced by a constant. + if !spills + && let Some(sh) = wb.sheet_mut(k.0) + && let Some(r) = sh.spill_ranges.remove(&k.1) + { + sh.clear_spill(r); + cleared.push((k.0, r)); + } + } None => { self.graph.remove(k); // A formula replaced by a constant (or cleared) takes its spilled values with it. @@ -338,11 +360,15 @@ impl Calc { exprs.insert(*k, e); } } + let python: HashMap = dirty + .iter() + .filter_map(|k| wb.sheet(k.0).and_then(|s| s.cell(k.1)).and_then(|c| c.py.as_ref()).and_then(|p| p.result_value()).map(|v| (*k, v))) + .collect(); let now = self.now(); let mut rng = self.rng; let tp = prof_now(); let (results, spills, cycles) = { - let mut host = PassHost::new(wb, &exprs, &mut rng, now); + let mut host = PassHost::new(wb, &exprs, &mut rng, now).with_python(python); host.iterate = wb.calc.iterative; for k in &dirty { host.calculate(*k); @@ -547,6 +573,48 @@ pub(crate) mod tests { v } + /// A 1,000 x 1,000 Python result laid out from A1 in a pass, with the same values already + /// spilled on the sheet from the last calculation, as a full recalculation finds them. + fn big_python_spill() -> (Workbook, HashMap) { + let n = 1_000usize; + let data: Vec = (0..n * n).map(|i| Value::Number(i as f64)).collect(); + let array = gridcraft_core::Array::new(n, n, data.clone()).unwrap(); + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + let anchor = CellRef::new(0, 0); + let py = gridcraft_model::PyCode::new("big"); + sh.set_cell(anchor, Cell { value: Value::Number(0.0), py: Some(std::sync::Arc::new(py)), ..Cell::default() }); + let area = RangeRef::new(anchor, CellRef::new(n as u32 - 1, n as u32 - 1)); + sh.spill_ranges.insert(anchor, area); + for (i, c) in area.iter().enumerate().skip(1) { + sh.spill.insert(c, data[i].clone()); + } + let mut python = HashMap::default(); + python.insert((0, anchor), Value::Array(std::sync::Arc::new(array))); + (wb, python) + } + + #[test] + fn a_read_beside_a_large_spill_walks_none_of_it() { + let (wb, python) = big_python_spill(); + let exprs = HashMap::default(); + let mut rng = 1u64; + let mut host = PassHost::new(&wb, &exprs, &mut rng, 0.0).with_python(python); + assert_eq!(host.cell_value(0, CellRef::new(0, 0)), Value::Number(0.0)); + // Beside the spill (column ALM, the 1,001st), over the rows it covers. + let beside = RangeRef::parse("ALM1:ALM1000").unwrap(); + host.spill_visits = 0; + assert!(host.range_values(0, beside).iter().all(Value::is_empty)); + assert!(host.visit_range(0, beside, &mut |_| true), "a disjoint read takes the fast path"); + assert_eq!(host.spill_visits, 0, "nothing of the spill is walked"); + // A read inside it still sees the spilled values, walking only the cells it reads. + let inside = RangeRef::parse("B2:C3").unwrap(); + host.spill_visits = 0; + assert_eq!(host.range_values(0, inside), [1_001.0, 1_002.0, 2_001.0, 2_002.0].map(Value::Number).to_vec()); + assert!(host.spill_visits <= 8, "{}", host.spill_visits); + assert!(!host.visit_range(0, inside, &mut |_| true), "an overlapping read leaves the block to range_values"); + } + #[test] fn intervals_match_a_linear_scan() { let mut iv: Intervals = Intervals::default(); diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 6aa8a1204e..5909369fda 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -45,6 +45,10 @@ pub(super) struct PassHost<'a> { /// Suspensions so far (tests check that a wide read at the limit needs one, not one per cell). #[cfg(test)] pub(super) suspensions: usize, + /// Spilled values looked at by range reads (tests check that a read outside a large spill + /// looks at none of it). + #[cfg(test)] + pub(super) spill_visits: usize, /// The formulas in `cycles`. cycle_seen: HashSet, /// Iterative calculation: a circular reference reads the cell's previous value instead of @@ -64,6 +68,10 @@ pub(super) struct PassHost<'a> { stack_top: usize, /// Whether an evaluation ran past the stack budget since the innermost formula started. out_of_stack: bool, + /// The kept results of the Python cells in the pass: a Python cell isn't evaluated, its + /// result is laid out (an array spills from the cell, as a formula's does). Each one is in + /// `pending` until it is laid out, so a formula that reads it first gets its new value. + python: HashMap, } impl<'a> PassHost<'a> { @@ -87,6 +95,8 @@ impl<'a> PassHost<'a> { also: Vec::new(), #[cfg(test)] suspensions: 0, + #[cfg(test)] + spill_visits: 0, cycle_seen: HashSet::default(), iterate: false, prev: HashMap::default(), @@ -96,8 +106,17 @@ impl<'a> PassHost<'a> { taint: false, stack_top: 0, out_of_stack: false, + python: HashMap::default(), } } + + /// Adds the dirty Python cells of the pass and their kept results: like the formulas, they + /// are pending until laid out, so every read path calculates them before reading them. + pub(super) fn with_python(mut self, python: HashMap) -> Self { + self.pending.extend(python.keys().copied()); + self.python = python; + self + } } /// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet, @@ -111,7 +130,10 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool { let own = sh.spill_ranges.get(&anchor); let spilled_over = |c: CellRef| { !own.is_some_and(|o| o.contains(c)) - && sh.spill_ranges.iter().any(|(o, r)| *o != anchor && r.contains(c) && !host.exprs.contains_key(&(sheet, *o))) + && sh.spill_ranges.iter().any(|(o, r)| { + // A formula or Python cell recalculated in this pass lays its array out again. + *o != anchor && r.contains(c) && !host.exprs.contains_key(&(sheet, *o)) && !host.python.contains_key(&(sheet, *o)) + }) }; end.row >= gridcraft_core::MAX_ROWS || end.col >= gridcraft_core::MAX_COLS @@ -135,6 +157,42 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef, .all(|(i, c)| c == anchor || (!sheet.cells.has(c) && sheet.spill.get(&c) == Some(arr.data.get(i).unwrap_or(&Value::Empty)))) } +/// The area an array anchored at `anchor` covers. +fn array_area(anchor: CellRef, a: &Array) -> RangeRef { + let end = + CellRef::new(anchor.row.saturating_add((a.rows as u32).saturating_sub(1)), anchor.col.saturating_add((a.cols as u32).saturating_sub(1))); + RangeRef::new(anchor, end) +} + +/// The spilled values `sheet` stores inside `range`, passed to `f` until it returns false. Values +/// outside the range are not walked: with fewer rows in the range than spilled values, each row +/// is looked up on its own; otherwise one ordered scan visits each spilled value at most once. +/// Returns how many values were looked at. +fn stored_spill_in<'s>(sheet: &'s gridcraft_model::Sheet, range: RangeRef, f: &mut dyn FnMut(CellRef, &'s Value) -> bool) -> usize { + let mut seen = 0usize; + if sheet.spill.is_empty() { + return 0; + } + if (range.height() as usize) < sheet.spill.len() { + for row in range.start.row..=range.end.row { + for (c, v) in sheet.spill.range(CellRef::new(row, range.start.col)..=CellRef::new(row, range.end.col)) { + seen += 1; + if !f(*c, v) { + return seen; + } + } + } + } else { + for (c, v) in sheet.spill.range(range.start..=range.end) { + seen += 1; + if range.contains(*c) && !f(*c, v) { + return seen; + } + } + } + seen +} + impl PassHost<'_> { /// Calculates `k` (and the formulas it reads) with bounded stack: when [`Self::compute`] would /// go deeper than [`MAX_NESTED`], it suspends what is in progress, the formula it needed is @@ -188,6 +246,9 @@ impl PassHost<'_> { } return v; } + if let Some(result) = self.python.get(&k).cloned() { + return self.python_result(k, result); + } let Some(expr) = self.exprs.get(&k) else { return self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(); }; @@ -305,6 +366,36 @@ impl PassHost<'_> { v } + /// A Python cell's kept result as its value: an array spills from the cell unless it is + /// blocked, malformed or larger than [`gridcraft_model::python::MAX_RESULT_CELLS`] (only a + /// crafted file holds one), which shows `#SPILL!`. + fn python_result(&mut self, k: Key, result: Value) -> Value { + self.pending.remove(&k); + let v = match result { + Value::Array(a) => { + let sane = a.rows >= 1 + && a.cols >= 1 + && a.rows.checked_mul(a.cols).is_some_and(|n| n == a.data.len() && n <= gridcraft_model::python::MAX_RESULT_CELLS); + if sane { + self.spills.insert(k, a.clone()); + a.data.first().cloned().unwrap_or_default() + } else { + Value::Error(CellError::Spill) + } + } + v => v, + }; + let v = match self.spills.get(&k) { + Some(a) if spill_blocked(self, k, a) => { + self.spills.remove(&k); + Value::Error(CellError::Spill) + } + _ => v, + }; + self.results.insert(k, v.clone()); + v + } + /// A formula's previous value for iterative calculation: from the last iteration, else the /// value it shows. Blank, and the `#CIRC!` of a loop calculated with iteration off, are 0. fn previous(&self, k: Key) -> Value { @@ -445,26 +536,29 @@ impl Host for PassHost<'_> { let (h, w) = (range.height() as usize, range.width() as usize); let mut out = vec![Value::Empty; h * w]; let Some(sh) = self.wb.sheet(sheet) else { return out }; - // Sparse walk: only stored cells; formula cells that are (or were) dirty go through - // `compute`, constants are copied straight from the store. + // Sparse walk: only stored cells; formula and Python cells that are (or were) dirty go + // through `compute`, constants are copied straight from the store. let mut formulas: Vec<(usize, CellRef)> = Vec::new(); for (c, cell) in sh.cells.iter_range(range) { let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; - if cell.formula.is_some() { + if cell.formula.is_some() || cell.py.is_some() { formulas.push((i, c)); } else if let Some(slot) = out.get_mut(i) { *slot = cell.value.clone(); } } - for (c, v) in sh.spill.range(range.start..=range.end) { - if range.contains(*c) { - let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; - if let Some(slot) = out.get_mut(i) - && slot.is_empty() - { - *slot = v.clone(); - } + let _seen = stored_spill_in(sh, range, &mut |c, v| { + let i = (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize; + if let Some(slot) = out.get_mut(i) + && slot.is_empty() + { + *slot = v.clone(); } + true + }); + #[cfg(test)] + { + self.spill_visits += _seen; } for (i, c) in formulas { let v = self.cell_value(sheet, c); @@ -473,26 +567,31 @@ impl Host for PassHost<'_> { } } if !self.spills.is_empty() { - let new: Vec<(usize, Value)> = self - .spills - .iter() - .filter(|(a, _)| a.0 == sheet) - .flat_map(|(a, arr)| { - let mut v = Vec::new(); - for r in 0..arr.rows { - for cc in 0..arr.cols { - let c = CellRef::new(a.1.row.saturating_add(r as u32), a.1.col.saturating_add(cc as u32)); - if c != a.1 && range.contains(c) { - v.push(( - (c.row - range.start.row) as usize * w + (c.col - range.start.col) as usize, - arr.get(r, cc).cloned().unwrap_or_default(), - )); - } + // Only the part of each array inside the range is walked: a large array beside a small + // read costs nothing. + let mut new: Vec<(usize, Value)> = Vec::new(); + for (a, arr) in self.spills.iter().filter(|(a, _)| a.0 == sheet) { + let area = array_area(a.1, arr); + if !area.intersects(&range) { + continue; + } + let (r0, r1) = (area.start.row.max(range.start.row), area.end.row.min(range.end.row)); + let (c0, c1) = (area.start.col.max(range.start.col), area.end.col.min(range.end.col)); + for row in r0..=r1 { + for col in c0..=c1 { + let c = CellRef::new(row, col); + if c == a.1 { + continue; } + let v = arr.get((row - a.1.row) as usize, (col - a.1.col) as usize).cloned().unwrap_or_default(); + new.push(((row - range.start.row) as usize * w + (col - range.start.col) as usize, v)); } - v - }) - .collect(); + } + } + #[cfg(test)] + { + self.spill_visits += new.len(); + } // Iterating: an array spilled by a formula that read a previous value. if self.iterate && self.spills.iter().any(|(a, arr)| { @@ -516,21 +615,31 @@ impl Host for PassHost<'_> { fn visit_range(&mut self, sheet: usize, range: RangeRef, f: &mut dyn FnMut(&Value) -> bool) -> bool { let wb = self.wb; let Some(sh) = wb.sheet(sheet) else { return false }; - // Formula cells first, in row-major order like `range_values`: reading one calculates it - // and the pass remembers the value, so the walk below gets the same value again without - // this method holding any. + // Formula and Python cells first, in row-major order like `range_values`: reading one + // calculates it (a Python cell lays out its result) and the pass remembers the value, so + // the walk below gets the same value again without this method holding any. for (c, cell) in sh.cells.iter_range(range) { - if cell.formula.is_some() { + if cell.formula.is_some() || cell.py.is_some() { let _ = self.cell_value(sheet, c); } } // Spilled values sit between the stored cells (and the formulas just calculated may have // produced some): leave such blocks to `range_values`. - if self.spills.keys().any(|a| a.0 == sheet) || sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c)) { + let arrays = self.spills.iter().any(|(a, arr)| a.0 == sheet && array_area(a.1, arr).intersects(&range)); + let mut stored = false; + let _seen = stored_spill_in(sh, range, &mut |_, _| { + stored = true; + false + }); + #[cfg(test)] + { + self.spill_visits += _seen; + } + if arrays || stored { return false; } for (c, cell) in sh.cells.iter_range(range) { - let go = if cell.formula.is_some() { f(&self.cell_value(sheet, c)) } else { f(&cell.value) }; + let go = if cell.formula.is_some() || cell.py.is_some() { f(&self.cell_value(sheet, c)) } else { f(&cell.value) }; if !go { break; } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 89e6e7327e..d635907370 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2312,3 +2312,63 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +/// Makes `at` a Python cell showing `cached` (its value before this calculation), with `result` +/// as its kept result, and returns the cell's key for `Calc::cells_changed`. +fn plant_python(t: &mut T, at: &str, cached: Value, result: Value) -> (usize, CellRef) { + use gridcraft_model::python::{PyCode, PyOutput}; + let output = PyOutput { value: result, type_name: "list".into(), preview: String::new(), convertible: true }; + let py = PyCode { output: Some(output), ..PyCode::new("[5, 6]") }; + let cell = Cell { value: cached, formula: None, style: gridcraft_model::StyleId::default(), py: Some(std::sync::Arc::new(py)) }; + t.wb.sheet_mut(0).unwrap().cells.set(c(at), cell); + (0, c(at)) +} + +fn column(values: &[f64]) -> Value { + let data = values.iter().map(|v| Value::Number(*v)).collect(); + Value::Array(std::sync::Arc::new(gridcraft_core::Array::new(values.len(), 1, data).unwrap())) +} + +#[test] +fn formulas_read_a_dirty_python_cell_after_it_is_laid_out() { + // B1's result can't spill (B2 holds a value), so it is #SPILL!. A1, A2 and A3 come before + // it in the pass; each must lay it out first rather than read its old value, 1. + let build = |t: &mut T| { + t.set("B2", "10"); + t.set("B3", "100"); + t.set("A1", "=B1"); + t.set("A2", "=MAX(B1:B3)"); + t.set("A3", "=SUM(B1:B3)"); + t.set("A4", "=COUNTA(B1:B3)"); + t.set("A5", "=SUMPRODUCT(--ISERROR(B1:B3))"); + }; + let check = |t: &T, how: &str| { + assert_eq!(t.get("B1"), Value::Error(CellError::Spill), "{how}"); + assert_eq!(t.get("A1"), Value::Error(CellError::Spill), "{how}: a reference"); + assert_eq!(t.get("A2"), Value::Error(CellError::Spill), "{how}: a range read"); + assert_eq!(t.get("A3"), Value::Error(CellError::Spill), "{how}: a range walked cell by cell"); + assert_eq!(t.num("A4"), 3.0, "{how}"); + assert_eq!(t.num("A5"), 1.0, "{how}: the error is seen in the range"); + }; + + // A full recalculation. + let mut t = T::new(); + build(&mut t); + plant_python(&mut t, "B1", Value::Number(1.0), column(&[5.0, 6.0])); + t.calc.recalc_all(&mut t.wb); + check(&t, "full"); + + // An incremental one: B1 becomes a Python cell after its readers. + let mut t = T::new(); + t.set("B1", "1"); + build(&mut t); + assert_eq!((t.num("A1"), t.num("A3")), (1.0, 111.0)); + let k = plant_python(&mut t, "B1", Value::Number(1.0), column(&[5.0, 6.0])); + t.calc.cells_changed(&mut t.wb, &[k]); + check(&t, "incremental"); + + // Unblocked, the readers see the new array. + t.set("B2", ""); + assert_eq!((t.num("B1"), t.num("B2")), (5.0, 6.0)); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (5.0, 100.0, 111.0)); +} diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 6a64558a10..7e50e78f62 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -14,6 +14,7 @@ mod frame; mod kinds; mod legend; mod lines; +mod table; mod trend; use cartesian::{cartesian, scatter}; diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index d449498e74..ce0bbebb0a 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -208,7 +208,9 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx // Outer levels padded to the slots (forecast slots stay in the last group). let outer: Vec> = data.category_levels.iter().map(|l| (0..ncat_slots).map(|j| l.get(j).cloned().unwrap_or_default()).collect()).collect(); - let plot = frame(ctx, area, CatAxis::Labels(&labels, &outer), &y1, y2.as_ref(), horizontal, chart.gridlines); + let (area, table) = super::table::reserve(ctx, chart, data, area, ncat_slots); + let category_axis = super::table::category_axis(&table, &labels, &outer); + let plot = frame(ctx, area, category_axis, &y1, y2.as_ref(), horizontal, chart.gridlines); if !plot.ok() { return; } @@ -355,6 +357,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels, (0.5, ncat_slots as f64 + 0.5)); } draw_trend_labels(ctx, plot, &trend_labels); + super::table::draw(ctx, chart, data, plot, table.as_ref()); } // ---------------------------------------------------------------- scatter & bubble diff --git a/crates/chart/src/render/frame.rs b/crates/chart/src/render/frame.rs index 0117423b39..92d8dd9e35 100644 --- a/crates/chart/src/render/frame.rs +++ b/crates/chart/src/render/frame.rs @@ -74,12 +74,14 @@ pub(super) enum CatAxis<'a> { /// Category labels and, for a multi-level axis, the outer levels (nearest the labels first; /// one entry per category, non-empty where a group starts). Labels(&'a [String], &'a [Vec]), + /// A data table supplies the labels below a vertical chart. Its stub must clear the plot. + Table(&'a [String], f32), Numeric(Scale, &'a Fmt), } /// Groups of an outer category level: `(first, end)` index pairs, a group starting at every /// non-empty entry (and at the first category). -fn level_groups(level: &[String], n: usize) -> Vec<(usize, usize)> { +pub(super) fn level_groups(level: &[String], n: usize) -> Vec<(usize, usize)> { let mut starts: Vec = (0..n).filter(|&j| j == 0 || level.get(j).is_some_and(|t| !t.is_empty())).collect(); starts.push(n); starts.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() @@ -101,9 +103,13 @@ pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Opti let ls = LABEL_SIZE; let lh = ls * 1.4; let ylabels = y.labels(); + let stub = match &cat { + CatAxis::Table(_, width) => *width, + _ => 0.0, + }; let maxw = |ctx: &Ctx, l: &[(f64, String)]| l.iter().map(|(_, t)| ctx.tw(t, ls)).fold(0.0f32, f32::max); if !horizontal { - let left = (maxw(ctx, &ylabels) + 6.0).min(area.w * 0.4); + let left = (maxw(ctx, &ylabels) + 6.0).min(area.w * 0.4).max(stub); let y2labels = y2.map(ValAxis::labels); let right = match (&y2labels, &cat) { (Some(l), _) => (maxw(ctx, l) + 6.0).min(area.w * 0.3), @@ -112,7 +118,7 @@ pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Opti }; let levels = match &cat { CatAxis::Labels(_, o) => o.len() as f32, - CatAxis::Numeric(..) => 0.0, + CatAxis::Numeric(..) | CatAxis::Table(..) => 0.0, }; let plot = Bx { x: area.x + left, y: area.y + lh * 0.5, w: area.w - left - right, h: area.h - lh * 1.5 - 4.0 - lh * levels }; if !plot.ok() { @@ -135,6 +141,7 @@ pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Opti let y0 = plot.bottom() - y.scale.frac(zero) * plot.h; ctx.hline(plot.x, plot.right(), y0, AXIS, 0.75); match cat { + CatAxis::Table(..) => {} CatAxis::Labels(l, outer) => { let n = l.len().max(1); let cw = plot.w / n as f32; @@ -181,6 +188,7 @@ pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Opti } else { let (labels, outer): (Vec, &[Vec]) = match cat { CatAxis::Labels(l, o) => (l.to_vec(), o), + CatAxis::Table(l, _) => (l.to_vec(), &[]), CatAxis::Numeric(..) => (vec![], &[]), }; let lw = (labels.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.35); @@ -189,7 +197,8 @@ pub(super) fn frame(ctx: &mut Ctx, area: Bx, cat: CatAxis, y: &ValAxis, y2: Opti outer.iter().map(|l| (l.iter().take(2000).map(|t| ctx.tw(t, ls)).fold(0.0f32, f32::max) + 6.0).min(area.w * 0.15)).collect(); let levels_w: f32 = level_w.iter().sum(); let right = ylabels.last().map(|(_, t)| ctx.tw(t, ls) / 2.0).unwrap_or(0.0).min(area.w * 0.2) + 2.0; - let plot = Bx { x: area.x + lw + levels_w, y: area.y + 2.0, w: area.w - lw - levels_w - right, h: area.h - lh - 6.0 }; + let left = (lw + levels_w).max(stub); + let plot = Bx { x: area.x + left, y: area.y + 2.0, w: area.w - left - right, h: area.h - lh - 6.0 }; if !plot.ok() { return plot; } diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index fec1e4549f..5ddb5a3cd3 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -85,7 +85,7 @@ fn swatch_w(sw: Swatch, s: f32) -> f32 { if sw == Swatch::Box { s } else { s * 2.0 } } -fn draw_swatch(ctx: &mut Ctx, sw: Swatch, x: f32, yc: f32, s: f32, color: Rgba) { +pub(super) fn draw_swatch(ctx: &mut Ctx, sw: Swatch, x: f32, yc: f32, s: f32, color: Rgba) { match sw { Swatch::Box => ctx.rect(x, yc - s / 2.0, s, s, color, None), Swatch::Line => ctx.hline(x, x + 2.0 * s, yc, color, 2.0), diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs new file mode 100644 index 0000000000..f0839dcfef --- /dev/null +++ b/crates/chart/src/render/table.rs @@ -0,0 +1,107 @@ +//! The chart data table uses the same primitives as the plot, including in print/PDF output. + +use super::frame::{Bx, CatAxis, level_groups}; +use super::legend::{Swatch, cat_label, draw_swatch, plot_kind}; +use super::{AXIS, Chart, ChartData, ChartKind, Ctx, Fmt, HAlign, LABEL_SIZE, TEXT, VAlign}; + +pub(super) struct Layout { + top: f32, + row_height: f32, + headers: usize, + stub: f32, + columns: usize, +} + +pub(super) fn category_axis<'a>(layout: &Option, labels: &'a [String], outer: &'a [Vec]) -> CatAxis<'a> { + match layout { + Some(t) => CatAxis::Table(labels, t.stub), + None => CatAxis::Labels(labels, outer), + } +} + +/// Reserve at most half the available height. A table that cannot fit is explicitly labelled +/// instead of dropping rows or allocating a series × point-sized matrix. +pub(super) fn reserve(ctx: &mut Ctx, chart: &Chart, data: &ChartData, mut area: Bx, columns: usize) -> (Bx, Option) { + if chart.data_table.is_none() || !chart.supports_data_table() { + return (area, None); + } + let headers = data.category_levels.len() + 1; + let rows = headers + data.series.len(); + let row_height = LABEL_SIZE * 1.4 + 4.0; + let height = row_height * rows as f32; + let key_width = if chart.data_table.as_ref().is_some_and(|t| t.show_keys) { 22.0 } else { 0.0 }; + let names = data.series.iter().take(32).map(|s| ctx.tw(&s.name, LABEL_SIZE)).fold(0.0f32, f32::max); + let stub = (names + key_width + 10.0).clamp(24.0, (area.w * 0.3).max(24.0)); + if columns == 0 || columns > 128 || data.series.len() > 32 || height > area.h * 0.5 || (area.w * 0.6) / (columns as f32) < 18.0 { + let message = ctx.fit("Data table needs more space", LABEL_SIZE, area.w); + ctx.text(area.cx(), area.bottom(), &message, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Bottom)); + area.h -= row_height; + return (area, None); + } + area.h -= height; + (area, Some(Layout { top: area.bottom(), row_height, headers, stub, columns })) +} + +pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, layout: Option<&Layout>) { + let Some(layout) = layout else { return }; + let Some(settings) = &chart.data_table else { return }; + let x0 = plot.x - layout.stub; + let top = layout.top; + let rows = layout.headers + data.series.len(); + let bottom = top + layout.row_height * rows as f32; + let cw = plot.w / layout.columns as f32; + // Outermost category level first, then the individual categories. + for (i, level) in data.category_levels.iter().rev().enumerate() { + for (first, end) in level_groups(level, layout.columns) { + let text = level.get(first).map(String::as_str).unwrap_or(""); + let text = ctx.fit(text, LABEL_SIZE, (end - first) as f32 * cw - 4.0); + let x = plot.x + (first + end) as f32 * cw / 2.0; + ctx.text(x, top + (i as f32 + 0.5) * layout.row_height, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + } + let header_y = top + (layout.headers as f32 - 0.5) * layout.row_height; + let n = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)); + for j in 0..layout.columns { + let text = if j < n { cat_label(data, j) } else { String::new() }; + let text = ctx.fit(&text, LABEL_SIZE, cw - 4.0); + ctx.text(plot.x + (j as f32 + 0.5) * cw, header_y, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + for (i, series) in data.series.iter().enumerate() { + let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; + let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; + if settings.show_keys { + let swatch = match plot_kind(chart, series) { + ChartKind::Line | ChartKind::LineStacked => Swatch::Line, + ChartKind::LineMarkers => Swatch::LineMarker, + _ => Swatch::Box, + }; + draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color); + } + let name = ctx.fit(&series.name, LABEL_SIZE, plot.x - name_x - 4.0); + ctx.text(name_x, y, &name, LABEL_SIZE, TEXT, (HAlign::Left, VAlign::Middle)); + let fmt = Fmt::new(&series.number_format); + for j in 0..layout.columns { + let value = series.values.get(j).copied().flatten().map(|v| fmt.format(v, None)).unwrap_or_default(); + let text = ctx.fit(&value, LABEL_SIZE, cw - 4.0); + ctx.text(plot.x + (j as f32 + 0.5) * cw, y, &text, LABEL_SIZE, TEXT, (HAlign::Center, VAlign::Middle)); + } + } + if settings.horizontal_border { + for row in 1..rows { + ctx.hline(x0, plot.right(), top + row as f32 * layout.row_height, AXIS, 0.75); + } + } + if settings.vertical_border { + ctx.vline(plot.x, top, bottom, AXIS, 0.75); + // The outer headers span groups; category dividers begin at the innermost header. + for j in 1..layout.columns { + ctx.vline(plot.x + j as f32 * cw, top + (layout.headers - 1) as f32 * layout.row_height, bottom, AXIS, 0.75); + } + } + if settings.outline { + ctx.hline(x0, plot.right(), top, AXIS, 0.75); + ctx.hline(x0, plot.right(), bottom, AXIS, 0.75); + ctx.vline(x0, top, bottom, AXIS, 0.75); + ctx.vline(plot.right(), top, bottom, AXIS, 0.75); + } +} diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 3f1a068a23..46d047afc8 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -5,6 +5,8 @@ use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, Sparkl use crate::*; +mod data_table; + const ALL_KINDS: [ChartKind; 26] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, @@ -43,6 +45,7 @@ fn chart(kind: ChartKind) -> Chart { series: vec![], legend: LegendPos::Bottom, data_labels: true, + data_table: None, gridlines: true, style: 0, x_title: Some("Quarter".into()), diff --git a/crates/chart/src/tests/data_table.rs b/crates/chart/src/tests/data_table.rs new file mode 100644 index 0000000000..13e2baf6c9 --- /dev/null +++ b/crates/chart/src/tests/data_table.rs @@ -0,0 +1,121 @@ +use super::*; +use gridcraft_model::ChartDataTable; + +#[test] +fn tables_draw_source_values_for_every_supported_chart_kind() { + for kind in ALL_KINDS { + let mut c = chart(kind); + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let supported = c.supports_data_table(); + let d = sample(kind); + let prims = render(&c, &d, 900.0, 500.0, &ApproxMeasure); + assert_sane(&prims, 900.0, 500.0); + let labels = texts(&prims); + // Source amounts, including on 100% stacked charts, not shares or running totals. + if supported { + for value in ["$12,000", "-$4,000", "$38,000", "$61,870"] { + assert!(labels.contains(&value), "{kind:?}: missing {value}"); + } + } else { + c.data_table = None; + assert_eq!(prims, render(&c, &d, 900.0, 500.0, &ApproxMeasure)); + } + } +} + +#[test] +fn table_columns_align_with_plot_and_keep_missing_values_blank() { + let mut c = chart(ChartKind::ColumnClustered); + c.title = Some(String::new()); + c.x_title = None; + c.y_title = None; + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let color = [1, 2, 3, 255]; + let mut s = series("Rate", &[0.25, 0.0, 0.75], color, c.kind); + s.values[1] = None; + s.number_format = "0.0%".into(); + let d = ChartData { categories: ["Jan", "Feb", "Mar"].map(String::from).to_vec(), series: vec![s], ..Default::default() }; + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + let at = |text: &str| -> (f32, f32) { + p.iter() + .find_map(|p| match p { + Prim::Text { text: t, x, y, .. } if t == text => Some((*x, *y)), + _ => None, + }) + .unwrap() + }; + let (x1, y1) = at("25.0%"); + let (x3, y3) = at("75.0%"); + let header_y = at("Jan").1; + assert!(y1 > header_y && (y1 - y3).abs() < 0.01); + assert_eq!(at("Jan").0, x1); + assert_eq!(at("Mar").0, x3); + assert_eq!(texts(&p).iter().filter(|t| **t == "Jan").count(), 1, "the table replaces category-axis labels"); + let centers: Vec = p + .iter() + .filter_map(|p| match p { + Prim::Rect { x, y, w, fill: Some(f), .. } if *f == color && *y < header_y => Some(x + w / 2.0), + _ => None, + }) + .collect(); + assert_eq!(centers.len(), 2); + assert!((centers[0] - x1).abs() < 0.01 && (centers[1] - x3).abs() < 0.01); + let cells: Vec<&str> = p + .iter() + .filter_map(|p| match p { + Prim::Text { y, text, .. } if (*y - y1).abs() < 0.01 => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(cells, ["Rate", "25.0%", "75.0%"], "blank cells are not zeroes"); + assert!( + p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y)), + "legend key independent of hidden chart legend" + ); + c.data_table = Some(ChartDataTable { show_keys: false, ..Default::default() }); + let off = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + assert!(!off.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y))); +} + +#[test] +fn table_borders_are_independent_and_multilevel_headers_are_kept() { + let mut c = chart(ChartKind::Line); + c.legend = LegendPos::None; + c.data_labels = false; + let mut d = sample(c.kind); + d.category_levels = vec![vec!["2025".into(), "".into(), "".into(), "2026".into(), "".into(), "".into()]]; + for (h, v, outline, want) in [(false, false, false, 0), (true, false, false, 4), (false, true, false, 6), (false, false, true, 4)] { + c.data_table = Some(ChartDataTable { horizontal_border: h, vertical_border: v, outline, show_keys: false }); + let p = render(&c, &d, 900.0, 600.0, &ApproxMeasure); + let year_y = p + .iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == "2025" => Some(*y), + _ => None, + }) + .unwrap(); + assert!(texts(&p).contains(&"2026")); + let lines = p.iter().filter(|p| matches!(p, Prim::Line { pts, .. } if pts.iter().all(|p| p[1] > year_y - 9.0))).count(); + assert_eq!(lines, want, "{h} {v} {outline}"); + assert_sane(&p, 900.0, 600.0); + } +} + +#[test] +fn dense_and_tiny_tables_are_bounded_and_explicit() { + let mut c = chart(ChartKind::ColumnClustered); + c.data_table = Some(ChartDataTable::default()); + let mut d = sample(c.kind); + d.categories = (0..20_000).map(|i| i.to_string()).collect(); + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + assert!(texts(&p).contains(&"Data table needs more space")); + assert_sane(&p, 600.0, 400.0); + d.categories.clear(); + for (w, h) in [(1.0, 1.0), (10.0, 10.0), (40.0, 35.0), (200.0, 100.0)] { + assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h); + } +} diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 46721bedab..0000028e93 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -21,10 +21,18 @@ pub enum CellError { Calc, /// Circular reference that could not be resolved (shown as 0 by Excel; we keep it explicit). Circ, + /// A Python cell's code raised an error, or Python stopped. + Python, + /// A Python cell is waiting to run. + Busy, + /// A Python cell ran longer than the time limit. + Timeout, + /// Python can't run here: the workbook's content isn't enabled, or this build has no Python. + Blocked, } impl CellError { - pub const ALL: [CellError; 10] = [ + pub const ALL: [CellError; 14] = [ CellError::Null, CellError::Div0, CellError::Value, @@ -35,6 +43,10 @@ impl CellError { CellError::GettingData, CellError::Spill, CellError::Calc, + CellError::Python, + CellError::Busy, + CellError::Timeout, + CellError::Blocked, ]; pub fn as_str(&self) -> &'static str { match self { @@ -49,9 +61,16 @@ impl CellError { CellError::Spill => "#SPILL!", CellError::Calc => "#CALC!", CellError::Circ => "#CIRC!", + CellError::Python => "#PYTHON!", + CellError::Busy => "#BUSY!", + CellError::Timeout => "#TIMEOUT!", + CellError::Blocked => "#BLOCKED!", } } - /// `ERROR.TYPE` number. + /// `ERROR.TYPE` number. Microsoft documents 1 to 8; 9 (#SPILL!), 11 (#BLOCKED!) and 14 (#CALC!) + /// are the numbers Excel returns. Microsoft documents no number for #PYTHON!, #BUSY! or + /// #TIMEOUT!: 19, 20 and 21 are GridCraft's own choice, after the numbers Excel is known to use, + /// and may change if Excel's numbers become known. pub fn code(&self) -> u32 { match self { CellError::Null => 1, @@ -65,6 +84,10 @@ impl CellError { CellError::Spill => 9, CellError::Calc => 14, CellError::Circ => 15, + CellError::Blocked => 11, + CellError::Python => 19, + CellError::Busy => 20, + CellError::Timeout => 21, } } pub fn parse(s: &str) -> Option { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 1de94c60c8..341d1b35c0 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -23,6 +23,7 @@ log = { workspace = true } gridcraft-xlsx = { workspace = true } gridcraft-chart = { workspace = true } gridcraft-pdf = { workspace = true } +gridcraft-math = { workspace = true } image = { workspace = true } [dev-dependencies] diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index be1a28f4d9..77fbb1d7ac 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -5,6 +5,7 @@ pub mod analysis; pub mod data; pub mod draw; pub mod edit; +pub mod equation; pub mod extra; pub mod file; pub mod forecast; @@ -15,6 +16,7 @@ pub mod inspect; pub mod macros; pub mod pivot; pub mod print; +pub mod python; pub mod review; pub mod sheet; pub mod slicer; @@ -40,7 +42,11 @@ pub struct CommandSpec { pub label: &'static str, /// Ribbon/menu placement, e.g. `["Home", "Font"]`. Empty = not in menus. pub menu: &'static [&'static str], + /// Portable notation: `Cmd` is ⌘ on macOS and Ctrl elsewhere. pub shortcut: Option<&'static str>, + /// macOS override when its key differs. Equal to `shortcut` marks a Mac-only shortcut + /// (Align Left/Center): other platforms show none. See [`CommandInfo::shortcut_for_platform`]. + pub shortcut_mac: Option<&'static str>, pub params: &'static str, pub enabled: Enabled, pub run: Run, @@ -54,12 +60,32 @@ pub struct CommandInfo { pub label: &'static str, pub menu: Vec<&'static str>, pub shortcut: Option<&'static str>, + pub shortcut_mac: Option<&'static str>, pub params: &'static str, pub enabled: bool, #[serde(skip_serializing_if = "Option::is_none")] pub disabled_reason: Option, } +impl CommandInfo { + /// Format the portable shortcut notation for the runtime operating system. + pub fn shortcut_for_platform(&self, mac: bool) -> Option { + let keys = if mac { + self.shortcut_mac.or(self.shortcut) + } else if self.shortcut_mac.is_some() && self.shortcut_mac == self.shortcut { + // An identical Mac override marks a Mac-only display shortcut. + // The portable field remains unchanged for legacy CLI consumers. + None + } else { + self.shortcut + }?; + if mac { + return Some(keys.to_owned()); + } + Some(keys.split('+').map(|part| if part == "Cmd" { "Ctrl" } else { part }).collect::>().join("+")) + } +} + impl CommandSpec { pub fn info(&self, s: &Session) -> CommandInfo { let e = (self.enabled)(s); @@ -68,6 +94,7 @@ impl CommandSpec { label: self.label, menu: self.menu.to_vec(), shortcut: self.shortcut, + shortcut_mac: self.shortcut_mac, params: self.params, enabled: e.is_ok(), disabled_reason: e.err(), @@ -118,13 +145,13 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> { macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: true } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: true, undoable: true } }; (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: false, undoable: false } }; (noundo $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, undoable: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, shortcut_mac: None, params: $params, enabled: $en, run: $run, journal: true, undoable: false } }; } pub(crate) use cmd; @@ -138,6 +165,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(format::specs()); v.extend(sheet::specs()); v.extend(insert::specs()); + v.extend(equation::specs()); v.extend(data::specs()); v.extend(formulas::specs()); v.extend(review::specs()); @@ -149,6 +177,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(spelling::specs()); v.extend(solver::specs()); v.extend(pivot::specs()); + v.extend(python::specs()); v.extend(slicer::specs()); v.extend(whatif::specs()); v.extend(forecast::specs()); @@ -180,6 +209,7 @@ pub fn register_test_command(id: &'static str, run: Run) { label: id, menu: &[], shortcut: None, + shortcut_mac: None, params: "", enabled: |_| Ok(()), run, @@ -197,6 +227,7 @@ pub(crate) fn register_undoable_test_command(id: &'static str, run: Run) { label: id, menu: &[], shortcut: None, + shortcut_mac: None, params: "", enabled: |_| Ok(()), run, @@ -374,6 +405,9 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) }; let r = f(&mut ctx)?; let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, edits, .. } = ctx; + // Equations whose source changed (or that arrived without a layout, as from a paste) are + // laid out here, so painting only ever reads the cache. + wb.refresh_equations(); if !protection_checked { check_protection(&d.wb, &wb, &d.unlocked_ranges)?; } @@ -490,7 +524,7 @@ fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> { continue; } for c in sh.cells.diff(&after.cells) { - let filled = after.cell(c).is_some_and(|x| x.formula.is_some() || !x.value.is_empty()); + let filled = after.cell(c).is_some_and(gridcraft_model::Cell::has_content); if !filled || !sh.spill.contains_key(&c) || same_content(sh.cell(c), after.cell(c)) { continue; } @@ -506,13 +540,18 @@ fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> { Ok(()) } -/// Two cells hold the same value or formula (formats aside). +/// Two cells hold the same value, formula or Python code (formats aside; a Python cell's result +/// is not something the person edits). fn same_content(a: Option<&gridcraft_model::Cell>, b: Option<&gridcraft_model::Cell>) -> bool { - let empty = |c: Option<&gridcraft_model::Cell>| c.is_none_or(|c| c.formula.is_none() && c.value.is_empty()); + let empty = |c: Option<&gridcraft_model::Cell>| c.is_none_or(|c| !c.has_content()); match (a, b) { (Some(a), Some(b)) => match (&a.formula, &b.formula) { (Some(x), Some(y)) => x.text == y.text && x.array == y.array, - (None, None) => a.value == b.value, + (None, None) => match (&a.py, &b.py) { + (Some(x), Some(y)) => x.code == y.code && x.object == y.object, + (None, None) => a.value == b.value, + _ => false, + }, _ => false, }, _ => empty(a) && empty(b), diff --git a/crates/engine/src/cmd/analysis.rs b/crates/engine/src/cmd/analysis.rs index 9552e95f7f..9cd10e50fb 100644 --- a/crates/engine/src/cmd/analysis.rs +++ b/crates/engine/src/cmd/analysis.rs @@ -27,6 +27,14 @@ const MAX_MATRIX_VARS: usize = 256; const MAX_REGRESSORS: usize = 16; /// Most histogram bins. const MAX_BINS: usize = 100_000; +/// Excel's limit on Fourier Analysis input values. +const MAX_FOURIER: usize = 4096; +/// Most numbers Random Number Generation or Sampling writes in one run. +const MAX_RANDOM: usize = 1_000_000; +/// Most trials of a binomial draw, and the farthest Poisson outcome considered. +const MAX_OUTCOMES: f64 = 1_000_000.0; +/// Largest seed: seeds are whole numbers that a JSON number holds exactly. +const MAX_SEED: u64 = (1 << 53) - 1; /// Part of the error a programmatic call gets when the output range already holds data; the /// dialog recognises it and asks before running again with `overwrite: true`. @@ -35,18 +43,24 @@ pub const OVERWRITE_ERROR: &str = "already holds data"; /// (id, label) of every tool, in the order of Excel's Analysis Tools list. pub const TOOLS: &[(&str, &str)] = &[ ("anovaSingle", "Anova: Single Factor"), + ("anovaTwoFactorWith", "Anova: Two-Factor With Replication"), + ("anovaTwoFactorWithout", "Anova: Two-Factor Without Replication"), ("correlation", "Correlation"), ("covariance", "Covariance"), ("descriptive", "Descriptive Statistics"), ("exponentialSmoothing", "Exponential Smoothing"), ("fTest", "F-Test Two-Sample for Variances"), + ("fourierAnalysis", "Fourier Analysis"), ("histogram", "Histogram"), ("movingAverage", "Moving Average"), + ("randomNumberGeneration", "Random Number Generation"), ("rankPercentile", "Rank and Percentile"), ("regression", "Regression"), + ("sampling", "Sampling"), ("tTestPaired", "t-Test: Paired Two Sample for Means"), ("tTestEqual", "t-Test: Two-Sample Assuming Equal Variances"), ("tTestUnequal", "t-Test: Two-Sample Assuming Unequal Variances"), + ("zTest", "z-Test: Two Sample for Means"), ]; pub fn specs() -> Vec { @@ -55,7 +69,7 @@ pub fn specs() -> Vec { "Data Analysis…", ["Data", "Analysis"], None, - "{tool: anovaSingle|correlation|covariance|descriptive|exponentialSmoothing|fTest|histogram|movingAverage|rankPercentile|regression|tTestPaired|tTestEqual|tTestUnequal (or the tool's label), output?: \"E1\" (top-left of the report; default a new sheet), newSheet?: name, outputTo?: range|newSheet (picks between the two), overwrite?: bool (else non-empty output cells are refused), labels?: bool (first row/column holds names), groupedBy?: columns|rows, …tool params} — range tools take `range`; descriptive: summary? (default true), confidence?: 95, kthLargest?, kthSmallest?; histogram: bins?: range (default evenly spaced), pareto?, cumulative?; regression: inputY, inputX, constantZero?, confidence?: 95, residuals?, standardizedResiduals?, normalProbability?; movingAverage: interval? (3), standardErrors?; exponentialSmoothing: damping? (0.3), standardErrors?; t-tests and fTest: range1, range2, alpha? (0.05), hypothesizedDifference? (0); anovaSingle: alpha?. Writes static values. No `tool` → {tools} (the menu opens the dialog).", + "{tool: anovaSingle|anovaTwoFactorWith|anovaTwoFactorWithout|correlation|covariance|descriptive|exponentialSmoothing|fTest|fourierAnalysis|histogram|movingAverage|randomNumberGeneration|rankPercentile|regression|sampling|tTestPaired|tTestEqual|tTestUnequal|zTest (or the tool's label), output?: \"E1\" (top-left of the report; default a new sheet), newSheet?: name, outputTo?: range|newSheet (picks between the two), overwrite?: bool (else non-empty output cells are refused), labels?: bool (first row/column holds names), groupedBy?: columns|rows, …tool params} — range tools take `range`; descriptive: summary? (default true), confidence?: 95, kthLargest?, kthSmallest?; histogram: bins?: range (default evenly spaced), pareto?, cumulative?; regression: inputY, inputX, constantZero?, confidence?: 95, residuals?, standardizedResiduals?, normalProbability?; movingAverage: interval? (3), standardErrors?; exponentialSmoothing: damping? (0.3), standardErrors?; t-tests and fTest: range1, range2, alpha? (0.05), hypothesizedDifference? (0); anovaSingle: alpha?; anovaTwoFactorWithout: range, labels? (the first row holds column names and the first column row names), alpha?; anovaTwoFactorWith: range (first row and column hold labels), rowsPerSample, alpha?; zTest: range1, range2, variance1, variance2 (known variances), alpha?, hypothesizedDifference?; fourierAnalysis: range (one row or column of 2^k numbers or complex text, at most 4096), inverse?; randomNumberGeneration: variables? (1), count (per variable; not for patterned), distribution: uniform{from, to} | normal{mean, standardDeviation} | bernoulli{p} | binomial{p, trials} | poisson{lambda} | patterned{from, to, step, repeatEach, repeatSequence} | discrete{valueRange: two columns of value and probability}, seed? (whole number, not for patterned; the same seed repeats the numbers; the result reports the seed used), at most 1,000,000 numbers; sampling: range, method?: periodic|random, period (periodic), samples (random, with replacement), seed?. Writes static values. No `tool` → {tools} (the menu opens the dialog).", has_doc, run )] @@ -107,7 +121,7 @@ fn confidence(p: &Json, key: &str) -> Result> { } fn alpha(p: &Json) -> Result { - match num(p, "alpha") { + match opt_num(p, "alpha")? { None => Ok(0.05), Some(a) if a > 0.0 && a < 1.0 => Ok(a), Some(_) => Err(bad(CMD, "alpha must be between 0 and 1")), @@ -1050,6 +1064,684 @@ fn anova_single(s: &Session, p: &Json) -> Result { Ok(g) } +// ---------------------------------------------------------------- two-factor anova and z-test + +/// Count, Sum, Average and Variance of a group, as the Anova summaries list them. +fn group_summary(x: &[f64]) -> [Value; 4] { + [Value::number(x.len() as f64), Value::number(x.iter().sum()), n_or_div0(mean(x)), n_or_div0(var_s(x))] +} + +const ANOVA_HEAD: [&str; 7] = ["Source of Variation", "SS", "df", "MS", "F", "P-value", "F crit"]; + +/// One line of an Anova table. A factor line, tested against the error term `err` (its MS and +/// df), adds F, the P-value and the critical F. +fn anova_line(g: &mut Grid, row: u32, label: &str, ss: f64, df: f64, err: Option<(f64, f64)>, alpha: f64) { + g.txt(row, 0, label); + g.num(row, 1, ss); + g.num(row, 2, df); + g.put(row, 3, ratio(ss, df)); + if let Some((mse, dfe)) = err { + let f = ss / df / mse; + g.put(row, 4, n_or_div0(f)); + g.put(row, 5, if f.is_finite() && dfe > 0.0 { callf("F.DIST.RT", &[f, df, dfe]) } else { div0() }); + g.put(row, 6, if df > 0.0 && dfe > 0.0 { callf("F.INV.RT", &[alpha, df, dfe]) } else { div0() }); + } +} + +/// The cells of a two-factor input range, row by row. +fn input_rows(s: &Session, p: &Json) -> Result>> { + let (si, r) = input_range(s, p, &["range", "input"])?; + Ok(variables(s, si, r, true, false, &|_| String::new())?.into_iter().map(|v| v.vals).collect()) +} + +/// The values of column `j` of a table of numbers. +fn column(data: &[Vec], j: usize) -> Vec { + data.iter().filter_map(|r| r.get(j).copied()).collect() +} + +/// Anova: Two-Factor Without Replication: one observation for each pair of levels (rows × +/// columns), the error term being the residual after both main effects. +fn anova_two_factor_without(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let labels = flag(p, "labels"); + let mut rows = input_rows(s, p)?; + let head = if labels && !rows.is_empty() { Some(rows.remove(0)) } else { None }; + let mut row_names = Vec::with_capacity(rows.len()); + let mut data: Vec> = Vec::with_capacity(rows.len()); + for (i, mut row) in rows.into_iter().enumerate() { + let name = if labels && !row.is_empty() { row.remove(0).display() } else { format!("Row {}", i + 1) }; + row_names.push(name); + data.push(numbers(&row, false)?); + } + let (a, b) = (data.len(), data.first().map_or(0, Vec::len)); + if a < 2 || b < 2 { + return Err(EngineError::Other("Anova needs at least two rows and two columns of numbers.".into())); + } + let col_names: Vec = match head { + Some(h) => h.iter().skip(1).map(Value::display).collect(), + None => (1..=b).map(|j| format!("Column {j}")).collect(), + }; + let cols: Vec> = (0..b).map(|j| column(&data, j)).collect(); + let all: Vec = data.iter().flatten().copied().collect(); + let grand = mean(&all); + let row_means: Vec = data.iter().map(|r| mean(r)).collect(); + let col_means: Vec = cols.iter().map(|c| mean(c)).collect(); + let ss_rows: f64 = row_means.iter().map(|m| b as f64 * (m - grand).powi(2)).sum(); + let ss_cols: f64 = col_means.iter().map(|m| a as f64 * (m - grand).powi(2)).sum(); + // The residual of each observation after removing both main effects. + let ss_err: f64 = + data.iter().zip(&row_means).flat_map(|(r, rm)| r.iter().zip(&col_means).map(move |(x, cm)| (x - rm - cm + grand).powi(2))).sum(); + let (df_rows, df_cols) = ((a - 1) as f64, (b - 1) as f64); + let df_err = df_rows * df_cols; + let mut g = Grid::default(); + g.txt(0, 0, "Anova: Two-Factor Without Replication"); + g.labels(2, 0, &["SUMMARY", "Count", "Sum", "Average", "Variance"]); + let summary = |g: &mut Grid, row: u32, name: &str, x: &[f64]| { + g.txt(row, 0, name); + for (k, v) in group_summary(x).into_iter().enumerate() { + g.put(row, 1 + idx(k), v); + } + }; + for (i, (name, x)) in row_names.iter().zip(&data).enumerate() { + summary(&mut g, 3 + idx(i), name, x); + } + let first_col = 3 + idx(a) + 1; + for (j, (name, x)) in col_names.iter().zip(&cols).enumerate() { + summary(&mut g, first_col + idx(j), name, x); + } + let row = first_col + idx(b) + 2; + g.txt(row, 0, "ANOVA"); + g.labels(row + 1, 0, &ANOVA_HEAD); + let err = Some((ss_err / df_err, df_err)); + anova_line(&mut g, row + 2, "Rows", ss_rows, df_rows, err, alpha); + anova_line(&mut g, row + 3, "Columns", ss_cols, df_cols, err, alpha); + anova_line(&mut g, row + 4, "Error", ss_err, df_err, None, alpha); + g.txt(row + 6, 0, "Total"); + g.num(row + 6, 1, ss(&all)); + g.num(row + 6, 2, (all.len() - 1) as f64); + Ok(g) +} + +/// The number of rows in each sample of a two-factor Anova with replication. +fn rows_per_sample(p: &Json, data_rows: usize) -> Result { + let per = num(p, "rowsPerSample").ok_or_else(|| bad(CMD, "missing `rowsPerSample` (the number of rows in each sample)"))?; + if per < 2.0 || per.fract() != 0.0 || per > data_rows as f64 || !data_rows.is_multiple_of(per as usize) { + return Err(EngineError::Other("Rows per sample must be a whole number of at least 2 that divides the number of data rows.".into())); + } + Ok(per as usize) +} + +/// Anova: Two-Factor With Replication. The input range holds column labels in its first row and +/// sample labels in its first column; each sample (a level of the row factor) spans +/// `rowsPerSample` consecutive rows, so every cell of the design holds that many observations. +fn anova_two_factor_with(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let mut rows = input_rows(s, p)?; + if rows.len() < 3 { + return Err(EngineError::Other("The input range must hold a row of labels and at least two samples.".into())); + } + let head = rows.remove(0); + let col_names: Vec = head.iter().skip(1).map(Value::display).collect(); + let per = rows_per_sample(p, rows.len())?; + let mut sample_names = Vec::new(); + let mut data: Vec> = Vec::with_capacity(rows.len()); + for (i, mut row) in rows.into_iter().enumerate() { + let name = if row.is_empty() { Value::Empty } else { row.remove(0) }; + if i.is_multiple_of(per) { + sample_names.push(name.display()); + } + data.push(numbers(&row, false)?); + } + let (a, b) = (sample_names.len(), col_names.len()); + if a < 2 || b < 2 { + return Err(EngineError::Other("Anova needs at least two samples and two columns of numbers.".into())); + } + // cells[i][j]: the observations of sample i in column j. + let cells: Vec>> = data.chunks(per).map(|block| (0..b).map(|j| column(block, j)).collect()).collect(); + let all: Vec = data.iter().flatten().copied().collect(); + let grand = mean(&all); + let sample_all: Vec> = data.chunks(per).map(|block| block.iter().flatten().copied().collect()).collect(); + let cols: Vec> = (0..b).map(|j| column(&data, j)).collect(); + let (sm, cm): (Vec, Vec) = (sample_all.iter().map(|x| mean(x)).collect(), cols.iter().map(|x| mean(x)).collect()); + let n = per as f64; + let ss_sample: f64 = sm.iter().map(|m| n * b as f64 * (m - grand).powi(2)).sum(); + let ss_cols: f64 = cm.iter().map(|m| n * a as f64 * (m - grand).powi(2)).sum(); + let mut ss_inter = 0.0; + let mut ss_within = 0.0; + for (i, row) in cells.iter().enumerate() { + for (j, cell) in row.iter().enumerate() { + let (si, cj) = (sm.get(i).copied().unwrap_or(f64::NAN), cm.get(j).copied().unwrap_or(f64::NAN)); + ss_inter += n * (mean(cell) - si - cj + grand).powi(2); + ss_within += ss(cell); + } + } + let (df_sample, df_cols) = ((a - 1) as f64, (b - 1) as f64); + let df_within = (a * b * (per - 1)) as f64; + let mut g = Grid::default(); + g.txt(0, 0, "Anova: Two-Factor With Replication"); + g.txt(2, 0, "SUMMARY"); + for (j, name) in col_names.iter().enumerate() { + g.txt(2, 1 + idx(j), name); + } + g.txt(2, 1 + idx(b), "Total"); + let stats = ["Count", "Sum", "Average", "Variance"]; + let mut row = 3u32; + let block = |g: &mut Grid, row: &mut u32, name: &str, groups: Vec<&[f64]>| { + g.txt(*row, 0, name); + let sums: Vec<[Value; 4]> = groups.iter().map(|x| group_summary(x)).collect(); + for (k, label) in stats.iter().enumerate() { + let r = *row + 1 + idx(k); + g.txt(r, 0, label); + for (j, sm) in sums.iter().enumerate() { + g.put(r, 1 + idx(j), sm.get(k).cloned().unwrap_or(Value::Empty)); + } + } + *row += 6; + }; + for ((name, row_cells), whole) in sample_names.iter().zip(&cells).zip(&sample_all) { + let mut groups: Vec<&[f64]> = row_cells.iter().map(Vec::as_slice).collect(); + groups.push(whole); + block(&mut g, &mut row, name, groups); + } + block(&mut g, &mut row, "Total", cols.iter().map(Vec::as_slice).collect()); + row += 1; + g.txt(row, 0, "ANOVA"); + g.labels(row + 1, 0, &ANOVA_HEAD); + let err = Some((ss_within / df_within, df_within)); + anova_line(&mut g, row + 2, "Sample", ss_sample, df_sample, err, alpha); + anova_line(&mut g, row + 3, "Columns", ss_cols, df_cols, err, alpha); + anova_line(&mut g, row + 4, "Interaction", ss_inter, df_sample * df_cols, err, alpha); + anova_line(&mut g, row + 5, "Within", ss_within, df_within, None, alpha); + g.txt(row + 7, 0, "Total"); + g.num(row + 7, 1, ss(&all)); + g.num(row + 7, 2, (all.len() - 1) as f64); + Ok(g) +} + +/// A known variance parameter: a positive number. +fn known_variance(p: &Json, key: &str) -> Result { + match num(p, key) { + Some(v) if v > 0.0 => Ok(v), + _ => Err(EngineError::Other(format!("Enter the known variance `{key}` (a positive number)."))), + } +} + +/// z-Test: Two Sample for Means, for two samples whose population variances are known. +fn z_test(s: &Session, p: &Json) -> Result { + let alpha = alpha(p)?; + let hmd = match opt_num(p, "hypothesizedDifference")? { + Some(d) => d, + None => num_or(p, "difference", 0.0)?, + }; + let (v1, v2) = (known_variance(p, "variance1")?, known_variance(p, "variance2")?); + let a = single(s, p, "range1", "Variable 1")?; + let b = single(s, p, "range2", "Variable 2")?; + let (x, y) = (numbers(&a.vals, true)?, numbers(&b.vals, true)?); + if x.is_empty() || y.is_empty() { + return Err(EngineError::Other("Each input range needs at least one number.".into())); + } + let (n1, n2) = (x.len() as f64, y.len() as f64); + let (m1, m2) = (mean(&x), mean(&y)); + let z = (m1 - m2 - hmd) / (v1 / n1 + v2 / n2).sqrt(); + let mut g = Grid::default(); + let row = test_head(&mut g, "z-Test: Two Sample for Means", &a.name, &b.name); + pair_row(&mut g, row, "Mean", Value::number(m1), Value::number(m2)); + pair_row(&mut g, row + 1, "Known Variance", Value::number(v1), Value::number(v2)); + pair_row(&mut g, row + 2, "Observations", Value::number(n1), Value::number(n2)); + pair_row(&mut g, row + 3, "Hypothesized Mean Difference", Value::number(hmd), Value::Empty); + pair_row(&mut g, row + 4, "z", n_or_div0(z), Value::Empty); + // The tail beyond |z|: 1 − Φ(|z|). + let tail = call("NORM.S.DIST", &[Value::Number(z.abs()), Value::Bool(true)]).as_f64().map(|c| 1.0 - c); + let lines: [(&str, Value); 4] = [ + ("P(Z<=z) one-tail", tail.map_or_else(div0, Value::number)), + ("z Critical one-tail", callf("NORM.S.INV", &[1.0 - alpha])), + ("P(Z<=z) two-tail", tail.map_or_else(div0, |t| Value::number(2.0 * t))), + ("z Critical two-tail", callf("NORM.S.INV", &[1.0 - alpha / 2.0])), + ]; + for (k, (label, v)) in lines.into_iter().enumerate() { + pair_row(&mut g, row + 5 + idx(k), label, v, Value::Empty); + } + Ok(g) +} + +// ---------------------------------------------------------------- fourier analysis + +/// Radix-2 fast Fourier transform (iterative Cooley–Tukey) in place, for a power-of-two number of +/// complex values (re, im). The forward transform is unscaled, X[k] = Σ x[n]·e^(−2πikn/N); the +/// inverse uses e^(+2πikn/N) and divides by N, so it returns the values the forward one took. +fn fft(a: &mut [(f64, f64)], inverse: bool) { + let n = a.len(); + if n < 2 || !n.is_power_of_two() { + return; + } + let bits = n.trailing_zeros(); + for i in 0..n { + let j = i.reverse_bits() >> (usize::BITS - bits); + if i < j { + a.swap(i, j); + } + } + let sign = if inverse { 1.0 } else { -1.0 }; + let mut len = 2; + while len <= n { + let ang = sign * 2.0 * std::f64::consts::PI / len as f64; + for start in (0..n).step_by(len) { + for k in 0..len / 2 { + // Each twiddle factor is computed directly, not by repeated multiplication. + let (wr, wi) = ((ang * k as f64).cos(), (ang * k as f64).sin()); + let (i, j) = (start + k, start + k + len / 2); + let (Some(&(ur, ui)), Some(&(xr, xi))) = (a.get(i), a.get(j)) else { continue }; + let (vr, vi) = (xr * wr - xi * wi, xr * wi + xi * wr); + if let Some(u) = a.get_mut(i) { + *u = (ur + vr, ui + vi); + } + if let Some(x) = a.get_mut(j) { + *x = (ur - vr, ui - vi); + } + } + } + len <<= 1; + } + if inverse { + let nf = n as f64; + a.iter_mut().for_each(|v| *v = (v.0 / nf, v.1 / nf)); + } +} + +/// Fourier Analysis: the discrete Fourier transform (or with `inverse` its inverse) of one row or +/// column of 2^k values, read and written as complex numbers the way IMREAL, IMAGINARY and +/// COMPLEX read and write them. +fn fourier_analysis(s: &Session, p: &Json) -> Result { + let v = single(s, p, "range", "")?; + let n = v.vals.len(); + if n == 0 || n > MAX_FOURIER || !n.is_power_of_two() { + return Err(EngineError::Other(format!("Fourier Analysis needs 1, 2, 4, 8 … {MAX_FOURIER} input values (a power of two)."))); + } + let mut a = Vec::with_capacity(n); + for x in &v.vals { + let part = |f: &str| call(f, std::slice::from_ref(x)).as_f64(); + match (x, part("IMREAL"), part("IMAGINARY")) { + (Value::Empty, ..) => return Err(non_numeric()), + (_, Some(re), Some(im)) => a.push((re, im)), + _ => return Err(EngineError::Other("Input range must hold numbers or complex numbers such as 3+4i.".into())), + } + } + let total: f64 = a.iter().map(|(re, im)| re.abs() + im.abs()).sum(); + let inverse = flag(p, "inverse"); + fft(&mut a, inverse); + // Parts that can only be rounding noise of the transform are written as 0. Each of the + // log2(N) butterfly stages adds at most a few units of f64::EPSILON times the magnitude of + // the values it combines, so the computed transform differs from the exact one by at most + // about log2(N) · ε · Σ|x_n| times a small constant (Higham, Accuracy and Stability of + // Numerical Algorithms, 2nd ed., chapter 24, The Fast Fourier Transform). The bound comes + // from the input and N, never from the largest output, so a small part beside a large one + // (an imaginary part of 1 beside a real part of 1e14, a harmonic of 4e-7 beside a DC term of + // 8e6) is kept. With N = 1 the transform is the identity and log2(N) = 0: nothing is zeroed. + // The inverse divides its outputs by N, so its noise is divided by N as well. An input sum + // that overflows gives no finite bound; then nothing is cleaned up. + let mut noise = 8.0 * f64::EPSILON * f64::from(n.trailing_zeros()) * total; + if inverse { + noise /= n as f64; + } + let noise = if noise.is_finite() { noise } else { 0.0 }; + let clean = |x: f64| if x.abs() <= noise { 0.0 } else { x }; + let mut g = Grid::default(); + let first = u32::from(flag(p, "labels")); + if first == 1 { + g.txt(0, 0, &v.name); + } + for (i, (re, im)) in a.into_iter().enumerate() { + g.put(first + idx(i), 0, callf("COMPLEX", &[clean(re), clean(im)])); + } + Ok(g) +} + +// ---------------------------------------------------------------- random numbers and sampling + +/// A seeded generator: xoshiro256** (Blackman and Vigna, a public-domain algorithm) with its +/// state filled by SplitMix64. The same seed gives the same numbers in GridCraft; they are not +/// Excel's numbers, whose generator is not documented. +struct Rng([u64; 4]); + +impl Rng { + fn new(seed: u64) -> Rng { + let mut x = seed; + let mut next = || { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = x; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + }; + Rng([next(), next(), next(), next()]) + } + + fn next_u64(&mut self) -> u64 { + let [s0, s1, s2, s3] = self.0; + let out = s1.wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let (s2, s3) = (s2 ^ s0, s3 ^ s1); + self.0 = [s0 ^ s3, s1 ^ s2, s2 ^ (s1 << 17), s3.rotate_left(45)]; + out + } + + /// Uniform in [0, 1), with 53 random bits. + fn uniform(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } + + /// Uniform whole number in [0, n), without modulo bias. + fn below(&mut self, n: u64) -> u64 { + if n <= 1 { + return 0; + } + let zone = u64::MAX - u64::MAX % n; + loop { + let v = self.next_u64(); + if v < zone { + return v % n; + } + } + } + + /// Standard normal by the Box–Muller transform. + fn normal(&mut self) -> f64 { + let (u1, u2) = (1.0 - self.uniform(), self.uniform()); + (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos() + } +} + +/// The `seed` parameter, or a seed taken from the clock when there is none. +fn seed_of(p: &Json) -> Result { + let given = p.get("seed").is_some_and(|v| match v { + Json::Null => false, + Json::String(t) => !t.trim().is_empty(), + _ => true, + }); + if !given { + let ms = gridcraft_core::date::unix_now_ms().unwrap_or(0.0); + return Ok((ms * 1000.0) as u64 & MAX_SEED); + } + match num(p, "seed") { + Some(x) if x >= 0.0 && x.fract() == 0.0 && x <= MAX_SEED as f64 => Ok(x as u64), + _ => Err(EngineError::Other("The random seed must be a whole number from 0.".into())), + } +} + +/// A number parameter: `None` when absent, null or blank; an error when present but not a +/// finite number (a typed "0,3" or "abc" must not quietly become the default). +fn opt_num(p: &Json, key: &str) -> Result> { + match p.get(key) { + None | Some(Json::Null) => Ok(None), + Some(Json::String(t)) if t.trim().is_empty() => Ok(None), + Some(_) => num(p, key).map(Some).ok_or_else(|| EngineError::Other(format!("`{key}` must be a number."))), + } +} + +/// A number parameter, `default` when absent or blank. +fn num_or(p: &Json, key: &str, default: f64) -> Result { + Ok(opt_num(p, key)?.unwrap_or(default)) +} + +/// A whole-number parameter of at least `min`, `default` when absent. +fn whole(p: &Json, key: &str, default: Option, min: f64) -> Result { + match opt_num(p, key)?.or(default) { + Some(x) if x >= min && x.fract() == 0.0 => Ok(x), + Some(_) => Err(EngineError::Other(format!("`{key}` must be a whole number of at least {min}."))), + None => Err(bad(CMD, format!("missing `{key}`"))), + } +} + +/// A probability parameter in [0, 1]. +fn probability(p: &Json) -> Result { + match num_or(p, "p", 0.5)? { + x if (0.0..=1.0).contains(&x) => Ok(x), + _ => Err(EngineError::Other("The p value must be between 0 and 1.".into())), + } +} + +/// The probabilities of a distribution on 0, 1, 2 … `last`, as (first outcome, probabilities of +/// first, first + 1, …), from its probability `at_mode` at `mode`, its most likely outcome, and +/// `ratio`(k) = pmf(k + 1) / pmf(k). Each term is one multiplication of its neighbour towards the +/// mode, so no worksheet function runs per outcome, and the terms only shrink away from the mode, +/// so nothing underflows before the terms that matter. The left tail ends where its terms vanish, +/// the right tail once the cumulative probability reaches 1 within f64 resolution (every later +/// draw would map to the last outcome). The table is as wide as the distribution's effective +/// support, not as `last`: Binomial(1,000,000, 0.5) takes about 23,000 entries, not 1,000,001. +fn pmf_table(last: f64, mode: f64, at_mode: f64, ratio: impl Fn(f64) -> f64) -> Result<(f64, Vec)> { + if !at_mode.is_finite() || at_mode <= 0.0 || !(0.0..=last).contains(&mode) || mode.fract() != 0.0 { + return Err(EngineError::Other("The distribution could not be tabulated.".into())); + } + let mut left = Vec::new(); + let (mut k, mut v) = (mode, at_mode); + while k > 0.0 { + v /= ratio(k - 1.0); + if v.is_nan() || v < f64::MIN_POSITIVE { + break; + } + left.push(v); + k -= 1.0; + } + let first = k; + let mut pmf: Vec = left.into_iter().rev().collect(); + let mut acc = pmf.iter().sum::() + at_mode; + pmf.push(at_mode); + let (mut k, mut v) = (mode, at_mode); + while k < last && acc < 1.0 - 1e-15 { + v *= ratio(k); + if v.is_nan() || v < f64::MIN_POSITIVE { + break; + } + pmf.push(v); + acc += v; + k += 1.0; + } + Ok((first, pmf)) +} + +/// A distribution on whole numbers tabulated for inversion sampling: the cumulative +/// probabilities of `first`, `first + 1`, … up to the last outcome that matters. +struct Table { + first: f64, + cdf: Vec, +} + +impl Table { + /// The distribution on 0, 1, 2 … `last` that `pmf_table` describes. + fn from_mode(last: f64, mode: f64, at_mode: f64, ratio: impl Fn(f64) -> f64) -> Result { + let (first, pmf) = pmf_table(last, mode, at_mode, ratio)?; + let mut acc = 0.0; + let cdf = pmf + .into_iter() + .map(|p| { + acc += p; + acc + }) + .collect(); + Ok(Table { first, cdf }) + } + + /// All the probability on one outcome. + fn point(value: f64) -> Table { + Table { first: value, cdf: vec![1.0] } + } + + /// A draw: the first outcome whose cumulative probability exceeds a uniform number (inversion). + fn draw(&self, r: &mut Rng) -> f64 { + let u = r.uniform() * self.cdf.last().copied().unwrap_or(1.0); + self.first + self.cdf.partition_point(|c| *c <= u).min(self.cdf.len().saturating_sub(1)) as f64 + } +} + +/// The numbers of a patterned sequence: `from` to `to` in steps, each number repeated, the whole +/// sequence repeated. +fn pattern(p: &Json) -> Result> { + let (from, to, step) = (num_or(p, "from", 1.0)?, num_or(p, "to", 1.0)?, num_or(p, "step", 1.0)?); + let (each, times) = (whole(p, "repeatEach", Some(1.0), 1.0)?, whole(p, "repeatSequence", Some(1.0), 1.0)?); + if step <= 0.0 || to < from { + return Err(EngineError::Other("The pattern must run from a smaller number to a larger one in positive steps.".into())); + } + let steps = ((to - from) / step + 1e-9).floor() + 1.0; + if steps * each * times > MAX_RANDOM as f64 { + return Err(EngineError::Other(format!("Random Number Generation writes at most {MAX_RANDOM} numbers."))); + } + let base: Vec = (0..steps as usize).map(|k| from + step * k as f64).collect(); + let one: Vec = base.iter().flat_map(|v| std::iter::repeat_n(*v, each as usize)).collect(); + Ok(one.repeat(times as usize)) +} + +/// Random Number Generation: `count` numbers from a distribution in each of `variables` +/// columns, drawn row by row. +fn random_numbers(s: &Session, p: &Json, seed: u64) -> Result { + let vars = whole(p, "variables", Some(1.0), 1.0)?; + let dist = text(p, &["distribution"]).map(norm).unwrap_or_else(|| "uniform".into()); + let cells = |rows: f64| { + if rows * vars > MAX_RANDOM as f64 { + Err(EngineError::Other(format!("Random Number Generation writes at most {MAX_RANDOM} numbers."))) + } else { + Ok(rows as usize) + } + }; + let mut g = Grid::default(); + let cols = vars as usize; + if dist == "patterned" { + let seq = pattern(p)?; + cells(seq.len() as f64)?; + for (i, x) in seq.iter().enumerate() { + for c in 0..cols { + g.num(idx(i), idx(c), *x); + } + } + return Ok(g); + } + let count = cells(whole(p, "count", None, 1.0)?)?; + let mut draw: Box f64> = match dist.as_str() { + "uniform" => { + let (a, b) = (num_or(p, "from", 0.0)?, num_or(p, "to", 1.0)?); + Box::new(move |r| a + (b - a) * r.uniform()) + } + "normal" => { + let (m, sd) = (num_or(p, "mean", 0.0)?, num_or(p, "standardDeviation", 1.0)?); + if sd < 0.0 { + return Err(EngineError::Other("The standard deviation must not be negative.".into())); + } + Box::new(move |r| m + sd * r.normal()) + } + "bernoulli" => { + let pr = probability(p)?; + Box::new(move |r| if r.uniform() < pr { 1.0 } else { 0.0 }) + } + "binomial" => { + let (pr, n) = (probability(p)?, whole(p, "trials", Some(1.0), 1.0)?); + if n > MAX_OUTCOMES { + return Err(EngineError::Other(format!("The number of trials must be at most {MAX_OUTCOMES}."))); + } + // p = 0 and p = 1 are exact: every draw is 0 or n. Otherwise one BINOM.DIST value at + // the mode ⌊(n + 1)p⌋ anchors pmf(k + 1) = pmf(k) · (n − k)/(k + 1) · p/(1 − p). + let table = if pr == 0.0 { + Table::point(0.0) + } else if pr == 1.0 { + Table::point(n) + } else { + let mode = ((n + 1.0) * pr).floor().min(n); + let at_mode = f64_of(&call("BINOM.DIST", &[Value::Number(mode), Value::Number(n), Value::Number(pr), Value::Bool(false)])); + let odds = pr / (1.0 - pr); + Table::from_mode(n, mode, at_mode, |k| (n - k) / (k + 1.0) * odds)? + }; + Box::new(move |r| table.draw(r)) + } + "poisson" => { + let lambda = num_or(p, "lambda", 1.0)?; + if lambda <= 0.0 || lambda > 100_000.0 { + return Err(EngineError::Other("Lambda must be greater than 0 and at most 100000.".into())); + } + // One POISSON.DIST value at the mode ⌊λ⌋ anchors pmf(k + 1) = pmf(k) · λ/(k + 1). + let last = (lambda + 40.0 * lambda.sqrt() + 100.0).min(MAX_OUTCOMES); + let mode = lambda.floor(); + let at_mode = f64_of(&call("POISSON.DIST", &[Value::Number(mode), Value::Number(lambda), Value::Bool(false)])); + let table = Table::from_mode(last, mode, at_mode, |k| lambda / (k + 1.0))?; + Box::new(move |r| table.draw(r)) + } + "discrete" => { + let (si, r) = input_range(s, p, &["valueRange", "values"])?; + if r.width() != 2 { + return Err(EngineError::Other("The value and probability input range must have two columns.".into())); + } + let v = variables(s, si, r, false, false, &|_| String::new())?; + let (values, probs) = match v.as_slice() { + [a, b] => (numbers(&a.vals, false)?, numbers(&b.vals, false)?), + _ => return Err(non_numeric()), + }; + if probs.iter().any(|x| !(0.0..=1.0).contains(x)) || (probs.iter().sum::() - 1.0).abs() > 1e-9 { + return Err(EngineError::Other("The probabilities must be between 0 and 1 and add up to 1.".into())); + } + let cdf: Vec = probs + .iter() + .scan(0.0, |acc, x| { + *acc += x; + Some(*acc) + }) + .collect(); + let table = Table { first: 0.0, cdf }; + Box::new(move |r| values.get(table.draw(r) as usize).copied().unwrap_or(f64::NAN)) + } + other => return Err(bad(CMD, format!("unknown distribution `{other}`"))), + }; + let mut rng = Rng::new(seed); + for i in 0..count { + for c in 0..cols { + g.num(idx(i), idx(c), draw(&mut rng)); + } + } + Ok(g) +} + +/// Whether Random Number Generation writes a patterned sequence (which uses no seed). +fn patterned(p: &Json) -> bool { + text(p, &["distribution"]).map(norm).is_some_and(|d| d == "patterned") +} + +fn random_sampling(p: &Json) -> bool { + text(p, &["method"]).is_some_and(|m| m.eq_ignore_ascii_case("random")) +} + +/// Sampling: every `period`-th value of the input, or `samples` values drawn at random with +/// replacement, down one column. The input is read column by column (row by row for a single +/// row); blanks are skipped. +fn sampling(s: &Session, p: &Json, seed: Option) -> Result { + let (si, r) = input_range(s, p, &["range", "input"])?; + let by_rows = r.height() == 1 && r.width() > 1; + let vars = variables(s, si, r, by_rows, flag(p, "labels"), &|_| String::new())?; + let mut x = Vec::new(); + for v in &vars { + x.extend(numbers(&v.vals, true)?); + } + if x.is_empty() { + return Err(EngineError::Other("The input range holds no numbers.".into())); + } + let picked: Vec = match seed { + Some(seed) => { + let k = whole(p, "samples", None, 1.0)?; + if k > MAX_RANDOM as f64 { + return Err(EngineError::Other(format!("Sampling takes at most {MAX_RANDOM} samples."))); + } + let mut rng = Rng::new(seed); + (0..k as usize).filter_map(|_| x.get(rng.below(x.len() as u64) as usize).copied()).collect() + } + None => { + let period = whole(p, "period", None, 1.0)?; + if period > x.len() as f64 { + return Err(EngineError::Other("The period must be at most the number of input values.".into())); + } + x.iter().skip(period as usize - 1).step_by(period as usize).copied().collect() + } + }; + let mut g = Grid::default(); + for (i, v) in picked.iter().enumerate() { + g.num(idx(i), 0, *v); + } + Ok(g) +} + // ---------------------------------------------------------------- output /// Writes the report at `output` (refusing to overwrite data unless `overwrite`) or on a new @@ -1096,7 +1788,7 @@ fn write_report(s: &mut Session, p: &Json, tool: &str, g: Grid) -> Result { for row in rect.start.row..=rect.end.row { for (c, cell) in sh.cells.row(row, rect.start.col, rect.end.col) { - if !cell.value.is_empty() || cell.formula.is_some() { + if cell.has_content() { occupied.push(CellRef::new(row, c)); } } @@ -1124,13 +1816,13 @@ fn write_report(s: &mut Session, p: &Json, tool: &str, g: Grid) -> Result let sh = cx.sheet_mut(si)?; for c in &occupied { let style = sh.style_id(*c); - sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style }); + sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style, py: None }); } let mut touched = occupied.clone(); for ((r, c), v) in &g.cells { let cell = CellRef::new(at.row + r, at.col + c); let style = pct_styles.get(&cell).copied().unwrap_or_else(|| sh.style_id(cell)); - sh.set_cell(cell, Cell { value: v.clone(), formula: None, style }); + sh.set_cell(cell, Cell { value: v.clone(), formula: None, style, py: None }); touched.push(cell); } for c in touched { @@ -1150,6 +1842,7 @@ fn run(s: &mut Session, p: &Json) -> Result { return Ok(json!({"tools": TOOLS.iter().map(|(id, label)| json!({"id": id, "label": label})).collect::>()})); }; let tool = tool_id(t).ok_or_else(|| bad(CMD, format!("unknown tool `{t}`")))?; + let mut seed = None; let g = match tool { "descriptive" => descriptive(s, p)?, "histogram" => histogram(s, p)?, @@ -1162,16 +1855,38 @@ fn run(s: &mut Session, p: &Json) -> Result { "tTestPaired" | "tTestEqual" | "tTestUnequal" => t_test(s, p, tool)?, "fTest" => f_test(s, p)?, "anovaSingle" => anova_single(s, p)?, + "anovaTwoFactorWithout" => anova_two_factor_without(s, p)?, + "anovaTwoFactorWith" => anova_two_factor_with(s, p)?, + "zTest" => z_test(s, p)?, + "fourierAnalysis" => fourier_analysis(s, p)?, + "randomNumberGeneration" => { + // A patterned sequence draws nothing: its seed is neither read nor reported. + if !patterned(p) { + seed = Some(seed_of(p)?); + } + random_numbers(s, p, seed.unwrap_or(0))? + } + "sampling" => { + if random_sampling(p) { + seed = Some(seed_of(p)?); + } + sampling(s, p, seed)? + } _ => return Err(bad(CMD, format!("unknown tool `{t}`"))), }; - write_report(s, p, tool, g) + let mut out = write_report(s, p, tool, g)?; + if let Some(k) = seed { + out["seed"] = json!(k); + } + Ok(out) } #[cfg(test)] mod tests { use gridcraft_core::{CellRef, Value}; - use serde_json::json; + use serde_json::{Value as Json, json}; + use super::{MAX_OUTCOMES, call, f64_of, pmf_table}; use crate::Session; fn s() -> Session { @@ -1375,6 +2090,462 @@ mod tests { assert_eq!(n(&s, "X4"), 0.25, "4 has one value below it among five"); } + #[test] + fn two_factor_anova_without_replication_matches_a_textbook_example() { + // Hardness testing, a randomized complete block design (Montgomery, Design and Analysis + // of Experiments, Example 4.1): four tips (rows) by four coupons (columns). Published: + // SS tips 0.385, SS coupons 0.825, SS error 0.080, SS total 1.290, F tips 14.44. + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["", "Coupon 1", "Coupon 2", "Coupon 3", "Coupon 4"], + ["Tip 1", 9.3, 9.4, 9.6, 10.0], + ["Tip 2", 9.4, 9.3, 9.8, 9.9], + ["Tip 3", 9.2, 9.4, 9.5, 9.7], + ["Tip 4", 9.7, 9.6, 10.0, 10.2], + ]}), + ) + .unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Anova: Two-Factor Without Replication", "range": "A1:E5", "labels": true, "output": "H1"})) + .unwrap(); + assert_eq!(v(&s, "H1"), Value::text("Anova: Two-Factor Without Replication")); + assert_eq!((v(&s, "H4"), n(&s, "I4")), (Value::text("Tip 1"), 4.0)); + assert!(close(n(&s, "J4"), 38.3, 1e-12), "sum of tip 1"); + assert_eq!(v(&s, "H9"), Value::text("Coupon 1")); + assert!(close(n(&s, "K12"), 9.95, 1e-12), "average of coupon 4"); + assert_eq!(v(&s, "H17"), Value::text("Rows")); + assert!(close(n(&s, "I17"), 0.385, 1e-12)); + assert!(close(n(&s, "I18"), 0.825, 1e-12)); + assert!(close(n(&s, "I19"), 0.080, 1e-12)); + assert!(close(n(&s, "I21"), 1.290, 1e-12)); + assert_eq!((n(&s, "J17"), n(&s, "J19"), n(&s, "J21")), (3.0, 9.0, 15.0)); + assert!(close(n(&s, "L17"), 14.4375, 1e-9), "F for tips"); + assert!(close(n(&s, "M17"), eval(&mut s, "=F.DIST.RT(14.4375,3,9)"), 1e-9)); + assert!(close(n(&s, "N17"), eval(&mut s, "=F.INV.RT(0.05,3,9)"), 1e-9)); + assert!(v(&s, "L19").is_empty(), "the error line has no F"); + } + + #[test] + fn two_factor_anova_with_replication_matches_a_textbook_example() { + let mut s = s(); + // Battery life (Montgomery, Example 5.1): three materials (samples of four rows) by three + // temperatures (columns). Published: SS material 10683.72, SS temperature 39118.72, + // SS interaction 9613.78, SS error 18230.75 on 27 df, SS total 77646.97. + s.execute( + "range.setValues", + json!({"range": "A20", "values": [ + ["Material", "15 F", "70 F", "125 F"], + ["Type 1", 130, 34, 20], ["", 155, 40, 70], ["", 74, 80, 82], ["", 180, 75, 58], + ["Type 2", 150, 136, 25], ["", 188, 122, 70], ["", 159, 106, 58], ["", 126, 115, 45], + ["Type 3", 138, 174, 96], ["", 110, 120, 104], ["", 168, 150, 82], ["", 160, 139, 60], + ]}), + ) + .unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "anovaTwoFactorWith", "range": "A20:D32", "rowsPerSample": 4, "newSheet": "Battery"})) + .unwrap(); + assert_eq!(v(&s, "Battery!A3"), Value::text("SUMMARY")); + assert_eq!((v(&s, "Battery!B3"), v(&s, "Battery!E3")), (Value::text("15 F"), Value::text("Total"))); + assert_eq!(v(&s, "Battery!A4"), Value::text("Type 1")); + assert_eq!((n(&s, "Battery!B5"), n(&s, "Battery!B6"), n(&s, "Battery!E5")), (4.0, 539.0, 12.0)); + assert_eq!(v(&s, "Battery!A22"), Value::text("Total")); + assert_eq!(n(&s, "Battery!B24"), 1738.0, "sum of the 15 F column"); + assert_eq!(v(&s, "Battery!A29"), Value::text("ANOVA")); + assert_eq!( + (v(&s, "Battery!A31"), v(&s, "Battery!A34"), v(&s, "Battery!A36")), + (Value::text("Sample"), Value::text("Within"), Value::text("Total")) + ); + assert!(close(n(&s, "Battery!B31"), 10683.72, 0.01)); + assert!(close(n(&s, "Battery!B32"), 39118.72, 0.01)); + assert!(close(n(&s, "Battery!B33"), 9613.78, 0.01)); + assert!(close(n(&s, "Battery!B34"), 18230.75, 0.01)); + assert!(close(n(&s, "Battery!B36"), 77646.97, 0.01)); + assert_eq!((n(&s, "Battery!C33"), n(&s, "Battery!C34"), n(&s, "Battery!C36")), (4.0, 27.0, 35.0)); + assert!(close(n(&s, "Battery!E31"), 7.91, 0.005) && close(n(&s, "Battery!E32"), 28.97, 0.005) && close(n(&s, "Battery!E33"), 3.56, 0.005)); + assert!(close(n(&s, "Battery!F33"), 0.0186, 0.00005), "interaction P-value"); + // Rows per sample must divide the data rows. + let bad = json!({"tool": "anovaTwoFactorWith", "range": "Sheet1!A20:D32", "rowsPerSample": 5, "output": "F60"}); + assert!(s.execute("data.analysisToolPak", bad).is_err()); + } + + #[test] + fn z_test_with_known_variances() { + // x̄ = 3 (n = 5, σ² = 2), ȳ = 4 (n = 3, σ² = 6): z = −1/√2.4. Critical values from the + // standard normal table: 1.644854 (one tail) and 1.959964 (two tails) at α = 0.05. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["x", "y"], [1, 2], [2, 4], [3, 6], [4, null], [5, null]]})).unwrap(); + s.execute( + "data.analysisToolPak", + json!({"tool": "zTest", "range1": "A1:A6", "range2": "B1:B6", "labels": true, "variance1": 2, "variance2": 6, "output": "D1"}), + ) + .unwrap(); + assert_eq!(v(&s, "D1"), Value::text("z-Test: Two Sample for Means")); + assert_eq!((v(&s, "E3"), v(&s, "F3")), (Value::text("x"), Value::text("y"))); + assert_eq!((n(&s, "E4"), n(&s, "F4"), n(&s, "E5"), n(&s, "F6")), (3.0, 4.0, 2.0, 3.0)); + let z = -1.0 / 2.4f64.sqrt(); + assert!(close(n(&s, "E8"), z, 1e-12)); + let tail = 1.0 - eval(&mut s, &format!("=NORM.S.DIST({},TRUE)", -z)); + assert!(close(n(&s, "E9"), tail, 1e-12) && close(n(&s, "E9"), 0.2593, 1e-4)); + assert!(close(n(&s, "E10"), 1.644_853_6, 1e-6)); + assert!(close(n(&s, "E11"), 2.0 * tail, 1e-12)); + assert!(close(n(&s, "E12"), 1.959_964_0, 1e-6)); + // Unknown or non-positive variances are refused. + assert!(s.execute("data.analysisToolPak", json!({"tool": "zTest", "range1": "A2:A6", "range2": "B2:B4", "output": "H1"})).is_err()); + let zero = json!({"tool": "zTest", "range1": "A2:A6", "range2": "B2:B4", "variance1": 0, "variance2": 1, "output": "H1"}); + assert!(s.execute("data.analysisToolPak", zero).is_err()); + } + + #[test] + fn fourier_analysis_matches_known_transforms() { + let mut s = s(); + // DFT of 1, 2, 3, 4: 10, −2+2i, −2, −2−2i. + s.execute("range.setValues", json!({"range": "A1", "values": [["Signal"], [1], [2], [3], [4]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Fourier Analysis", "range": "A1:A5", "labels": true, "output": "C1"})).unwrap(); + let col = |s: &Session, c: &str, rows: std::ops::RangeInclusive| rows.map(|r| v(s, &format!("{c}{r}"))).collect::>(); + assert_eq!(col(&s, "C", 1..=5), ["Signal", "10", "-2+2i", "-2", "-2-2i"].map(Value::text).to_vec()); + // The inverse transform of that output returns the signal. + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C2:C5", "inverse": true, "output": "E1"})).unwrap(); + assert_eq!(col(&s, "E", 1..=4), ["1", "2", "3", "4"].map(Value::text).to_vec()); + // cos(2πn/8) over eight points: N/2 = 4 at the first and last frequencies, 0 elsewhere. + let wave: Vec = (0..8).map(|k| json!([(std::f64::consts::PI * k as f64 / 4.0).cos()])).collect(); + s.execute("range.setValues", json!({"range": "G1", "values": wave})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "G1:G8", "output": "H1"})).unwrap(); + assert_eq!(col(&s, "H", 1..=8), ["0", "4", "0", "0", "0", "0", "0", "4"].map(Value::text).to_vec()); + // Complex text input; a single value is its own transform. + s.execute("range.setValues", json!({"range": "J1", "values": [["3+4i"], ["1-i"]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "J1:J2", "output": "K1"})).unwrap(); + assert_eq!(col(&s, "K", 1..=2), ["4+3i", "2+5i"].map(Value::text).to_vec()); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "J1", "output": "L1"})).unwrap(); + assert_eq!(v(&s, "L1"), Value::text("3+4i")); + // Three values are not a power of two; a word is not a number. + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A2:A4", "output": "N1"})).is_err()); + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A4", "output": "N1"})).is_err()); + assert!(s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A8192", "output": "N1"})).is_err()); + } + + #[test] + fn fourier_analysis_keeps_a_small_imaginary_part_beside_a_large_real_one() { + let mut s = s(); + // With one value the transform is the identity and performs no arithmetic, so no part of + // the output is rounding noise: 1e14 + 1i comes back as 1e14 + 1i, forward and inverse. + s.execute("range.setValues", json!({"range": "A1", "values": [["100000000000000+1i"]]})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1", "output": "C1"})).unwrap(); + assert_eq!(eval(&mut s, "=IMREAL(C1)"), 1e14); + assert_eq!(eval(&mut s, "=IMAGINARY(C1)"), 1.0); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C1", "inverse": true, "output": "E1"})).unwrap(); + assert_eq!(eval(&mut s, "=IMREAL(E1)"), 1e14); + assert_eq!(eval(&mut s, "=IMAGINARY(E1)"), 1.0); + } + + #[test] + fn fourier_analysis_round_trip_recovers_small_components_beside_a_large_dc() { + let mut s = s(); + // x_n = 1e6 + 1e-7·cos(2πn/8) for n = 0 … 7. The transform of a constant c over N points is + // N·c at k = 0 and 0 elsewhere; the transform of a·cos(2πn/N) is a·N/2 at k = 1 and + // k = N − 1. So X_0 = 8·1e6 = 8e6, X_1 = X_7 = 1e-7·8/2 = 4e-7 and X_2 … X_6 = 0. The inputs + // are stored to within ulp(1e6)/2 ≈ 6e-11 and the first butterfly stage subtracts nearby + // numbers exactly, so the harmonics carry at most about 5e-10 of noise. The cleanup bound + // 8·ε·log2(8)·Σ|x_n| ≈ 8 · 2.2e-16 · 3 · 8e6 ≈ 4.3e-8 zeroes noise of that size and keeps + // 4e-7; a cutoff relative to the largest output (8e6 · 1e-13 = 8e-7) would zero the + // harmonics. + let x = |k: usize| 1e6 + 1e-7 * (std::f64::consts::PI * k as f64 / 4.0).cos(); + let wave: Vec = (0..8).map(|k| json!([x(k)])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": wave})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "A1:A8", "output": "C1"})).unwrap(); + assert!(close(eval(&mut s, "=IMREAL(C1)"), 8e6, 1e-6)); + assert_eq!(eval(&mut s, "=IMAGINARY(C1)"), 0.0); + for cell in ["C2", "C8"] { + assert!(close(eval(&mut s, &format!("=IMREAL({cell})")), 4e-7, 5e-9), "{cell}"); + assert_eq!(eval(&mut s, &format!("=IMAGINARY({cell})")), 0.0, "{cell}"); + } + for r in 3..=7 { + assert_eq!(v(&s, &format!("C{r}")), Value::text("0"), "C{r}"); + } + // The inverse of that output returns each x_n to within 2e-9 (2e-15 relative); without the + // harmonics every value would come back as 1e6, off by up to 1e-7. + s.execute("data.analysisToolPak", json!({"tool": "fourierAnalysis", "range": "C1:C8", "inverse": true, "output": "E1"})).unwrap(); + for k in 0..8 { + let cell = format!("E{}", k + 1); + assert!(close(eval(&mut s, &format!("=IMREAL({cell})")), x(k), 2e-9), "{cell}"); + assert_eq!(eval(&mut s, &format!("=IMAGINARY({cell})")), 0.0, "{cell}"); + } + } + + /// Column `col` of sheet `sheet`, rows 1 to `rows`, as numbers. + fn numbers_of(s: &Session, sheet: &str, col: &str, rows: u32) -> Vec { + (1..=rows).map(|r| n(s, &format!("{sheet}!{col}{r}"))).collect() + } + fn mean_var(x: &[f64]) -> (f64, f64) { + let m = x.iter().sum::() / x.len() as f64; + (m, x.iter().map(|v| (v - m).powi(2)).sum::() / (x.len() - 1) as f64) + } + + #[test] + fn random_numbers_are_seeded_and_follow_their_distributions() { + let mut s = s(); + let rng = |s: &mut Session, sheet: &str, p: Json| { + let mut p = p; + p["tool"] = json!("randomNumberGeneration"); + p["newSheet"] = json!(sheet); + s.execute("data.analysisToolPak", p).unwrap() + }; + // The same seed repeats the numbers; the result reports the seed. + let r = rng(&mut s, "U1", json!({"variables": 2, "count": 2000, "distribution": "uniform", "from": 2, "to": 4, "seed": 42})); + assert_eq!((r["seed"].as_u64(), r["range"].as_str()), (Some(42), Some("A1:B2000"))); + rng(&mut s, "U2", json!({"variables": 2, "count": 2000, "distribution": "uniform", "from": 2, "to": 4, "seed": 42})); + let (a, b) = (numbers_of(&s, "U1", "B", 2000), numbers_of(&s, "U2", "B", 2000)); + assert_eq!(a, b); + assert!(a.iter().all(|x| (2.0..4.0).contains(x))); + // Uniform on [2, 4]: mean 3, variance 1/3. + let (m, var) = mean_var(&a); + assert!((m - 3.0).abs() < 0.05 && (var - 1.0 / 3.0).abs() < 0.03, "{m} {var}"); + let unseeded = rng(&mut s, "U3", json!({"count": 1})); + assert!(unseeded["seed"].as_u64().is_some(), "a seed is chosen and reported"); + // Normal(10, 2): mean 10, variance 4. + rng(&mut s, "N", json!({"count": 20000, "distribution": "normal", "mean": 10, "standardDeviation": 2, "seed": 7})); + let (m, var) = mean_var(&numbers_of(&s, "N", "A", 20000)); + assert!((m - 10.0).abs() < 0.05 && (var - 4.0).abs() < 0.15, "{m} {var}"); + // Binomial(20, 0.3): mean np = 6, variance np(1 − p) = 4.2. + rng(&mut s, "B", json!({"count": 20000, "distribution": "binomial", "p": 0.3, "trials": 20, "seed": 8})); + let x = numbers_of(&s, "B", "A", 20000); + assert!(x.iter().all(|v| v.fract() == 0.0 && (0.0..=20.0).contains(v))); + let (m, var) = mean_var(&x); + assert!((m - 6.0).abs() < 0.08 && (var - 4.2).abs() < 0.2, "{m} {var}"); + // Poisson(3.5): mean and variance 3.5. + rng(&mut s, "P", json!({"count": 20000, "distribution": "poisson", "lambda": 3.5, "seed": 9})); + let (m, var) = mean_var(&numbers_of(&s, "P", "A", 20000)); + assert!((m - 3.5).abs() < 0.08 && (var - 3.5).abs() < 0.2, "{m} {var}"); + // Bernoulli(0.25) and a discrete distribution on {1, 2} with P(2) = 0.75. + rng(&mut s, "Ber", json!({"count": 4000, "distribution": "bernoulli", "p": 0.25, "seed": 10})); + let ones = numbers_of(&s, "Ber", "A", 4000).iter().filter(|v| **v == 1.0).count(); + assert!((900..1100).contains(&ones), "{ones}"); + s.execute("range.setValues", json!({"range": "Sheet1!A1", "values": [[1, 0.25], [2, 0.75]]})).unwrap(); + rng(&mut s, "D", json!({"count": 4000, "distribution": "discrete", "valueRange": "Sheet1!A1:B2", "seed": 11})); + let x = numbers_of(&s, "D", "A", 4000); + assert!(x.iter().all(|v| *v == 1.0 || *v == 2.0)); + let twos = x.iter().filter(|v| **v == 2.0).count(); + assert!((2900..3100).contains(&twos), "{twos}"); + // Patterned: 1 to 3, each number twice, the sequence twice. + rng(&mut s, "Pat", json!({"distribution": "patterned", "from": 1, "to": 3, "step": 1, "repeatEach": 2, "repeatSequence": 2})); + assert_eq!(numbers_of(&s, "Pat", "A", 12), [1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0]); + assert!(v(&s, "Pat!A13").is_empty()); + // Output is bounded; parameters are checked. + for p in [ + json!({"count": 2_000_000}), + json!({"count": 1000, "variables": 2000}), + json!({"count": 0}), + json!({"count": 1.5}), + json!({"distribution": "uniform"}), + json!({"count": 1, "distribution": "bernoulli", "p": 2}), + json!({"count": 1, "distribution": "binomial", "trials": 1e9}), + json!({"count": 1, "distribution": "poisson", "lambda": -1}), + json!({"count": 1, "distribution": "normal", "standardDeviation": -1}), + json!({"count": 1, "distribution": "discrete", "valueRange": "Sheet1!A1:A2"}), + json!({"count": 1, "distribution": "patterned", "from": 1, "to": 1e9, "step": 1}), + json!({"count": 1, "distribution": "patterned", "from": 3, "to": 1}), + json!({"count": 1, "distribution": "weird"}), + json!({"count": 1, "seed": -1}), + json!({"count": 1, "seed": "abc"}), + ] { + let mut q = p.clone(); + q["tool"] = json!("randomNumberGeneration"); + q["output"] = json!("Sheet1!H1"); + assert!(s.execute("data.analysisToolPak", q).is_err(), "{p}"); + } + s.execute("range.setValues", json!({"range": "Sheet1!A1", "values": [[1, 0.5], [2, 0.6]]})).unwrap(); + let p = + json!({"tool": "randomNumberGeneration", "count": 1, "distribution": "discrete", "valueRange": "Sheet1!A1:B2", "output": "Sheet1!H1"}); + assert!(s.execute("data.analysisToolPak", p).is_err(), "probabilities must add up to 1"); + } + + #[test] + fn binomial_and_poisson_tables_agree_with_the_worksheet_functions() { + // The recurrence outward from the mode reproduces BINOM.DIST and POISSON.DIST at every + // tabulated outcome, the table carries the whole distribution, and it is only as wide as + // the outcomes that matter. The worksheet functions themselves are accurate to about + // n · ε for n trials (their logarithms are of that size), hence the moderate n and λ. + let binom = |k: f64, n: f64, p: f64| f64_of(&call("BINOM.DIST", &[Value::Number(k), Value::Number(n), Value::Number(p), Value::Bool(false)])); + for (n, p) in [(20.0f64, 0.3f64), (100.0, 0.5), (50.0, 0.9), (30.0, 0.01), (7.0, 0.999), (1.0, 0.5)] { + let mode = ((n + 1.0) * p).floor().min(n); + let odds = p / (1.0 - p); + let (first, pmf) = pmf_table(n, mode, binom(mode, n, p), |k| (n - k) / (k + 1.0) * odds).unwrap(); + assert!(first >= 0.0 && first + pmf.len() as f64 - 1.0 <= n, "n={n} p={p}: {first} + {}", pmf.len()); + for (i, got) in pmf.iter().enumerate() { + let k = first + i as f64; + let want = binom(k, n, p); + assert!(((got - want) / want).abs() < 1e-12, "n={n} p={p} k={k}: {got} vs {want}"); + } + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-12, "n={n} p={p}"); + } + let poisson = |k: f64, lambda: f64| f64_of(&call("POISSON.DIST", &[Value::Number(k), Value::Number(lambda), Value::Bool(false)])); + for lambda in [0.2f64, 3.5, 50.0] { + let mode = lambda.floor(); + let (first, pmf) = pmf_table(MAX_OUTCOMES, mode, poisson(mode, lambda), |k| lambda / (k + 1.0)).unwrap(); + assert_eq!(first, 0.0); + for (i, got) in pmf.iter().enumerate() { + let want = poisson(i as f64, lambda); + assert!(((got - want) / want).abs() < 1e-12, "lambda={lambda} k={i}: {got} vs {want}"); + } + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-12, "lambda={lambda}"); + } + // Binomial(1e6, 0.5): standard deviation 500, so the terms vanish within about 38 + // standard deviations below the mode and the sum reaches 1 within about 8 above it: + // roughly 23,000 entries starting near 481,000, not 1,000,001 starting at 0. + let (n, p) = (1_000_000.0, 0.5); + let (first, pmf) = pmf_table(n, 500_000.0, binom(500_000.0, n, p), |k| (n - k) / (k + 1.0)).unwrap(); + assert!((470_000.0..=490_000.0).contains(&first) && pmf.len() < 40_000, "{first} + {}", pmf.len()); + // The anchor BINOM.DIST(500000, 1e6, 0.5) carries that function's error of about n · ε + // (its logarithms are near 7e5), which scales the whole table; draws divide by the total. + assert!((pmf.iter().sum::() - 1.0).abs() < 1e-8); + // A bad anchor or mode is refused rather than tabulated. + assert!(pmf_table(10.0, 5.0, f64::NAN, |_| 1.0).is_err()); + assert!(pmf_table(10.0, 5.0, 0.0, |_| 1.0).is_err()); + assert!(pmf_table(10.0, 11.0, 0.5, |_| 1.0).is_err()); + } + + #[test] + #[allow(clippy::disallowed_methods)] // a native-only timing test: the clock is read off wasm + fn binomial_and_poisson_draws_at_the_limits_are_tabulated_quickly() { + let mut s = s(); + // The tables cover the outcomes around the mode, not every one of the 1,000,001 for a + // million trials, so the largest inputs cost milliseconds. Binomial(1e6, 0.5) has mean + // 500000 and standard deviation 500: 1000 draws put the sample mean within 500/√1000 ≈ 16 + // of it, so 100 is six standard errors. Poisson(1e5) has mean 1e5 and standard deviation + // 316: 1000 draws put the mean within 10, so 60 is six standard errors. With p = 1 every + // draw is exactly 1e6, with p = 0 exactly 0. + let mut draw = |sheet: &str, dist: Json| { + let mut dist = dist; + dist["tool"] = json!("randomNumberGeneration"); + dist["count"] = json!(1000); + dist["seed"] = json!(3); + dist["newSheet"] = json!(sheet); + s.execute("data.analysisToolPak", dist).unwrap(); + }; + let start = std::time::Instant::now(); + draw("Half", json!({"distribution": "binomial", "p": 0.5, "trials": 1_000_000})); + draw("Sure", json!({"distribution": "binomial", "p": 1, "trials": 1_000_000})); + draw("Never", json!({"distribution": "binomial", "p": 0, "trials": 1_000_000})); + draw("Pois", json!({"distribution": "poisson", "lambda": 100_000})); + let elapsed = start.elapsed(); + let (m, _) = mean_var(&numbers_of(&s, "Half", "A", 1000)); + assert!((m - 500_000.0).abs() < 100.0, "{m}"); + assert!(numbers_of(&s, "Sure", "A", 1000).iter().all(|v| *v == 1_000_000.0)); + assert!(numbers_of(&s, "Never", "A", 1000).iter().all(|v| *v == 0.0)); + let (m, _) = mean_var(&numbers_of(&s, "Pois", "A", 1000)); + assert!((m - 100_000.0).abs() < 60.0, "{m}"); + assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}"); + } + + #[test] + fn sampling_periodic_and_random() { + let mut s = s(); + let values: Vec = (1..=10).map(|k| json!([k])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("data.analysisToolPak", json!({"tool": "Sampling", "range": "A1:A10", "period": 3, "output": "C1"})).unwrap(); + assert_eq!(numbers_of(&s, "Sheet1", "C", 3), [3.0, 6.0, 9.0]); + assert!(v(&s, "C4").is_empty()); + let r = s + .execute( + "data.analysisToolPak", + json!({"tool": "sampling", "range": "A1:A10", "method": "random", "samples": 20, "seed": 5, "output": "D1"}), + ) + .unwrap(); + assert_eq!(r["seed"], 5); + s.execute( + "data.analysisToolPak", + json!({"tool": "sampling", "range": "A1:A10", "method": "random", "samples": 20, "seed": 5, "output": "E1"}), + ) + .unwrap(); + let (a, b) = (numbers_of(&s, "Sheet1", "D", 20), numbers_of(&s, "Sheet1", "E", 20)); + assert_eq!(a, b, "the same seed repeats the sample"); + assert!(a.iter().all(|x| x.fract() == 0.0 && (1.0..=10.0).contains(x))); + for p in [ + json!({"range": "A1:A10", "period": 11}), + json!({"range": "A1:A10", "period": 0}), + json!({"range": "A1:A10"}), + json!({"range": "A1:A10", "method": "random", "samples": 2_000_000}), + json!({"range": "B1:B10", "period": 1}), + ] { + let mut q = p.clone(); + q["tool"] = json!("sampling"); + q["output"] = json!("G1"); + assert!(s.execute("data.analysisToolPak", q).is_err(), "{p}"); + } + } + + #[test] + fn options_typed_as_text_that_is_not_a_number_are_refused() { + // A form sends its options as text; one that doesn't read as a number (a decimal comma, + // a typo) is an error, not the default, while a blank option takes the default. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2], [2, 4], [3, 6]]})).unwrap(); + let rng = |dist: &str| json!({"tool": "randomNumberGeneration", "count": 3, "distribution": dist, "seed": 1, "outputTo": "newSheet"}); + let z = json!({"tool": "zTest", "range1": "Sheet1!A1:A3", "range2": "Sheet1!B1:B3", "variance1": 1, "variance2": 4, "outputTo": "newSheet"}); + let with = |base: &Json, key: &str, val: &str| { + let mut p = base.clone(); + p[key] = json!(val); + p + }; + let cases = [ + (rng("uniform"), "from"), + (rng("uniform"), "to"), + (rng("normal"), "mean"), + (rng("normal"), "standardDeviation"), + (rng("bernoulli"), "p"), + (rng("binomial"), "p"), + (rng("poisson"), "lambda"), + (rng("patterned"), "step"), + (rng("uniform"), "variables"), + (z.clone(), "hypothesizedDifference"), + ]; + for (base, key) in cases { + let e = s.execute("data.analysisToolPak", with(&base, key, "0,3")).unwrap_err().to_string(); + assert!(e.contains(key), "{key}: {e}"); + s.execute("data.analysisToolPak", with(&base, key, " ")).unwrap_or_else(|e| panic!("{key} blank: {e}")); + } + } + + #[test] + fn an_alpha_that_is_not_a_number_is_refused() { + // A decimal comma or a typo in Alpha must not run the test at 0.05 without a word. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["", "c1", "c2"], ["r1", 1, 2], ["r1", 2, 4], ["r2", 3, 6], ["r2", 5, 9]]})) + .unwrap(); + for base in [ + json!({"tool": "zTest", "range1": "Sheet1!B2:B5", "range2": "Sheet1!C2:C5", "variance1": 1, "variance2": 4}), + json!({"tool": "anovaTwoFactorWithout", "range": "Sheet1!B2:C5"}), + json!({"tool": "anovaTwoFactorWith", "range": "Sheet1!A1:C5", "rowsPerSample": 2}), + json!({"tool": "tTestEqual", "range1": "Sheet1!B2:B5", "range2": "Sheet1!C2:C5"}), + ] { + let mut p = base.clone(); + p["alpha"] = json!("0,01"); + let e = s.execute("data.analysisToolPak", p).unwrap_err().to_string(); + assert!(e.contains("alpha"), "{base}: {e}"); + let mut p = base.clone(); + p["alpha"] = json!(""); + s.execute("data.analysisToolPak", p).unwrap_or_else(|e| panic!("{base} blank alpha: {e}")); + } + } + + #[test] + fn a_patterned_sequence_ignores_the_seed() { + // Patterned generation draws nothing, so a seed left in the form (even one that isn't a + // number) neither blocks the run nor shows up in the result. + let mut s = s(); + for seed in [json!("abc"), json!(7)] { + let r = s + .execute( + "data.analysisToolPak", + json!({"tool": "randomNumberGeneration", "distribution": "patterned", "from": 1, "to": 3, "seed": seed, "outputTo": "newSheet"}), + ) + .unwrap_or_else(|e| panic!("seed {seed}: {e}")); + assert!(r.get("seed").is_none(), "seed {seed}: {r}"); + } + // A random distribution still refuses the bad seed. + let bad = json!({"tool": "randomNumberGeneration", "distribution": "uniform", "count": 2, "seed": "abc", "outputTo": "newSheet"}); + assert!(s.execute("data.analysisToolPak", bad).is_err()); + } + #[test] fn hostile_inputs_are_refused_without_panicking() { let mut s = s(); @@ -1399,6 +2570,11 @@ mod tests { json!({"tool": "anovaSingle", "range": "A1:A2"}), json!({"tool": "correlation", "range": "A1:B2", "alpha": "x", "groupedBy": 5}), json!({"tool": "descriptive", "range": "A1:A2", "confidence": 250}), + json!({"tool": "anovaTwoFactorWithout", "range": "A1:B2"}), + json!({"tool": "anovaTwoFactorWithout", "range": "A1:A2"}), + json!({"tool": "anovaTwoFactorWith", "range": "A1:B2", "rowsPerSample": 2}), + json!({"tool": "anovaTwoFactorWith", "range": "A1:B2", "rowsPerSample": 1e300}), + json!({"tool": "zTest", "range1": "A1", "range2": "A2", "variance1": "x", "variance2": -1}), ] { assert!(s.execute("data.analysisToolPak", p.clone()).is_err(), "{p}"); } diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 143763a5e9..0906f48937 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -99,18 +99,30 @@ pub fn specs() -> Vec { ), cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd), cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → invalid cells", has_doc, circle_invalid), - cmd!( - "data.group", - "Group", - ["Data", "Outline"], - Some("Alt+Shift+Right"), - "{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default), sheet?}", - has_doc, - |s, p| group(s, p, true) - ), - cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Alt+Shift+Left"), "{rows? | cols? | by?: rows|cols, sheet?}", has_doc, |s, p| { - group(s, p, false) - }), + CommandSpec { + shortcut_mac: Some("Cmd+Shift+K"), + ..cmd!( + "data.group", + "Group", + ["Data", "Outline"], + Some("Alt+Shift+Right"), + "{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default), sheet?}", + has_doc, + |s, p| group(s, p, true) + ) + }, + CommandSpec { + shortcut_mac: Some("Cmd+Shift+J"), + ..cmd!( + "data.ungroup", + "Ungroup", + ["Data", "Outline"], + Some("Alt+Shift+Left"), + "{rows? | cols? | by?: rows|cols, sheet?}", + has_doc, + |s, p| { group(s, p, false) } + ) + }, cmd!( "data.hideDetail", "Hide Detail", diff --git a/crates/engine/src/cmd/data/sort.rs b/crates/engine/src/cmd/data/sort.rs index a365276502..491e3d51e4 100644 --- a/crates/engine/src/cmd/data/sort.rs +++ b/crates/engine/src/cmd/data/sort.rs @@ -195,8 +195,7 @@ fn do_sort(s: &mut Session, sheet: usize, r: RangeRef, header: bool, keys: Vec = - sh.images.iter().map(|o| o.anchor).chain(sh.charts.iter().map(|o| o.anchor)).chain(sh.shapes.iter().map(|o| o.anchor)).collect(); + let objs: Vec = sh.object_anchors().copied().collect(); let descs: Vec<(u32, u32, f32, f32)> = objs .iter() .map(|a| { @@ -242,33 +241,22 @@ fn do_sort(s: &mut Session, sheet: usize, r: RangeRef, header: bool, keys: Vec o1 { - continue; - } - let na = sorted_anchor(shm, a, desc, by_cols, b0, b1, &dst_of); - if na != a { - if i < ni { - if let Some(o) = shm.images.get_mut(i) { - o.anchor = na; - } - } else if i < ni + nch { - if let Some(o) = shm.charts.get_mut(i - ni) { - o.anchor = na; - } - } else if let Some(o) = shm.shapes.get_mut(i - ni - nch) { - o.anchor = na; - } - } + let new_anchors: Vec = objs + .into_iter() + .zip(descs) + .map(|(a, desc)| { + let other = if by_cols { a.cell.row } else { a.cell.col }; + if other < o0 || other > o1 { a } else { sorted_anchor(shm, a, desc, by_cols, b0, b1, &dst_of) } + }) + .collect(); + for (a, n) in shm.object_anchors_mut().zip(new_anchors) { + *a = n; } for (c, _) in moved { cx.changed.push((sheet, c)); @@ -284,7 +272,9 @@ fn do_sort(s: &mut Session, sheet: usize, r: RangeRef, header: bool, keys: Vec Anchor { if a.mode == AnchorMode::Absolute { return a; @@ -302,7 +292,10 @@ fn sorted_anchor(sh: &Sheet, a: Anchor, bottom: (u32, u32, f32, f32), by_cols: b let y1 = sh.row_top(nr) + a.dy as f64; let x2 = sh.col_left(nbc) + tdx as f64; let y2 = sh.row_top(nbr) + tdy as f64; - Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode: a.mode } + // An extent that is not positive means the sort put the bottom-right line before the + // top-left one on that axis: the object keeps its old size there. + let fit = |extent: f64, old: f32| if extent > 0.0 { extent as f32 } else { old.max(0.0) }; + Anchor { cell: CellRef::new(nr, nc), dx: a.dx, dy: a.dy, width: fit(x2 - x1, a.width), height: fit(y2 - y1, a.height), mode: a.mode } } else { Anchor { cell: CellRef::new(nr, nc), ..a } } diff --git a/crates/engine/src/cmd/data/tools.rs b/crates/engine/src/cmd/data/tools.rs index 2cbca17bd1..c4ae43ef4a 100644 --- a/crates/engine/src/cmd/data/tools.rs +++ b/crates/engine/src/cmd/data/tools.rs @@ -146,7 +146,16 @@ pub(super) fn text_to_columns(s: &mut Session, p: &Json) -> Result { } } for (c, t) in out { - let cell = crate::cmd::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); + let cell = match crate::cmd::edit::input_to_cell(&t, sheet, c, &mut cx.wb) { + Ok(cell) => cell, + // `=PY(…)` doesn't make a Python cell (that takes python.set): the piece is kept + // as text rather than lost. + Err(_) if gridcraft_model::python::is_py_formula(&t) => { + let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default(); + Some(Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style, py: None }) + } + Err(_) => None, + }; let shm = cx.sheet_mut(sheet)?; match cell { Some(x) => shm.set_cell(c, x), diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index f6184509c3..c8921718c2 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -80,6 +80,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result { let text = pts.iter().map(|q| format!("{:.1},{:.1}", q[0] - minx, q[1] - miny)).collect::>().join(";"); let id = d.wb.next_object_id(); let shape = Shape { + math: Default::default(), id, kind: ShapeKind::Ink, anchor: Anchor { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 126c73c9a5..2aa9d8fe3d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -35,7 +35,7 @@ use go_to::go_to_special; #[cfg(test)] use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; use paste_special::paste_special; -pub(crate) use paste_special::rewrite_all_formulas; +pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs}; use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_set}; pub fn specs() -> Vec { @@ -81,15 +81,18 @@ pub fn specs() -> Vec { has_doc, paste ), - cmd!( - "edit.pasteSpecial", - "Paste Special…", - ["Home", "Clipboard"], - Some("Ctrl+Cmd+V"), - "{what: all|formulas|values|formats|comments|validation|allExceptBorders|columnWidths|formulasAndNumberFormats|valuesAndNumberFormats, operation?: none|add|subtract|multiply|divide, skipBlanks?, transpose?, link?}", - has_clipboard, - paste_special - ), + CommandSpec { + shortcut_mac: Some("Ctrl+Cmd+V"), + ..cmd!( + "edit.pasteSpecial", + "Paste Special…", + ["Home", "Clipboard"], + Some("Ctrl+Alt+V"), + "{what: all|formulas|values|formats|comments|validation|allExceptBorders|columnWidths|formulasAndNumberFormats|valuesAndNumberFormats, operation?: none|add|subtract|multiply|divide, skipBlanks?, transpose?, link?}", + has_clipboard, + paste_special + ) + }, cmd!(noundo "edit.clearClipboard", "Cancel Copy", [], Some("Escape"), "{}", has_doc, clear_clipboard), cmd!("edit.clearAll", "Clear All", ["Home", "Editing", "Clear"], None, "{range?}", has_doc, |s, p| clear(s, p, "all")), cmd!("edit.clearFormats", "Clear Formats", ["Home", "Editing", "Clear"], None, "{range?}", has_doc, |s, p| clear(s, p, "formats")), @@ -129,7 +132,7 @@ pub fn specs() -> Vec { "Replace…", ["Home", "Editing", "Find & Select"], Some("Ctrl+H"), - "{what, with, matchCase?, wholeCell?, all?: true, within?: sheet|workbook}", + "{what, with, matchCase?, wholeCell?, all?: true, within?: sheet|workbook} → {replaced, skipped?} (in a Python cell the code is edited; skipped counts Python cells whose code would no longer fit)", has_doc, replace ), @@ -264,6 +267,7 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result { for (_, cell) in cells.iter_mut() { let checkbox = cx.wb.styles.get(cell.style).num_fmt.as_str() == "checkbox"; cell.formula = None; + cell.py = None; if checkbox && uncheck_only { cell.value = Value::Bool(false); } else { diff --git a/crates/engine/src/cmd/edit/cell.rs b/crates/engine/src/cmd/edit/cell.rs index 8eb9075bfe..6101356824 100644 --- a/crates/engine/src/cmd/edit/cell.rs +++ b/crates/engine/src/cmd/edit/cell.rs @@ -5,6 +5,9 @@ use super::{ // ---------------------------------------------------------------- entry +/// Typing `=PY(` doesn't make a Python cell; this says what does. +pub(crate) const PY_FORMULA: &str = "Python cells are made with the python.set command (the code as `code`), not by typing =PY(…)."; + /// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or /// a parenthesis (not a number), as Excel takes `+SUM(1)`. pub(crate) fn is_formula_input(input: &str) -> bool { @@ -21,14 +24,18 @@ pub(crate) fn is_formula_input(input: &str) -> bool { pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); if input.is_empty() { - let c = Cell { value: Value::Empty, formula: None, style }; + let c = Cell { value: Value::Empty, formula: None, style, py: None }; return Ok(if c.is_blank() { None } else { Some(c) }); } let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; if fmt_is_text { - return Ok(Some(Cell { value: Value::text(input), formula: None, style })); + return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None })); } - if is_formula_input(input) { + let is_formula = is_formula_input(input); + if is_formula && gridcraft_model::python::is_py_formula(input) { + return Err(EngineError::Other(PY_FORMULA.into())); + } + if is_formula { let body = input.strip_prefix('=').unwrap_or(input); let expr = wb.name_call_case(parse_typed_formula(body)?); check_arg_counts(&expr)?; @@ -79,7 +86,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri if input.contains('\n') && !wb.styles.get(style).align.wrap { style = wb.styles.derive(style, |s| s.align.wrap = true); } - Ok(Some(Cell { value: parsed.value, formula: None, style })) + Ok(Some(Cell { value: parsed.value, formula: None, style, py: None })) } /// Parses a formula as it is typed (without the `=`). Excel closes missing parentheses for you, @@ -147,7 +154,7 @@ pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; // The array takes the whole range: other cells in it lose their contents. for c in range.iter().skip(1).take(1_000_000) { - if let Some(old) = sh.cells.get(c).filter(|x| !x.value.is_empty() || x.formula.is_some()) { + if let Some(old) = sh.cells.get(c).filter(|x| x.has_content()) { let style = old.style; sh.set_cell(c, Cell { style, ..Cell::default() }); } @@ -239,10 +246,14 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result { value: Value::number(n.as_f64().unwrap_or(0.0)), formula: None, style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), + py: None, + }), + Json::Bool(b) => Some(Cell { + value: Value::Bool(*b), + formula: None, + style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), + py: None, }), - Json::Bool(b) => { - Some(Cell { value: Value::Bool(*b), formula: None, style: cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default() }) - } // Text as given: no date or number reading, and a leading `'` is part of the // text rather than the marker that makes it text. A formula is still a // formula, which is what the ticket asks for and what `=` means in a cell. @@ -258,7 +269,7 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result { if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { style = cx.wb.styles.derive(style, |s| s.align.wrap = true); } - Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style }) + Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None }) } } _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index de921226e1..3a1cd07390 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -92,7 +92,7 @@ fn slide_together(wb: &gridcraft_model::Workbook, sheet: usize, areas: &[RangeRe for c in cells { let Some(to) = c.offset(dr, dc) else { continue }; let style = src.cell(c).map(|x| x.style).unwrap_or_default(); - dst.set_cell(to, Cell { value: src.value(c), formula: None, style }); + dst.set_cell(to, Cell { value: src.value(c), formula: None, style, py: None }); if let Some(picture) = src.cell_pictures.get(&c) { dst.cell_pictures.insert(to, picture.clone()); } diff --git a/crates/engine/src/cmd/edit/find.rs b/crates/engine/src/cmd/edit/find.rs index bce0ba728d..0d4656320e 100644 --- a/crates/engine/src/cmd/edit/find.rs +++ b/crates/engine/src/cmd/edit/find.rs @@ -115,6 +115,7 @@ pub(super) fn replace(s: &mut Session, p: &Json) -> Result { let all = bool_param(p, "all").unwrap_or(true); let workbook = str_param(p, "within") == Some("workbook"); let active = s.doc()?.selection.active; + let mut skipped = 0usize; let n = edit(s, |cx| { let sheets: Vec = if workbook { (0..cx.wb.sheets.len()).collect() } else { vec![cx.wb.active_sheet()] }; let mut n = 0; @@ -135,6 +136,30 @@ pub(super) fn replace(s: &mut Session, p: &Json) -> Result { } else { replace_ci(&text, &what, &with) }; + // A Python cell's text is its code: the replacement edits the code and the cell + // stays a Python cell. Code that would no longer fit in a PY formula is left as it was. + let old_py = cx.wb.sheet(si).and_then(|sh| sh.cell(c)).and_then(|x| x.py.clone()); + if let Some(old) = old_py { + let py = gridcraft_model::PyCode { object: old.object, ..gridcraft_model::PyCode::new(&new) }; + if py.code == old.code { + continue; + } + if !py.fits() { + skipped += 1; + continue; + } + // Its old spill is left to the recalculation, which removes it and + // recalculates what read it. + let sh = cx.sheet_mut(si)?; + let style = sh.style_id(c); + sh.set_cell( + c, + Cell { value: Value::Error(gridcraft_core::CellError::Blocked), formula: None, style, py: Some(std::sync::Arc::new(py)) }, + ); + cx.touch(si, c); + n += 1; + continue; + } let cell = input_to_cell(&new, si, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(new.as_str())))); let sh = cx.sheet_mut(si)?; match cell { @@ -149,6 +174,9 @@ pub(super) fn replace(s: &mut Session, p: &Json) -> Result { } Ok(n) })?; + if skipped > 0 { + return Ok(json!({"replaced": n, "skipped": skipped})); + } Ok(json!({"replaced": n})) } diff --git a/crates/engine/src/cmd/edit/go_to.rs b/crates/engine/src/cmd/edit/go_to.rs index bc4f414db4..0cd7a3de9f 100644 --- a/crates/engine/src/cmd/edit/go_to.rs +++ b/crates/engine/src/cmd/edit/go_to.rs @@ -174,8 +174,8 @@ pub(super) fn go_to_special(s: &mut Session, p: &Json) -> Result { let v = sheet.value(c); let ok = match kind { "blanks" => v.is_empty(), - "constants" => cell.is_some_and(|x| x.formula.is_none() && !x.value.is_empty()), - "formulas" => cell.is_some_and(|x| x.formula.is_some()), + "constants" => cell.is_some_and(|x| x.formula.is_none() && x.py.is_none() && !x.value.is_empty()), + "formulas" => cell.is_some_and(|x| x.formula.is_some() || x.py.is_some()), "comments" | "notes" => sheet.comments.contains_key(&c), "errors" => v.is_error(), "numbers" => v.is_number(), diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index 0a6d14247f..2477dc1a66 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -145,6 +145,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } moved_formulas = taken; } + let dest_name = cx.wb.sheet(dest_sheet).map(|sh| sh.name.clone()).unwrap_or_default(); for (tr, tc, r, c) in tiled_cells(src.height(), src.width(), tiles_r, tiles_c) { let sc = CellRef::new(src.start.row + r, src.start.col + c); let (dr, dc) = if transpose { (c, r) } else { (r, c) }; @@ -152,7 +153,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let src_cell = if cut_move { moved_formulas.iter().find(|(k, _)| *k == sc).map(|(_, v)| v.clone()) } else { src_sheet.cell(sc).cloned() }; let src_val = src_sheet.value(sc); let src_picture = if cut_move { moved_pictures.get(&sc) } else { src_sheet.cell_pictures.get(&sc) }.cloned(); - if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none()) { + if skip_blanks && src_picture.is_none() && src_val.is_empty() && src_cell.as_ref().is_none_or(|x| x.formula.is_none() && x.py.is_none()) { continue; } let old = cx.wb.sheet(dest_sheet).and_then(|sh| sh.cell(dest)).cloned().unwrap_or_default(); @@ -186,6 +187,33 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) })) }; + // A Python cell's code travels with it. Cut to another sheet, it keeps reading the + // cells its `xl()` references named on its original sheet, as a moved formula does: + // they are qualified with that sheet before the workbook-wide move adjustment below. + let moved_py = |cell: &Cell| -> Result>> { + let Some(py) = cell.py.clone() else { return Ok(None) }; + if !cut_move || dest_sheet == clip.sheet { + return Ok(Some(py)); + } + let qualified = gridcraft_model::python::rewrite_xl(&py.code, |reference| { + let e = gridcraft_formula::parse(reference).ok()?.map(&mut |x| match x { + gridcraft_formula::Expr::Ref(mut r) if r.sheet == gridcraft_formula::SheetSel::Current => { + r.sheet = gridcraft_formula::SheetSel::Named(src_sheet_name.clone()); + gridcraft_formula::Expr::Ref(r) + } + other => other, + }); + Some(gridcraft_formula::print(&e)) + }); + Ok(Some(match qualified { + Some(code) => { + let moved = gridcraft_model::PyCode { code, ..(*py).clone() }; + check_python_fits(&moved, &dest_name, dest)?; + std::sync::Arc::new(moved) + } + None => py, + })) + }; if link { let sheet_prefix = if dest_sheet == clip.sheet && same_doc { String::new() @@ -194,6 +222,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { }; new.formula = Some(std::sync::Arc::new(Formula::new(&format!("={sheet_prefix}{}", sc.a1())))); new.value = Value::Empty; + new.py = None; new_picture = None; } else { let sc_cell = src_cell.clone().unwrap_or_default(); @@ -202,6 +231,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { new_picture = src_picture.clone(); new.formula = shift(&sc_cell); new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; let st = map_style(sc_cell.style, &mut cx.wb); new.style = if what == What::AllExceptBorders { let borders = cx.wb.styles.get(old.style).borders; @@ -214,6 +244,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { new_picture = src_picture.clone(); new.formula = shift(&sc_cell); new.value = if new.formula.is_some() { Value::Empty } else { sc_cell.value.clone() }; + new.py = moved_py(&sc_cell)?; if what == What::FormulasAndNumberFormats { let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); new.style = cx.wb.styles.derive(old.style, |s| s.num_fmt = nf); @@ -222,6 +253,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { What::Values | What::ValuesAndNumberFormats => { new_picture = src_picture.clone(); new.formula = None; + new.py = None; new.value = src_val.clone(); if what == What::ValuesAndNumberFormats { let nf = src_wb.styles.get(sc_cell.style).num_fmt.clone(); @@ -232,7 +264,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { What::Comments | What::Validation | What::ColumnWidths => {} } // Operations combine numbers with what is already there. - if op != "none" && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) && new.formula.is_none() { + if op != "none" + && matches!(what, What::All | What::Values | What::ValuesAndNumberFormats | What::Formulas) + && new.formula.is_none() + && new.py.is_none() + { if old_picture.is_some() || new_picture.is_some() { new_picture = None; new.value = Value::Error(gridcraft_core::CellError::Value); @@ -292,7 +328,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } else { gridcraft_formula::adjust::Edit::MoveToSheet { from: src, to_sheet: dest_name, to_row: at.row, to_col: at.col } }; - rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e); + rewrite_all_formulas(&mut cx.wb, &src_sheet_name, &e)?; cx.structural = true; } let end = at.offset_clamped((tiles_r * h) as i64 - 1, (tiles_c * w) as i64 - 1); @@ -316,7 +352,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result { } /// Applies a reference adjustment to every cell formula and defined name in the workbook. -pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) { +pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { use gridcraft_formula::adjust::Edit; // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too // (a cut moves its arrays itself). @@ -355,4 +391,109 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: & n.formula = gridcraft_formula::print(&new); } } + rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)); + rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)) +} + +/// Runs `f` over every reference a floating object holds (a chart's series values, categories, +/// name and bubble sizes, and the source block it was made from). Every edit that moves +/// references calls it: inserting and deleting lines and cells and cut-moves (through +/// [`rewrite_all_formulas`]), and renaming and deleting sheets. `f` maps a reference held by an +/// object on the sheet named `host` to its new form; text that does not parse is kept. A source +/// block that no longer exists is dropped. +pub(crate) fn rewrite_cell_links(wb: &mut gridcraft_model::Workbook, f: impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr) { + for si in 0..wb.sheets.len() { + let Some(host) = wb.sheets.get(si).filter(|s| !s.charts.is_empty()).map(|s| s.name.clone()) else { continue }; + let Some(sh) = wb.sheet_mut(si) else { continue }; + let fix = |text: &str| -> String { + match gridcraft_formula::parse(text) { + Ok(expr) => gridcraft_formula::print(&f(&host, expr)), + Err(_) => text.to_string(), + } + }; + for ch in sh.charts.iter_mut() { + ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!")); + for se in ch.series.iter_mut() { + se.values = fix(&se.values); + se.categories = se.categories.as_deref().map(fix); + se.name = se.name.as_deref().map(fix); + se.bubble_sizes = se.bubble_sizes.as_deref().map(fix); + } + } + } +} + +/// Rewrites the `xl("…")` literals in every Python cell with `f`, which maps a reference held on +/// sheet `host` to its new form. Every reference-moving edit (insert and delete of lines or cells, +/// cut-move, sheet rename and delete) runs it, as it adjusts formulas. A literal is only replaced +/// when the reference it names changed, and text that doesn't parse is kept. A cell's cached +/// result is kept while its references still name the same data (a rename, a move); a reference +/// the edit deleted (`#REF!`), or one that grew or shrank (rows or columns inserted or deleted +/// inside it), leaves the result stale, so the cell is new code (`#BLOCKED!`) and the +/// recalculation removes its spill. A rewrite that would +/// make a cell's code longer than one cell holds (a longer sheet name, `Z1` becoming `AA1`) refuses +/// the whole edit, which then changes nothing: see [`check_python_fits`]. +pub(crate) fn rewrite_python_refs( + wb: &mut gridcraft_model::Workbook, + f: &impl Fn(&str, gridcraft_formula::Expr) -> gridcraft_formula::Expr, +) -> Result<()> { + for si in 0..wb.sheets.len() { + let Some(sh) = wb.sheets.get(si) else { continue }; + let host = sh.name.clone(); + let mut new_code: Vec<(CellRef, String, bool)> = Vec::new(); + for (c, cell) in sh.cells.iter() { + let Some(py) = &cell.py else { continue }; + let mut lost = false; + let changed = gridcraft_model::python::rewrite_xl(&py.code, |reference| { + let expr = gridcraft_formula::parse(reference).ok()?; + let before = gridcraft_formula::print(&expr); + let after = gridcraft_formula::print(&f(&host, expr)); + lost |= (after.contains("#REF!") && !before.contains("#REF!")) || area_shape(&before) != area_shape(&after); + (after != before).then_some(after) + }); + if let Some(code) = changed { + check_python_fits(&gridcraft_model::PyCode { code: code.clone(), object: py.object, ..Default::default() }, &host, c)?; + new_code.push((c, code, lost)); + } + } + if new_code.is_empty() { + continue; + } + let Some(sh) = wb.sheet_mut(si) else { continue }; + for (c, code, lost) in new_code { + if let Some(cell) = sh.cells.get_mut(c) + && let Some(py) = cell.py.as_mut() + { + let py = std::sync::Arc::make_mut(py); + py.code = code; + if lost { + py.output = None; + cell.value = Value::Error(gridcraft_core::CellError::Blocked); + } + } + } + } + Ok(()) +} + +/// The rows and columns a printed reference covers (`A1:B3`, `Sheet2!$A$1`, `C:E`), or `None` +/// for any other form (a name, an error). +fn area_shape(reference: &str) -> Option<(u32, u32)> { + let r = RangeRef::parse(reference.rsplit('!').next()?)?; + Some((r.height(), r.width())) +} + +/// Refuses Python code an edit has made longer than one cell holds: the limit `python.set` +/// enforces and opening a file applies (code over it is dropped to its value on open). The edit +/// is refused rather than made, so no code is lost and none keeps a reference the edit moved. +pub(crate) fn check_python_fits(py: &gridcraft_model::PyCode, sheet: &str, at: CellRef) -> Result<()> { + if py.fits() { + return Ok(()); + } + Err(EngineError::Other(format!( + "The edit would make the Python code in {}!{} longer than Excel's {}-character formula limit, so nothing was changed. Shorten the code first.", + gridcraft_formula::quote_sheet(sheet), + at.a1(), + gridcraft_model::python::MAX_FORMULA_CHARS + ))) } diff --git a/crates/engine/src/cmd/equation.rs b/crates/engine/src/cmd/equation.rs new file mode 100644 index 0000000000..d485a3535c --- /dev/null +++ b/crates/engine/src/cmd/equation.rs @@ -0,0 +1,305 @@ +//! Equations (Insert › Symbols › Equation): floating shapes holding LaTeX source, laid out by +//! `gridcraft-math` and drawn from the cached layout. +//! +//! An equation is drawn to fit its frame, so resizing the frame scales it. Inserting sizes the +//! frame for the requested font size; editing keeps the current scale and resizes the frame to +//! the new content. + +use gridcraft_math::{MathError, MathList}; +use gridcraft_model::{Anchor, AnchorMode, Color, EquationCache, Shape, ShapeKind}; +use serde_json::{Value as Json, json}; + +use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, cell_param, cmd, edit, f64_param, has_doc, ok, str_param, u32_param}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "insert.equation", + "Equation", + ["Insert", "Symbols"], + None, + "{latex: \"x^2\", cell?|at?: \"B2\", size?: 11 (points), color?: hex|\"auto\"}", + has_doc, + insert_equation + ), + cmd!("equation.edit", "Edit Equation", [], None, "{id, latex}", has_doc, edit_equation), + ] +} + +/// Default equation font size, in points. +pub const DEFAULT_SIZE_PT: f64 = 11.0; +/// Space between an equation's frame and its content, in sheet pixels. +pub const PADDING: f32 = 4.0; +/// Sheet pixels per point. +const PX_PER_PT: f64 = 96.0 / 72.0; + +/// The scale (sheet pixels per em) at which `list` fits a frame of `w` by `h` pixels. +pub fn fit_scale(list: &MathList, w: f32, h: f32) -> f32 { + let (cw, ch) = (list.width.max(0.01), list.total_height().max(0.01)); + let s = ((w - 2.0 * PADDING) / cw).min((h - 2.0 * PADDING) / ch); + if s.is_finite() { s.max(0.0) } else { 0.0 } +} + +/// The frame size for `list` at `scale` pixels per em. +fn frame_for(list: &MathList, scale: f32) -> (f32, f32) { + let w = list.width.max(0.5) * scale + 2.0 * PADDING; + let h = list.total_height().max(1.0) * scale + 2.0 * PADDING; + (w.clamp(8.0, 20_000.0), h.clamp(8.0, 20_000.0)) +} + +/// `latex` laid out, or a readable error with the position of the problem. +fn lay_out(cmd: &str, latex: &str) -> Result { + gridcraft_math::layout(latex).map_err(|e| bad(cmd, describe(latex, &e))) +} + +/// "Error at character 5: Undefined control sequence: \foo". +pub fn describe(latex: &str, e: &MathError) -> String { + match e.char_pos(latex) { + Some(p) => format!("equation error at character {p}: {}", e.message), + None => format!("equation error: {}", e.message), + } +} + +fn insert_equation(s: &mut Session, p: &Json) -> Result { + const CMD: &str = "insert.equation"; + let latex = str_param(p, "latex").ok_or_else(|| bad(CMD, "`latex` must be the equation's LaTeX source, such as \"x^2 + y^2 = r^2\""))?; + if latex.trim().is_empty() { + return Err(bad(CMD, "`latex` is empty")); + } + let size = f64_param(p, "size").unwrap_or(DEFAULT_SIZE_PT); + if !(1.0..=409.0).contains(&size) { + return Err(bad(CMD, "`size` must be between 1 and 409 points")); + } + let color = match p.get("color") { + None | Some(Json::Null) => Color::Auto, + Some(c) => super::format::color_param(Some(c)).ok_or_else(|| bad(CMD, "`color` must be a hex colour such as \"#1F4E79\", or \"auto\""))?, + }; + let list = lay_out(CMD, latex)?; + let at = match cell_param(s, p, "cell")? { + Some(c) => Some(c), + None => cell_param(s, p, "at")?, + }; + let d = s.doc()?; + if d.wb.active().is_some_and(|sh| sh.is_protected()) { + return Err(EngineError::Other(PROTECTED.into())); + } + let at = at.unwrap_or(d.selection.active); + let id = d.wb.next_object_id(); + let (width, height) = frame_for(&list, (size * PX_PER_PT) as f32); + let mut shape = Shape { + id, + kind: ShapeKind::Equation, + anchor: Anchor { cell: at, dx: 0.0, dy: 0.0, width, height, mode: AnchorMode::MoveOnly }, + fill: Color::Auto, + line: color, + text: latex.to_string(), + format: Default::default(), + math: Default::default(), + }; + shape.math.refresh(latex); + let sheet = d.wb.active_sheet(); + edit(s, |cx| { + cx.sheet_mut(sheet)?.shapes.push(shape); + Ok(json!({"equation": id})) + }) +} + +fn edit_equation(s: &mut Session, p: &Json) -> Result { + const CMD: &str = "equation.edit"; + let id = u32_param(p, "id").ok_or_else(|| bad(CMD, "`id` must be an equation id"))?; + let latex = str_param(p, "latex").ok_or_else(|| bad(CMD, "`latex` must be the equation's LaTeX source"))?; + if latex.trim().is_empty() { + return Err(bad(CMD, "`latex` is empty; delete the equation instead")); + } + let d = s.doc()?; + let sheet = d.wb.active_sheet(); + let sh = d.wb.active().ok_or_else(|| bad(CMD, "no such equation"))?; + let shape = sh.shapes.iter().find(|x| x.id == id && x.kind == ShapeKind::Equation).ok_or_else(|| bad(CMD, "no such equation"))?; + if sh.is_protected() { + return Err(EngineError::Other(PROTECTED.into())); + } + // The same source is a no-op, unless it has no layout yet (a file with more equations than + // are laid out at once): then OK lays it out. + if shape.text == latex && matches!(shape.math.get(latex), Some(Ok(_))) { + return ok(); + } + let list = lay_out(CMD, latex)?; + // Keep the size the equation is drawn at now; without a layout, use the default size. + let scale = match shape.math.get(&shape.text) { + Some(Ok(old)) => fit_scale(old, shape.anchor.width, shape.anchor.height), + _ => 0.0, + }; + let scale = if scale > 0.1 { scale } else { (DEFAULT_SIZE_PT * PX_PER_PT) as f32 }; + let (width, height) = frame_for(&list, scale); + edit(s, |cx| { + let shape = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|x| x.id == id).ok_or_else(|| bad(CMD, "no such equation"))?; + shape.text = latex.to_string(); + shape.math = EquationCache::default(); + shape.math.refresh(latex); + shape.anchor.width = width; + shape.anchor.height = height; + Ok(json!({"equation": id})) + }) +} + +// ---------------------------------------------------------------- PDF + +/// The first [`gridcraft_math::MAX_SOURCE_BYTES`] bytes of an equation's source, cut at a char +/// boundary. A longer source never lays out (the editor refuses it, and a file can carry one of +/// megabytes), so what shows it as text, the sheet painter and the PDF fallback, shows this much +/// and does no work on the rest. +pub fn source_excerpt(text: &str) -> &str { + let cap = gridcraft_math::MAX_SOURCE_BYTES; + if text.len() <= cap { + return text; + } + let mut end = cap; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.get(..end).unwrap_or("") +} + +/// The PDF face for a glyph: Symbol for Greek letters and operators, else the Times (or +/// Helvetica, Courier) face for its style. `None` when no standard font can show `c`. +fn pdf_font(c: char, face: gridcraft_math::Face) -> Option { + use gridcraft_math::Face; + use gridcraft_pdf::Font; + let text = match face { + Face::Italic => Font::TimesItalic, + Face::Bold => Font::TimesBold, + Face::BoldItalic => Font::TimesBoldItalic, + Face::Sans => Font::Helvetica, + Face::SansBold => Font::HelveticaBold, + Face::SansItalic => Font::HelveticaOblique, + Face::Mono => Font::Courier, + Face::Roman | Face::Large(_) => Font::TimesRoman, + }; + // Letters and digits stay in the text face; everything Symbol has goes to Symbol, whose + // operators (minus, equals, plus) match the maths better than the text faces'. + if c.is_ascii_alphanumeric() { + return Some(text); + } + if Font::Symbol.can_encode(c) { + return Some(Font::Symbol); + } + text.can_encode(c).then_some(text) +} + +/// Draws an equation's layout into the box `(x, y, w, h)` (page points) of a PDF page, with +/// `pad` points of padding. Glyphs no standard font has are drawn as `[?]` boxes. +pub(crate) fn draw_pdf(pg: &mut gridcraft_pdf::Page, list: &MathList, rect: (f32, f32, f32, f32), pad: f32, ink: gridcraft_pdf::Rgb) { + use gridcraft_math::{Face, Item, PathCmd}; + let (x, y, w, h) = rect; + let (cw, ch) = (list.width.max(0.01), list.total_height().max(0.01)); + let s = ((w - 2.0 * pad) / cw).min((h - 2.0 * pad) / ch); + if !(s.is_finite() && s > 0.01) { + return; + } + let s = s.min(4000.0); + let (ox, oy) = (x + (w - cw * s) / 2.0, y + (h - ch * s) / 2.0); + let col = |c: Option<[u8; 3]>| c.unwrap_or(ink); + for item in list.items.iter().take(gridcraft_math::MAX_ITEMS) { + match item { + Item::Glyph(g) => { + let color = col(g.color); + let (gx, base) = (ox + g.x * s, oy + g.y * s); + // The radical sign: Symbol's glyph (AFM bounding box -147 to 917 high, right edge + // at 558, in 1/1000 em) fitted to the TeX box, so its top meets the vinculum. + if g.ch == '\u{221A}' { + let size = (g.height + g.depth) * s / 1.064; + if size.is_finite() && size >= 0.5 { + let top = base - g.height * s; + pg.text(gx + g.width * s - 0.558 * size, top + 0.917 * size, size, gridcraft_pdf::Font::Symbol, color, "\u{221A}"); + } + continue; + } + let large = matches!(g.face, Face::Large(_)); + let size = if large { (g.height + g.depth) * s } else { g.size * s }; + if !(size.is_finite() && size >= 0.5) { + continue; + } + let pick = pdf_font(g.ch, g.face).map(|f| (g.ch, f)).or_else(|| g.alt.and_then(|a| pdf_font(a, g.face).map(|f| (a, f)))); + match pick { + Some((c, font)) => { + let text = c.to_string(); + if large { + // Centred on the glyph's box, like the screen. + let mid = oy + (g.y - (g.height - g.depth) / 2.0) * s; + let tw = gridcraft_pdf::text_width(font, size, &text); + pg.text(gx + (g.width * s - tw) / 2.0, mid + 0.25 * size, size, font, color, &text); + } else { + pg.text(gx, base, size, font, color, &text); + } + } + None => { + // [?]: the glyph's box with a question mark. + let (bw, bh) = ((g.width.max(0.3)) * s, (g.height + g.depth) * s); + pg.rect_stroke(gx, base - g.height * s, bw, bh, (0.05 * s).clamp(0.2, 1.0), color); + let qs = (bh * 0.6).min(bw * 1.2).max(1.0); + let qw = gridcraft_pdf::text_width(gridcraft_pdf::Font::Helvetica, qs, "?"); + pg.text(gx + (bw - qw) / 2.0, base - g.height * s + (bh + qs * 0.7) / 2.0, qs, gridcraft_pdf::Font::Helvetica, color, "?"); + } + } + } + Item::Rule(r) => { + if r.width > 0.0 && r.height > 0.0 { + pg.fill_rect(ox + r.x * s, oy + r.y * s, r.width * s, (r.height * s).max(0.25), col(r.color)); + } + } + Item::Path(p) => { + let (px, py) = (ox + p.x * s, oy + p.y * s); + let mut subs: Vec> = vec![]; + let mut cur: Vec<[f32; 2]> = vec![]; + let at = |a: f32, b: f32| [px + a * s, py + b * s]; + for c in &p.commands { + match *c { + PathCmd::MoveTo(a, b) => { + if cur.len() > 1 { + subs.push(std::mem::take(&mut cur)); + } + cur = vec![at(a, b)]; + } + PathCmd::LineTo(a, b) => cur.push(at(a, b)), + PathCmd::QuadTo(x1, y1, a, b) => { + let p0 = cur.last().copied().unwrap_or(at(x1, y1)); + let (c1, p1) = (at(x1, y1), at(a, b)); + for k in 1..=8 { + let t = k as f32 / 8.0; + let u = 1.0 - t; + cur.push([u * u * p0[0] + 2.0 * u * t * c1[0] + t * t * p1[0], u * u * p0[1] + 2.0 * u * t * c1[1] + t * t * p1[1]]); + } + } + PathCmd::CubicTo(x1, y1, x2, y2, a, b) => { + let p0 = cur.last().copied().unwrap_or(at(x1, y1)); + let (c1, c2, p1) = (at(x1, y1), at(x2, y2), at(a, b)); + for k in 1..=10 { + let t = k as f32 / 10.0; + let u = 1.0 - t; + let (a3, b3, c3, d3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + cur.push([a3 * p0[0] + b3 * c1[0] + c3 * c2[0] + d3 * p1[0], a3 * p0[1] + b3 * c1[1] + c3 * c2[1] + d3 * p1[1]]); + } + } + PathCmd::Close => { + if cur.len() > 1 { + subs.push(std::mem::take(&mut cur)); + } + } + } + } + if cur.len() > 1 { + subs.push(cur); + } + let color = col(p.color); + for sub in subs.iter().filter(|v| v.len() <= 4000) { + if p.fill && sub.len() >= 3 { + // The PDF fill rule handles concave outlines itself. + pg.polygon(sub, Some(color), None); + } else { + pg.polyline(sub, (0.05 * s).clamp(0.2, 1.0), color, &[]); + } + } + } + } + } +} diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index fd2a6e7a29..a6f66b41b6 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -3,8 +3,8 @@ use gridcraft_core::{CellRef, RangeRef, Value}; use gridcraft_model::{ - Anchor, Chart, Color, DefinedName, HAlign, LegendPos, NumFmt, Shape, Sheet, SheetViewMode, TableColumn, TotalsFn, Trendline, TrendlineKind, - Workbook, + Anchor, Chart, Color, DefinedName, HAlign, LegendPos, NumFmt, Shape, ShapeKind, Sheet, SheetViewMode, TableColumn, TotalsFn, Trendline, + TrendlineKind, Workbook, }; use serde_json::{Value as Json, json}; @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "Add Chart Element", ["Chart Design", "Chart Layouts"], None, - "{chart?, element: title|legend|dataLabels|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}", + "{chart?, element: title|legend|dataLabels|dataTable|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; dataTable: dataTableKeys?: bool, dataTableHorizontalBorder?: bool, dataTableVerticalBorder?: bool, dataTableOutline?: bool; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}", has_doc, add_element ), @@ -97,7 +97,7 @@ pub fn specs() -> Vec { "Bring Forward", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, id, toFront?: bool}", + "{kind: chart|image|shape|slicer|equation, id, toFront?: bool}", has_doc, |s, p| arrange(s, p, true) ), @@ -106,7 +106,7 @@ pub fn specs() -> Vec { "Send Backward", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, id, toBack?: bool}", + "{kind: chart|image|shape|slicer|equation, id, toBack?: bool}", has_doc, |s, p| arrange(s, p, false) ), @@ -116,7 +116,7 @@ pub fn specs() -> Vec { "Align", ["Page Layout", "Arrange"], None, - "{kind: chart|image|shape, ids: [..], align: left|center|right|top|middle|bottom}", + "{kind: chart|image|shape|slicer|equation, ids: [..], align: left|center|right|top|middle|bottom}", has_doc, align ), diff --git a/crates/engine/src/cmd/extra/cells.rs b/crates/engine/src/cmd/extra/cells.rs index 795d7f0117..838ce83422 100644 --- a/crates/engine/src/cmd/extra/cells.rs +++ b/crates/engine/src/cmd/extra/cells.rs @@ -51,6 +51,7 @@ pub(super) fn toggle_checkbox(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(si)?; if let Some(cell) = sh.cells.get_mut(c) && cell.formula.is_none() + && cell.py.is_none() { // An empty checkbox cell counts as FALSE. let next = match cell.value { diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs index b6761f1a97..8d9af2064d 100644 --- a/crates/engine/src/cmd/extra/chart.rs +++ b/crates/engine/src/cmd/extra/chart.rs @@ -43,6 +43,7 @@ pub(super) fn add_element(s: &mut Session, p: &Json) -> Result { } } "dataLabels" => c.data_labels = on, + "dataTable" => crate::cmd::insert::update_data_table(c, p, Some(on))?, "gridlines" => c.gridlines = on, "axisTitles" => { c.x_title = on.then(|| c.x_title.clone().unwrap_or_else(|| "Axis Title".into())); diff --git a/crates/engine/src/cmd/extra/objects.rs b/crates/engine/src/cmd/extra/objects.rs index 30725f81e7..fa5a5f438b 100644 --- a/crates/engine/src/cmd/extra/objects.rs +++ b/crates/engine/src/cmd/extra/objects.rs @@ -1,8 +1,29 @@ +use gridcraft_model::ObjKind; + use super::chart::format_series; use super::{ - Anchor, CellRef, Color, EngineError, Json, Result, Session, Shape, Sheet, anchor_mode_name, bad, bool_param, edit, json, str_param, u32_param, + Anchor, CellRef, Color, EngineError, Json, Result, Session, Shape, ShapeKind, Sheet, anchor_mode_name, bad, bool_param, edit, json, str_param, + u32_param, }; +/// The kind of object a `kind` parameter names: `shape` when the parameter is absent; one that +/// is present but not one of the names (`null`, a number, an unknown word) is an error, as for +/// the `object.*` commands, where the kind is required. +fn kind_param(p: &Json, cmd: &str) -> Result { + let err = || bad(cmd, "kind must be chart, image, shape, slicer or equation"); + match p.get("kind") { + None => Ok(ObjKind::Shape), + Some(Json::String(k)) => ObjKind::parse(k).ok_or_else(err), + Some(_) => Err(err()), + } +} + +/// Whether `kind` names the shape `sh`: an equation is a shape too, and a plain shape is not an +/// equation, as `Sheet::object_anchor` has it for the `object.*` commands. +fn shape_is(kind: ObjKind, sh: &Shape) -> bool { + kind != ObjKind::Equation || sh.kind == ShapeKind::Equation +} + pub(super) fn shape_fill(s: &mut Session, p: &Json) -> Result { if str_param(p, "kind") == Some("shape") { let color = str_param(p, "color").and_then(Color::from_hex).unwrap_or_default(); @@ -33,7 +54,7 @@ fn with_shape(s: &mut Session, p: &Json, f: impl FnOnce(&mut Shape)) -> Result Result { let id = u32_param(p, "id").ok_or_else(|| bad("arrange", "missing `id`"))?; - let kind = str_param(p, "kind").unwrap_or("shape").to_string(); + let kind = kind_param(p, "arrange")?; let extreme = bool_param(p, "toFront").or(bool_param(p, "toBack")).unwrap_or(false); let si = s.doc()?.wb.active_sheet(); fn reorder(v: &mut Vec, i: usize, forward: bool, extreme: bool) { @@ -51,23 +72,17 @@ pub(super) fn arrange(s: &mut Session, p: &Json, forward: bool) -> Result } edit(s, |cx| { let sh = cx.sheet_mut(si)?; - match kind.as_str() { - "chart" => { - if let Some(i) = sh.charts.iter().position(|c| c.id == id) { - reorder(&mut sh.charts, i, forward, extreme); - } + // An id that is not an object of this kind is an error, so a stale id, or a shape's id + // given as an equation, never reorders something else or succeeds silently. + let found = match kind { + ObjKind::Chart => sh.charts.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.charts, i, forward, extreme)), + ObjKind::Image => sh.images.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.images, i, forward, extreme)), + ObjKind::Slicer => sh.slicers.iter().position(|c| c.id == id).map(|i| reorder(&mut sh.slicers, i, forward, extreme)), + ObjKind::Shape | ObjKind::Equation => { + sh.shapes.iter().position(|c| c.id == id && shape_is(kind, c)).map(|i| reorder(&mut sh.shapes, i, forward, extreme)) } - "image" => { - if let Some(i) = sh.images.iter().position(|c| c.id == id) { - reorder(&mut sh.images, i, forward, extreme); - } - } - _ => { - if let Some(i) = sh.shapes.iter().position(|c| c.id == id) { - reorder(&mut sh.shapes, i, forward, extreme); - } - } - } + }; + found.ok_or_else(|| bad("arrange", "no such object"))?; Ok(Json::Null) }) } @@ -77,7 +92,8 @@ pub(super) fn selection_pane(s: &mut Session, _: &Json) -> Result { let sh = d.wb.active().ok_or(EngineError::NoDocument)?; let mut v = Vec::new(); for c in &sh.shapes { - v.push(json!({"kind": "shape", "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + let kind = if c.kind == ShapeKind::Equation { "equation" } else { "shape" }; + v.push(json!({"kind": kind, "id": c.id, "name": format!("{:?} {}", c.kind, c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); } for c in &sh.images { v.push(json!({"kind": "image", "id": c.id, "name": format!("Picture {}", c.id), "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); @@ -85,33 +101,51 @@ pub(super) fn selection_pane(s: &mut Session, _: &Json) -> Result { for c in &sh.charts { v.push(json!({"kind": "chart", "id": c.id, "name": format!("Chart {}", c.id), "title": c.title, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); } + // Slicers paint above the other objects. + for c in &sh.slicers { + let name = if c.caption.is_empty() { &c.column } else { &c.caption }; + v.push(json!({"kind": "slicer", "id": c.id, "name": name, "at": c.anchor.cell.a1(), "anchorMode": anchor_mode_name(c.anchor.mode)})); + } Ok(Json::Array(v)) } -fn anchors_of<'a>(sh: &'a mut Sheet, kind: &str) -> Vec<(u32, &'a mut Anchor)> { +/// The anchors of every object of `kind` on the sheet; under `equation`, only the equations. +fn anchors_of(sh: &mut Sheet, kind: ObjKind) -> Vec<(u32, &mut Anchor)> { match kind { - "chart" => sh.charts.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), - "image" => sh.images.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), - _ => sh.shapes.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Chart => sh.charts.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Image => sh.images.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Slicer => sh.slicers.iter_mut().map(|c| (c.id, &mut c.anchor)).collect(), + ObjKind::Shape | ObjKind::Equation => sh.shapes.iter_mut().filter(|c| shape_is(kind, c)).map(|c| (c.id, &mut c.anchor)).collect(), } } pub(super) fn align(s: &mut Session, p: &Json) -> Result { - let kind = str_param(p, "kind").unwrap_or("shape").to_string(); - let ids: Vec = - p.get("ids").and_then(Json::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()).unwrap_or_default(); + let kind = kind_param(p, "arrange.align")?; + // `ids` may be absent (nothing to align) but, present, must be an array whose every entry is + // an object id naming an object of the kind: a stale or mismatched id, or a value of another + // shape, is an error, as for `arrange` and the `object.*` commands, not something silently + // left out. + let bad_ids = || bad("arrange.align", "ids must be an array of object ids"); + let ids: Vec = match p.get("ids") { + None => Vec::new(), + Some(Json::Array(a)) => a.iter().map(|v| v.as_u64().and_then(|x| u32::try_from(x).ok()).ok_or_else(bad_ids)).collect::>()?, + Some(_) => return Err(bad_ids()), + }; let how = str_param(p, "align").unwrap_or("left").to_string(); let si = s.doc()?.wb.active_sheet(); edit(s, |cx| { let sheet = cx.sheet_mut(si)?; let geo: Vec<(u32, f64, f64, f32, f32)> = { let shc = sheet.clone(); - anchors_of(sheet, &kind) + anchors_of(sheet, kind) .into_iter() .filter(|(id, _)| ids.contains(id)) .map(|(id, a)| (id, shc.col_left(a.cell.col) + a.dx as f64, shc.row_top(a.cell.row) + a.dy as f64, a.width, a.height)) .collect() }; + if let Some(missing) = ids.iter().find(|id| !geo.iter().any(|g| g.0 == **id)) { + return Err(bad("arrange.align", format!("no such object: {missing}"))); + } if geo.len() < 2 { return Ok(Json::Null); } @@ -120,7 +154,7 @@ pub(super) fn align(s: &mut Session, p: &Json) -> Result { let top = geo.iter().map(|g| g.2).fold(f64::INFINITY, f64::min); let bottom = geo.iter().map(|g| g.2 + g.4 as f64).fold(f64::NEG_INFINITY, f64::max); let shc = sheet.clone(); - for (id, a) in anchors_of(sheet, &kind) { + for (id, a) in anchors_of(sheet, kind) { let Some(g) = geo.iter().find(|g| g.0 == id) else { continue }; let (mut x, mut y) = (g.1, g.2); match how.as_str() { diff --git a/crates/engine/src/cmd/extra/scripts.rs b/crates/engine/src/cmd/extra/scripts.rs index b14fbdb234..e9b8776722 100644 --- a/crates/engine/src/cmd/extra/scripts.rs +++ b/crates/engine/src/cmd/extra/scripts.rs @@ -138,7 +138,7 @@ pub(super) fn run_script(s: &mut Session, p: &Json) -> Result { let opened_dialog = s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::Dialog(..)))); let changed = wb_before.as_ref().is_some_and(|(uid, wb)| s.docs.iter().any(|d| d.uid == *uid && !std::sync::Arc::ptr_eq(&d.wb, wb))); if !opened_dialog || changed { - ran_steps.push((id.to_string(), crate::record::with_toggle_state(st["params"].clone(), &result))); + ran_steps.push((id.to_string(), crate::record::with_toggle_state(id, st["params"].clone(), &result))); } } } diff --git a/crates/engine/src/cmd/forecast.rs b/crates/engine/src/cmd/forecast.rs index 9bb15936b2..3c62e469f5 100644 --- a/crates/engine/src/cmd/forecast.rs +++ b/crates/engine/src/cmd/forecast.rs @@ -315,7 +315,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result { let vstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = vfmt.clone()); let mut sheet = Sheet::new(sheet_name.clone()); let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| { - sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style }); + sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style, py: None }); }; let formula = |sheet: &mut Sheet, row: u32, col: u32, text: String, style: StyleId| { let mut cell = Cell::formula(Formula::new(&text)); @@ -424,6 +424,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result { series, legend: LegendPos::Bottom, data_labels: false, + data_table: None, gridlines: true, style: 1, x_title: None, diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 69123dcfad..1066f48e2e 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -90,8 +90,14 @@ pub fn specs() -> Vec { format_cells ), // Alignment - cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)), - cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)), + CommandSpec { + shortcut_mac: Some("Cmd+L"), + ..cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)) + }, + CommandSpec { + shortcut_mac: Some("Cmd+E"), + ..cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)) + }, cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)), cmd!("home.justify", "Justify", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Justify)), cmd!("home.alignTop", "Top Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Top)), @@ -650,8 +656,7 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let others: Vec = sh.cells.iter_range(m).map(|(c, _)| c).filter(|c| *c != m.start).collect(); for c in others { if let Some(mut cell) = sh.cells.get(c).cloned() { - cell.value = gridcraft_core::Value::Empty; - cell.formula = None; + cell.clear_content(); sh.set_cell(c, cell); } touched.push((sheet, c)); @@ -668,8 +673,7 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let others: Vec = sh.cells.iter_range(*r).map(|(c, _)| c).filter(|c| *c != r.start).collect(); for c in others { if let Some(mut cell) = sh.cells.get(c).cloned() { - cell.value = gridcraft_core::Value::Empty; - cell.formula = None; + cell.clear_content(); sh.set_cell(c, cell); } touched.push((sheet, c)); @@ -686,7 +690,10 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result { let blocked = sh .cells .iter_range(reach) - .filter(|(_, x)| x.formula.is_some() && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill)); + // A Python cell's result is blocked and unblocked like a formula's. + .filter(|(_, x)| { + (x.formula.is_some() || x.py.is_some()) && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill) + }); touched.extend(blocked.map(|(c, _)| (sheet, c))); } cx.changed.extend(touched); diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index c9d8acec9a..d72f814a18 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -69,6 +69,15 @@ pub fn specs() -> Vec { ), cmd!(query "formulas.tracePrecedents", "Trace Precedents", ["Formulas", "Formula Auditing"], None, "{cell?} → ranges", has_doc, trace_precedents), cmd!(query "formulas.traceDependents", "Trace Dependents", ["Formulas", "Formula Auditing"], None, "{cell?} → cells", has_doc, trace_dependents), + cmd!( + query "formulas.traceError", + "Trace Error", + ["Formulas", "Formula Auditing"], + None, + "{cell?} → {sheet, cell, error, source: {sheet, cell}, arrows: [{from: {sheet, range}, to: {sheet, cell}, kind: \"error\"|\"precedent\"}], truncated}: from the cell, follows the first reference that shows the same error (in a range, its first cell showing it) back to the cell the error starts in, `source`. `error` arrows link the cells on the way; `precedent` arrows lead from the source's own references into it. A cell without an error gives `error` and `source` null and no arrows. A chain longer than 10,000 links stops there with `truncated` true and `source` null.", + has_doc, + trace_error + ), cmd!(noundo "formulas.selectPrecedents", "Select Precedents", ["Formulas", "Formula Auditing"], Some("Ctrl+["), "{cell?, all?: true = every level (Ctrl+Shift+[)} → selects the precedent cells", has_doc, select_precedents), cmd!(noundo "formulas.selectDependents", "Select Dependents", ["Formulas", "Formula Auditing"], Some("Ctrl+]"), "{cell?, all?: true = every level (Ctrl+Shift+])}", has_doc, select_dependents), cmd!(noundo "formulas.removeArrows", "Remove Arrows", ["Formulas", "Formula Auditing"], None, "{}", has_doc, |_, _| ok()), @@ -626,7 +635,7 @@ fn paste_name(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; let style = sh.style_id(c); // The second column holds the refers-to text as a text value, with no formula. - sh.set_cell(c, Cell { value: Value::text(text.as_str()), formula: None, style }); + sh.set_cell(c, Cell { value: Value::text(text.as_str()), formula: None, style, py: None }); cx.touch(sheet, c); } } @@ -653,6 +662,79 @@ fn trace_dependents(s: &mut Session, p: &Json) -> Result { Ok(Json::Array(v)) } +/// Trace Error goes back at most this many links; a longer chain stops there. +const TRACE_ERROR_LINKS: usize = 10_000; + +/// Trace Error: from the cell, the first reference in its formula that shows the same error +/// (in a range, the range's first cell showing it, row by row), then that cell's, and so on to the +/// cell the error starts in: one none of whose references shows it, or one without references. +/// Arrows link the cells on the way, and lead from the source's own references into it. +fn trace_error(s: &mut Session, p: &Json) -> Result { + use std::collections::HashSet; + let d = s.doc()?; + let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active); + let sheet = d.wb.active_sheet(); + let name = |si: usize| d.wb.sheet(si).map(|sh| sh.name.clone()); + let cell = |(si, c): (usize, CellRef)| json!({"sheet": name(si), "cell": c.a1()}); + let Some(error) = d.wb.sheet(sheet).and_then(|sh| sh.value(at).as_error()) else { + return Ok(json!({"sheet": name(sheet), "cell": at.a1(), "error": null, "source": null, "arrows": [], "truncated": false})); + }; + // A value spilled by a dynamic array comes from its anchor's formula. + let precedents = |(si, c): (usize, CellRef)| { + let anchor = d.wb.sheet(si).filter(|sh| sh.cell(c).is_none_or(|x| x.formula.is_none())).and_then(|sh| sh.spill_anchor(c)); + d.calc.graph.precedents_of((si, anchor.unwrap_or(c))) + }; + // The walk keeps to cells it hasn't been to, so a circular reference ends it. + let mut chain = vec![(sheet, at)]; + let mut seen: HashSet<(usize, CellRef)> = HashSet::from([(sheet, at)]); + let mut truncated = false; + let mut last = (sheet, at); + while let Some(next) = precedents(last).iter().find_map(|a| first_showing(&d.wb, a, error)) { + if !seen.insert(next) { + break; + } + if chain.len() > TRACE_ERROR_LINKS { + truncated = true; + break; + } + chain.push(next); + last = next; + } + let mut arrows = Vec::new(); + // A chain cut short hasn't reached its source. + if !truncated { + let mut drawn = HashSet::new(); + for a in precedents(last) { + if drawn.insert(a) { + arrows.push(json!({"from": {"sheet": name(a.sheet), "range": a.range.a1()}, "to": cell(last), "kind": "precedent"})); + } + } + } + // From the source outwards, as the error travels. + for pair in chain.windows(2).rev() { + if let [to, from] = pair { + arrows.push(json!({"from": {"sheet": name(from.0), "range": from.1.a1()}, "to": cell(*to), "kind": "error"})); + } + } + let source = if truncated { Json::Null } else { cell(last) }; + Ok(json!({"sheet": name(sheet), "cell": at.a1(), "error": error.as_str(), "source": source, "arrows": arrows, "truncated": truncated})) +} + +/// The first cell of an area, row by row, that shows `error`: a stored cell or a value spilled +/// into the area by a dynamic array. +fn first_showing(wb: &Workbook, a: &gridcraft_calc::Area, error: CellError) -> Option<(usize, CellRef)> { + let sh = wb.sheet(a.sheet)?; + let holds = |c: &Cell| !c.value.is_empty() || c.formula.is_some(); + let stored = sh.cells.iter_range(a.range).find(|(_, c)| holds(c) && c.value.as_error() == Some(error)).map(|(at, _)| at); + let spilled = sh + .spill + .range(a.range.start..) + .take_while(|(at, _)| **at <= a.range.end) + .find(|(at, v)| a.range.contains(**at) && v.as_error() == Some(error) && !sh.cell(**at).is_some_and(holds)) + .map(|(at, _)| *at); + stored.into_iter().chain(spilled).min().map(|c| (a.sheet, c)) +} + /// Excel's Ctrl+[ / Ctrl+]: select the precedent (or dependent) cells. When they all live on /// another sheet, jump there. `all` walks every level (Ctrl+Shift+[ / Ctrl+Shift+]). fn select_trace_cells(s: &mut Session, p: &Json, precedents: bool) -> Result { diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index d55af2b6ff..dbd4d9d782 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -1,12 +1,12 @@ //! Insert tab: tables, charts, sparklines, pictures, shapes, hyperlinks, comments and notes, //! conditional formatting (Home › Styles) and symbols. -use gridcraft_core::{CellRef, MAX_ROWS, RangeRef}; +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; use gridcraft_formula::adjust::{Axis, Edit}; use gridcraft_model::{ Anchor, BorderLine, BorderStyle, Borders, Cell, CellPicture, CfOperator, CfRule, CfValueKind, Chart, ChartKind, Color, Comment, CondFormat, Fill, - Formula, Hyperlink, Image, LegendPos, Series, Shape, ShapeKind, Sheet, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn, Underline, - Workbook, + Formula, Hyperlink, Image, LegendPos, ObjKind, ObjRef, Series, Shape, ShapeKind, Sheet, Sparkline, SparklineKind, Style, Table, TableColumn, + TotalsFn, Underline, Workbook, }; use serde_json::{Value as Json, json}; @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Chart Properties", ["Chart Design"], None, - "{chart?: id, type?, subtype?, title?, legend?: none|bottom|top|left|right, dataLabels?, gridlines?, quartiles?: exclusive|inclusive, style?, xTitle?, yTitle?, at?, width?, height?, dx?, dy?}", + "{chart?: id, type?, subtype?, title?, legend?: none|bottom|top|left|right, dataLabels?, gridlines?, dataTable?: bool, dataTableKeys?: bool, dataTableHorizontalBorder?: bool, dataTableVerticalBorder?: bool, dataTableOutline?: bool (data tables: column/bar/line/area and compatible combo charts), quartiles?: exclusive|inclusive, style?, xTitle?, yTitle?, at?, width?, height?, dx?, dy?}", has_doc, chart_set ), @@ -146,14 +146,22 @@ pub fn specs() -> Vec { &with(p, "kind", json!("textBox")) )), cmd!("shape.setText", "Edit Text Box", [], None, "{id: textBox id, text: string}", has_doc, shape_set_text), - cmd!("object.delete", "Delete Object", [], None, "{kind: chart|image|shape, id}", has_doc, delete_object), - cmd!("object.move", "Move Object", [], None, "{kind: chart|image|shape, id, at?: \"C3\", dx?, dy?, width?, height?}", has_doc, move_object), + cmd!("object.delete", "Delete Object", [], None, "{kind: chart|image|shape|slicer|equation, id}", has_doc, delete_object), + cmd!( + "object.move", + "Move Object", + [], + None, + "{kind: chart|image|shape|slicer|equation, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger)}", + has_doc, + move_object + ), cmd!( "object.setAnchorMode", "Object Properties", [], None, - "{kind: chart|image|shape, id, mode: moveAndSize|moveOnly|absolute}", + "{kind: chart|image|shape|slicer|equation, id, mode: moveAndSize|moveOnly|absolute}", has_doc, set_anchor_mode ), @@ -234,14 +242,30 @@ fn block(s: &Session, p: &Json) -> Result { } fn chart_areas(s: &Session, p: &Json) -> Result> { - if p.get("range").is_some() { - return target_ranges(s, p); + let mut areas = if p.get("range").is_some() { + target_ranges(s, p)? + } else if s.doc()?.selection.ranges.len() > 1 { + s.doc()?.selection.ranges.clone() + } else { + vec![block(s, p)?] + }; + // Whole columns/rows span a million cells: clip their far edges to the cells in use, so only + // a block that really is too large gets refused. Bounded areas keep their extent as given. + let sheet = target_sheet(s, p)?; + if let Some(used) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()) { + // Areas that start outside the used range keep their extent as given. + for r in &mut areas { + let whole_cols = r.start.row == 0 && r.end.row >= MAX_ROWS - 1; + let whole_rows = r.start.col == 0 && r.end.col >= MAX_COLS - 1; + if whole_cols && r.start.row <= used.end.row { + r.end.row = r.end.row.min(used.end.row); + } + if whole_rows && r.start.col <= used.end.col { + r.end.col = r.end.col.min(used.end.col); + } + } } - let d = s.doc()?; - if d.selection.ranges.len() > 1 { - return Ok(d.selection.ranges.clone()); - } - Ok(vec![block(s, p)?]) + Ok(areas) } // ---------------------------------------------------------------- tables @@ -292,7 +316,7 @@ fn insert_table(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; // The header row pushes the data down one row: never off the end of the sheet. let last = RangeRef::new(CellRef::new(MAX_ROWS - 1, r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col)); - if sh.cells.iter_range(last).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) { + if sh.cells.iter_range(last).any(|(_, x)| x.has_content()) { return Err(EngineError::Other("To prevent possible loss of data, cells can't be pushed off the end of the worksheet.".into())); } sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.start.row, 1); @@ -301,7 +325,7 @@ fn insert_table(s: &mut Session, p: &Json) -> Result { let e = Edit::InsertCells { axis: Axis::Rows, range: RangeRef::new(r.start, CellRef::new(r.start.row, r.end.col)) }; shift_cell_features(sh, &e); let name = sh.name.clone(); - rewrite(cx, &name, &e); + rewrite(cx, &name, &e)?; let sh = cx.sheet_mut(sheet)?; for (i, c) in (r.start.col..=r.end.col).enumerate() { sh.set_value(CellRef::new(r.start.row, c), gridcraft_core::Value::text(format!("Column{}", i + 1))); @@ -452,7 +476,10 @@ fn write_totals(sh: &mut Sheet, ti: usize) { let c = CellRef::new(row, t.range.start.col + i as u32); if let Some(code) = col.totals.subtotal_code() { let f = format!("=SUBTOTAL({code},{}[{}])", t.name, col.name); - sh.set_cell(c, Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c) }); + sh.set_cell( + c, + Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c), py: None }, + ); } else if let Some(l) = &col.totals_label { sh.set_value(c, gridcraft_core::Value::text(l.as_str())); } else { @@ -820,6 +847,7 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> { series, legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom }, data_labels: false, + data_table: None, gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel), style: 1, x_title: None, @@ -867,7 +895,11 @@ fn chart_set(s: &mut Session, p: &Json) -> Result { let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) }; if let Some(t) = str_param(p, "type") { c.kind = chart_kind(t, str_param(p, "subtype").unwrap_or("")); + if !c.supports_data_table() { + c.data_table = None; + } } + update_data_table(c, p, bool_param(p, "dataTable"))?; if let Some(method) = quartiles { for series in &mut c.series { series.quartiles = method; @@ -904,10 +936,10 @@ fn chart_set(s: &mut Session, p: &Json) -> Result { c.anchor.cell = at; } if let Some(w) = f64_param(p, "width") { - c.anchor.width = w.clamp(20.0, 10000.0) as f32; + c.anchor.width = w.clamp(20.0, size_cap(c.anchor.width)) as f32; } if let Some(h) = f64_param(p, "height") { - c.anchor.height = h.clamp(20.0, 10000.0) as f32; + c.anchor.height = h.clamp(20.0, size_cap(c.anchor.height)) as f32; } if let Some(v) = f64_param(p, "dx") { c.anchor.dx = v as f32; @@ -919,6 +951,32 @@ fn chart_set(s: &mut Session, p: &Json) -> Result { }) } +/// Shared by Chart Properties and Add Chart Element; no separate UI state. +pub(super) fn update_data_table(c: &mut Chart, p: &Json, on: Option) -> Result<()> { + if p.get("dataTable").is_some_and(|v| !v.is_boolean()) { + return Err(bad("chart", "`dataTable` must be a boolean")); + } + if on == Some(false) { + c.data_table = None; + return Ok(()); + } + let fields = ["dataTableKeys", "dataTableHorizontalBorder", "dataTableVerticalBorder", "dataTableOutline"]; + if on == Some(true) || fields.iter().any(|k| p.get(k).is_some()) { + if !c.supports_data_table() { + return Err(bad("chart", "data tables need a column, bar, line, area or compatible combo chart")); + } + let table = c.data_table.get_or_insert_with(Default::default); + for (key, value) in + fields.into_iter().zip([&mut table.show_keys, &mut table.horizontal_border, &mut table.vertical_border, &mut table.outline]) + { + if let Some(v) = p.get(key) { + *value = v.as_bool().ok_or_else(|| bad("chart", format!("`{key}` must be a boolean")))?; + } + } + } + Ok(()) +} + fn chart_switch(s: &mut Session, p: &Json) -> Result { let (si, ci) = find_chart(s, p)?; edit(s, |cx| { @@ -1115,6 +1173,7 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result { Color::Theme(4, -250) }); let shape = Shape { + math: Default::default(), id, kind, anchor: Anchor { @@ -1168,51 +1227,62 @@ fn shape_set_text(s: &mut Session, p: &Json) -> Result { }) } +/// The floating object a `{kind, id}` command names on the active sheet. Unknown kinds and +/// objects are errors, so a stale id never succeeds silently. +fn object_param(s: &Session, p: &Json, cmd: &str) -> Result<(usize, ObjRef)> { + let id = u32_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?; + let kind = str_param(p, "kind").and_then(ObjKind::parse).ok_or_else(|| bad(cmd, "kind must be chart, image, shape, slicer or equation"))?; + let d = s.doc()?; + let sheet = d.wb.active_sheet(); + let o = ObjRef::new(kind, id); + if !d.wb.sheet(sheet).is_some_and(|sh| sh.has_object(o)) { + return Err(bad(cmd, "no such object")); + } + Ok((sheet, o)) +} + fn delete_object(s: &mut Session, p: &Json) -> Result { - let id = u32_param(p, "id").ok_or_else(|| bad("object.delete", "missing `id`"))?; - let kind = str_param(p, "kind").unwrap_or("").to_string(); - let sheet = s.doc()?.wb.active_sheet(); + let (sheet, o) = object_param(s, p, "object.delete")?; edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - match kind.as_str() { - "chart" => sh.charts.retain(|c| c.id != id), - "image" => sh.images.retain(|c| c.id != id), - "slicer" => sh.slicers.retain(|c| c.id != id), - _ => sh.shapes.retain(|c| c.id != id), - } - Ok(Json::Null) + cx.sheet_mut(sheet)?.remove_object(o); + Ok(json!({"deleted": o})) }) } +/// Largest offset (points) `object.move` accepts from the anchor cell. +const MAX_OBJECT_OFFSET: f64 = 100_000.0; + +/// Largest width or height (points) `object.move` and `chart.set` give an object that is not +/// already larger: see [`size_cap`]. +const MAX_OBJECT_SIZE: f64 = 10_000.0; + +/// The most a command may make a dimension that is `current` now: [`MAX_OBJECT_SIZE`], or the +/// current size when a file made the object larger (the XLSX reader accepts anchors far past the +/// limit). Such an object keeps its size when it is moved and shrinks by what a resize asks, but +/// it never grows further, so hostile input is still capped. Never NaN: `f64::max` drops one. +fn size_cap(current: f32) -> f64 { + MAX_OBJECT_SIZE.max(f64::from(current)) +} + fn move_object(s: &mut Session, p: &Json) -> Result { - let id = u32_param(p, "id").ok_or_else(|| bad("object.move", "missing `id`"))?; - let kind = str_param(p, "kind").unwrap_or("").to_string(); - let sheet = s.doc()?.wb.active_sheet(); + let (sheet, o) = object_param(s, p, "object.move")?; let at = cell_param(s, p, "at")?; edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - let anchor = match kind.as_str() { - "chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - "image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - "slicer" => sh.slicers.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - "shape" => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - _ => None, - }; - let Some(a) = anchor else { return Err(bad("object.move", "no such object")) }; + let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.move", "no such object")) }; if let Some(at) = at { a.cell = at; } if let Some(v) = f64_param(p, "dx") { - a.dx = v as f32; + a.dx = v.clamp(-MAX_OBJECT_OFFSET, MAX_OBJECT_OFFSET) as f32; } if let Some(v) = f64_param(p, "dy") { - a.dy = v as f32; + a.dy = v.clamp(-MAX_OBJECT_OFFSET, MAX_OBJECT_OFFSET) as f32; } if let Some(v) = f64_param(p, "width") { - a.width = v.clamp(1.0, 10000.0) as f32; + a.width = v.clamp(1.0, size_cap(a.width)) as f32; } if let Some(v) = f64_param(p, "height") { - a.height = v.clamp(0.0, 10000.0) as f32; + a.height = v.clamp(0.0, size_cap(a.height)) as f32; } Ok(Json::Null) }) @@ -1222,21 +1292,10 @@ fn move_object(s: &mut Session, p: &Json) -> Result { /// cells" / "Don't move or size with cells"), so it follows — or ignores — its rows and columns /// when the sheet is sorted or edited structurally. fn set_anchor_mode(s: &mut Session, p: &Json) -> Result { - let id = u32_param(p, "id").ok_or_else(|| bad("object.setAnchorMode", "missing `id`"))?; - let kind = str_param(p, "kind").unwrap_or("").to_string(); - if !matches!(kind.as_str(), "chart" | "image" | "shape") { - return Err(bad("object.setAnchorMode", "kind must be chart, image or shape")); - } + let (sheet, o) = object_param(s, p, "object.setAnchorMode")?; let mode = anchor_mode_param(p).ok_or_else(|| bad("object.setAnchorMode", "mode must be moveAndSize, moveOnly or absolute"))?; - let sheet = s.doc()?.wb.active_sheet(); edit(s, |cx| { - let sh = cx.sheet_mut(sheet)?; - let anchor = match kind.as_str() { - "chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - "image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - _ => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor), - }; - let Some(a) = anchor else { return Err(bad("object.setAnchorMode", "no such object")) }; + let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.setAnchorMode", "no such object")) }; a.mode = mode; Ok(json!({"mode": anchor_mode_name(mode)})) }) @@ -1267,7 +1326,7 @@ fn insert_link(s: &mut Session, p: &Json) -> Result { }); let sh = cx.sheet_mut(sheet)?; if let Some(t) = text.clone().or_else(|| sh.value(at).is_empty().then(|| target.clone())) { - sh.set_cell(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style }); + sh.set_cell(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style, py: None }); } else { sh.set_style(at, link_style); } @@ -1729,6 +1788,7 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result { let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active); let color = super::format::color_param(p.get("color")).unwrap_or(Color::Theme(1, 0)); let shape = Shape { + math: Default::default(), id, kind: ShapeKind::Icon, anchor: Anchor { cell: at, dx: 4.0, dy: 4.0, width: size, height: size, mode: anchor_mode_param(p).unwrap_or_default() }, @@ -1748,6 +1808,86 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result { mod tests { use super::*; + #[test] + fn chart_from_whole_columns_uses_the_rows_in_use() { + // #3114: selecting two whole columns of data refused the chart as "range too large". + let mut s = Session::new(); + s.new_workbook(); + let values: Vec> = (1..=5).map(|i| vec![i.to_string(), (i * 10).to_string()]).collect(); + s.execute("range.setValues", json!({"range": "A1:B5", "values": values})).unwrap(); + s.execute("selection.set", json!({"range": "A:B"})).unwrap(); + s.execute("insert.chart", json!({"type": "line"})).unwrap(); + let d = s.doc().unwrap(); + let chart = d.wb.active().unwrap().charts.last().unwrap(); + let values: Vec<&str> = chart.series.iter().map(|x| x.values.as_str()).collect(); + assert_eq!(values, ["Sheet1!$A$1:$A$5", "Sheet1!$B$1:$B$5"]); + // A block that really is too large still is. + s.execute("cell.set", json!({"cell": "B600000", "input": "1"})).unwrap(); + assert!(s.execute("insert.chart", json!({"range": "A:B", "type": "line"})).is_err()); + // A bounded block keeps its extent, even where it runs past the data. + s.execute("insert.chart", json!({"range": "A1:A20", "type": "line"})).unwrap(); + let d = s.doc().unwrap(); + let chart = d.wb.active().unwrap().charts.last().unwrap(); + let values: Vec<&str> = chart.series.iter().map(|x| x.values.as_str()).collect(); + assert_eq!(values, ["Sheet1!$A$1:$A$20"]); + // A bounded block entirely below the data keeps its extent. + s.execute("insert.chart", json!({"range": "C700000:C700010", "type": "line"})).unwrap(); + let d = s.doc().unwrap(); + let chart = d.wb.active().unwrap().charts.last().unwrap(); + let values: Vec<&str> = chart.series.iter().map(|x| x.values.as_str()).collect(); + assert_eq!(values, ["Sheet1!$C$700000:$C$700010"]); + } + + #[test] + fn chart_data_table_commands_undo_and_follow_live_values() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "Sales"], ["Q1", 10], ["Q2", 20]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "column"})).unwrap(); + s.execute("chart.addElement", json!({"element": "dataTable", "dataTableKeys": false})).unwrap(); + let get = |s: &Session| s.active().unwrap().wb.active().unwrap().charts[0].clone(); + let table = get(&s).data_table.unwrap(); + assert!(!table.show_keys && table.horizontal_border && table.vertical_border && table.outline); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(get(&s).data_table, None); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(get(&s).data_table, Some(table)); + s.execute("chart.set", json!({"dataTableKeys": true, "dataTableHorizontalBorder": false})).unwrap(); + assert!(get(&s).data_table.as_ref().unwrap().show_keys); + assert!(!get(&s).data_table.as_ref().unwrap().horizontal_border); + s.execute("cell.set", json!({"cell": "B2", "input": "=12*3"})).unwrap(); + let d = s.active().unwrap(); + assert_eq!(gridcraft_chart::resolve(&d.wb, 0, &get(&s)).series[0].values[0], Some(36.0)); + s.execute("chart.addElement", json!({"element": "dataTable", "on": false})).unwrap(); + assert_eq!(get(&s).data_table, None); + // Old JSON documents have no table field. + let mut json = serde_json::to_value(get(&s)).unwrap(); + json.as_object_mut().unwrap().remove("data_table"); + assert_eq!(serde_json::from_value::(json).unwrap().data_table, None); + } + + #[test] + fn chart_data_table_refuses_unsupported_types_without_changing_history() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Q", "Sales"], ["Q1", 10], ["Q2", 20]]})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "type": "pie"})).unwrap(); + let before = s.active().unwrap().wb.clone(); + let history = s.execute("history.list", json!({})).unwrap(); + for params in [json!({"dataTable": true}), json!({"dataTableKeys": true}), json!({"dataTable": "yes"})] { + assert!(s.execute("chart.set", params).is_err()); + assert_eq!(s.active().unwrap().wb, before); + assert_eq!(s.execute("history.list", json!({})).unwrap(), history); + } + assert!(s.execute("chart.addElement", json!({"element": "dataTable"})).is_err()); + s.execute("chart.set", json!({"type": "line", "dataTable": true})).unwrap(); + assert!(s.active().unwrap().wb.active().unwrap().charts[0].data_table.is_some()); + s.execute("chart.set", json!({"type": "scatter"})).unwrap(); + assert!(s.active().unwrap().wb.active().unwrap().charts[0].data_table.is_none()); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().wb.active().unwrap().charts[0].data_table.is_some()); + } + #[test] fn manage_rules_delete_then_move() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/insert/chart.rs b/crates/engine/src/cmd/insert/chart.rs index bdd5e77d14..ac486f837c 100644 --- a/crates/engine/src/cmd/insert/chart.rs +++ b/crates/engine/src/cmd/insert/chart.rs @@ -260,6 +260,7 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> { series, legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom }, data_labels: false, + data_table: None, gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel), style: 1, x_title: None, diff --git a/crates/engine/src/cmd/insert/cond_format.rs b/crates/engine/src/cmd/insert/cond_format.rs index faafcfcf2f..89bac49c95 100644 --- a/crates/engine/src/cmd/insert/cond_format.rs +++ b/crates/engine/src/cmd/insert/cond_format.rs @@ -333,6 +333,7 @@ pub(super) fn insert_icon(s: &mut Session, p: &Json) -> Result { line: Color::Auto, text: name, format: Default::default(), + math: Default::default(), }; let sheet = d.wb.active_sheet(); edit(s, |cx| { diff --git a/crates/engine/src/cmd/insert/objects.rs b/crates/engine/src/cmd/insert/objects.rs index 9f51daf0f1..f86915a3a6 100644 --- a/crates/engine/src/cmd/insert/objects.rs +++ b/crates/engine/src/cmd/insert/objects.rs @@ -153,6 +153,7 @@ pub(super) fn insert_shape(s: &mut Session, p: &Json) -> Result { line, text: str_param(p, "text").unwrap_or("").into(), format: Default::default(), + math: Default::default(), }; let sheet = d.wb.active_sheet(); edit(s, |cx| { diff --git a/crates/engine/src/cmd/insert/table.rs b/crates/engine/src/cmd/insert/table.rs index 381a9e64bb..4ca6248261 100644 --- a/crates/engine/src/cmd/insert/table.rs +++ b/crates/engine/src/cmd/insert/table.rs @@ -60,7 +60,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result { let e = Edit::InsertCells { axis: Axis::Rows, range: RangeRef::new(r.start, CellRef::new(r.start.row, r.end.col)) }; shift_cell_features(sh, &e); let name = sh.name.clone(); - rewrite(cx, &name, &e); + rewrite(cx, &name, &e)?; let sh = cx.sheet_mut(sheet)?; for (i, c) in (r.start.col..=r.end.col).enumerate() { sh.set_value(CellRef::new(r.start.row, c), gridcraft_core::Value::text(format!("Column{}", i + 1))); diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index ee4e059175..e91a269fb3 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { vec![ cmd!(query "document.inspect", "Inspect Workbook", [], None, "{} → sheets, selection, names, tables, charts, dirty, trust (local|fromFile), history", has_doc, inspect), cmd!(query "sheet.read", "Read Range", [], None, "{range?: \"A1:D10\" (default: used range), sheet?, formulas?: bool, formatted?: bool} → rows of values", has_doc, read), - cmd!(query "cell.get", "Get Cell", [], None, "{cell?, sheet?} → value, formula, display text, style, comment, link", has_doc, cell_get), + cmd!(query "cell.get", "Get Cell", [], None, "{cell?, sheet?} → value, formula, display text, style, comment, link, python {code, output, typeName, preview, stale}", has_doc, cell_get), cmd!(query "selection.stats", "Selection Statistics", [], None, "{} → count, sum, average, min, max", has_doc, sel_stats), cmd!(query "history.list", "Undo History", [], None, "{} → undo/redo labels, grouping (an undo group is open)", has_doc, history), cmd!(query "app.commands", "List Commands", [], None, "{search?} → ids, labels, params", always, list_commands), @@ -46,7 +46,7 @@ fn inspect(s: &mut Session, _: &Json) -> Result { "freeze": sh.freeze, "merges": sh.merges.iter().map(|m| m.a1()).collect::>(), "tables": sh.tables.iter().map(|t| json!({"name": t.name, "range": t.range.a1(), "style": t.style, "totals": t.totals_row, "columns": t.columns.iter().map(|c| c.name.clone()).collect::>()})).collect::>(), - "charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len(), "trendlines": c.series.iter().flat_map(|s| s.trendlines.iter().map(|t| format!("{:?}", t.kind))).collect::>()})).collect::>(), + "charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len(), "dataTable": c.data_table.as_ref().map(|t| json!({"showKeys": t.show_keys, "horizontalBorder": t.horizontal_border, "verticalBorder": t.vertical_border, "outline": t.outline})), "trendlines": c.series.iter().flat_map(|s| s.trendlines.iter().map(|t| format!("{:?}", t.kind))).collect::>()})).collect::>(), "images": sh.images.len(), "shapes": sh.shapes.len(), "conditionalFormats": sh.cond_formats.len(), @@ -137,6 +137,13 @@ fn cell_get(s: &mut Session, p: &Json) -> Result { "merge": sh.merge_at(c).map(|m| m.a1()), "comment": sh.comments.get(&c), "hyperlink": sh.hyperlinks.get(&c), + "python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({ + "code": py.code, + "output": if py.object { "object" } else { "value" }, + "typeName": py.output.as_ref().map(|o| o.type_name.as_str()), + "preview": py.output.as_ref().map(|o| o.preview.as_str()), + "stale": py.stale, + })), })) } diff --git a/crates/engine/src/cmd/pivot/charts.rs b/crates/engine/src/cmd/pivot/charts.rs index 8ae00b1614..d7a3b73b12 100644 --- a/crates/engine/src/cmd/pivot/charts.rs +++ b/crates/engine/src/cmd/pivot/charts.rs @@ -65,6 +65,7 @@ pub(super) fn insert_pivot_chart(s: &mut Session, p: &Json) -> Result { series, legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom }, data_labels: false, + data_table: None, gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel), style: 1, x_title: None, diff --git a/crates/engine/src/cmd/pivot/create.rs b/crates/engine/src/cmd/pivot/create.rs index e9a6dcbde2..18946f99bb 100644 --- a/crates/engine/src/cmd/pivot/create.rs +++ b/crates/engine/src/cmd/pivot/create.rs @@ -255,7 +255,10 @@ pub(super) fn show_details(s: &mut Session, p: &Json) -> Result { } } for (c, h) in src.headers.iter().enumerate() { - sh.set_cell(CellRef::new(0, c as u32), Cell { value: gridcraft_core::Value::text(h.as_str()), formula: None, style: StyleId::default() }); + sh.set_cell( + CellRef::new(0, c as u32), + Cell { value: gridcraft_core::Value::text(h.as_str()), formula: None, style: StyleId::default(), py: None }, + ); } for (r, i) in records.iter().enumerate() { let Some(rec) = src.rows.get(*i) else { continue }; @@ -264,7 +267,7 @@ pub(super) fn show_details(s: &mut Session, p: &Json) -> Result { if v.is_empty() && style == StyleId::default() { continue; } - sh.set_cell(CellRef::new(r as u32 + 1, c as u32), Cell { value: v.clone(), formula: None, style }); + sh.set_cell(CellRef::new(r as u32 + 1, c as u32), Cell { value: v.clone(), formula: None, style, py: None }); } } let name = sh.name.clone(); diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index cda52f31db..b3ce40d583 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -1,20 +1,20 @@ //! Printing: Page Setup, pagination and PDF output (File › Print, File › Export › PDF). //! -//! Sheets are paginated like Excel's default "down, then over": the print area (or the used -//! range plus drawing objects) is split into bands of rows and columns that fit the printable -//! area at the page scale, honouring manual breaks, repeated title rows/columns, headings, Fit -//! To and centring. Each page is drawn into a PDF with `gridcraft-pdf`: fills, gridlines, -//! borders, formatted text (fonts mapped to the standard 14 PDF fonts), merged cells, wrapping, -//! overflow into empty neighbours, conditional formats, table styles, charts, images, shapes and -//! sparklines. Headers and footers support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` -//! codes. +//! Sheets are paginated like Excel: the print area (or the used range plus drawing objects) is +//! split into bands of rows and columns that fit the printable area at the page scale, honouring +//! manual breaks, repeated title rows/columns, headings, Fit To and centring, and the pages follow +//! the sheet's page order ("down, then over" by default, or "over, then down"). Each page is +//! drawn into a PDF with `gridcraft-pdf`: fills, gridlines, borders, formatted text (fonts mapped +//! to the standard 14 PDF fonts), merged cells, wrapping, overflow into empty neighbours, +//! conditional formats, table styles, charts, images, shapes and sparklines. Headers and footers +//! support `&L`/`&C`/`&R` sections and the `&P &N &D &T &A &F &Z` codes. use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value}; #[cfg(test)] use gridcraft_model::{Alignment, Image, SheetViewMode}; use gridcraft_model::{ - Anchor, BorderLine, BorderStyle, Borders, Color, HAlign, Orientation, PatternType, PrintSettings, ShapeKind, Sheet, Style, StyleId, StyleTable, - Underline, VAlign, Visibility, Workbook, + Anchor, BorderLine, BorderStyle, Borders, Color, HAlign, Orientation, PageOrder, PatternType, PrintSettings, ShapeKind, Sheet, Style, StyleId, + StyleTable, Underline, VAlign, Visibility, Workbook, }; use gridcraft_pdf::{Font, Page, PdfDoc, Point, Rect, Rgb}; use serde_json::{Value as Json, json}; @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "Print Preview", ["File"], None, - "{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, width, height}]}", + "{page? (1-based), sheets?: active|all, range?, fitToPage?} → {pages, pageList: [{page, sheet, range, rows, columns, scale, paper, orientation, pageOrder, width, height}]} in print order", has_doc, print_preview ), @@ -78,7 +78,7 @@ pub fn specs() -> Vec { "Page Setup…", ["Page Layout", "Page Setup"], None, - "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"]} → the sheet's print settings", + "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", has_doc, page_setup ), @@ -222,6 +222,7 @@ fn print_preview(s: &mut Session, p: &Json) -> Result { "scale": (lay.scale * 1000.0).round() / 10.0, "paper": lay.settings.paper, "orientation": if lay.settings.orientation == Orientation::Landscape { "landscape" } else { "portrait" }, + "pageOrder": lay.settings.page_order.id(), "width": lay.page_w, "height": lay.page_h, })); @@ -244,6 +245,16 @@ fn page_setup(s: &mut Session, p: &Json) -> Result { Some("landscape") => Some(Orientation::Landscape), Some(o) => return Err(bad(CMD, format!("orientation must be portrait or landscape, not `{o}`"))), }; + let page_order = match p.get("pageOrder") { + None => None, + Some(v) => match v.as_str().and_then(PageOrder::parse) { + Some(o) => Some(o), + None => { + let shown = v.as_str().map_or_else(|| v.to_string(), str::to_string); + return Err(bad(CMD, format!("pageOrder must be downThenOver or overThenDown, not `{shown}`"))); + } + }, + }; let paper = match str_param(p, "paper") { None => None, Some(name) => { @@ -385,6 +396,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result { if let Some(b) = &col_breaks { pr.col_breaks = b.clone(); } + if let Some(o) = page_order { + pr.page_order = o; + } Ok(()) })?; let pr = s.doc()?.wb.sheet(si).map(|sh| sh.print.clone()).unwrap_or_default(); diff --git a/crates/engine/src/cmd/print/layout.rs b/crates/engine/src/cmd/print/layout.rs index 83ff451831..0f484f8755 100644 --- a/crates/engine/src/cmd/print/layout.rs +++ b/crates/engine/src/cmd/print/layout.rs @@ -1,7 +1,7 @@ use super::header_footer::HF_FIXED_SIDE_MARGIN; use super::{ - Anchor, CellRef, Json, MAX_COLS, MAX_PAGES, MAX_ROWS, Orientation, PX_TO_PT, PrintSettings, RangeRef, Result, Sheet, Visibility, Workbook, bad, - bool_param, split_sheet, str_param, + Anchor, CellRef, Json, MAX_COLS, MAX_PAGES, MAX_ROWS, Orientation, PX_TO_PT, PageOrder, PrintSettings, RangeRef, Result, Sheet, Visibility, + Workbook, bad, bool_param, split_sheet, str_param, }; /// Cells in a page block above which only stored cells are visited (not every grid position). @@ -253,15 +253,7 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid let paginate = |lay: &mut SheetLayout, manual: bool| { lay.manual_breaks = manual; (lay.row_bands, lay.col_bands) = split_bands(sh, lay, MAX_PAGES); - lay.pages.clear(); - 'outer: for ci in 0..lay.col_bands.len() { - for ri in 0..lay.row_bands.len() { - if lay.pages.len() >= MAX_PAGES { - break 'outer; - } - lay.pages.push((ri, ci)); - } - } + lay.pages = page_sequence(lay.row_bands.len(), lay.col_bands.len(), lay.settings.page_order, MAX_PAGES); }; match fit { Some((fw, fh)) => { @@ -290,6 +282,25 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid Some(lay) } +/// The pages of a sheet `rows` pages tall and `cols` pages wide as (row band, column band), in +/// print order, at most `cap` of them: down each column of pages, then over to the next (Excel's +/// default), or over each row of pages, then down to the next. +pub(crate) fn page_sequence(rows: usize, cols: usize, order: PageOrder, cap: usize) -> Vec<(usize, usize)> { + let (outer, inner) = match order { + PageOrder::DownThenOver => (cols, rows), + PageOrder::OverThenDown => (rows, cols), + }; + (0..outer) + .flat_map(|o| { + (0..inner).map(move |i| match order { + PageOrder::DownThenOver => (i, o), + PageOrder::OverThenDown => (o, i), + }) + }) + .take(cap) + .collect() +} + /// Inclusive-start/end index spans of the pages along one axis. pub(crate) type Bands = Vec<(u32, u32)>; diff --git a/crates/engine/src/cmd/print/objects.rs b/crates/engine/src/cmd/print/objects.rs index d2128f9615..faa855cb92 100644 --- a/crates/engine/src/cmd/print/objects.rs +++ b/crates/engine/src/cmd/print/objects.rs @@ -29,6 +29,26 @@ pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32 } /// Sheet pixel rectangle of an anchor. +/// Most source lines printed for an equation that has no layout. +pub(super) const MAX_FALLBACK_LINES: usize = 500; + +/// The lines of `text` printed in place of an equation that has no layout: those of its first +/// `MAX_SOURCE_BYTES` (a longer source never lays out, and a file can carry megabytes) that fit a +/// frame `h` points tall at `line_h` points per line (at least the first), and never more than +/// [`MAX_FALLBACK_LINES`]. A single `pg.text` call would print every newline as `?`. +pub(super) fn fallback_lines(text: &str, h: f32, line_h: f32) -> impl Iterator { + let text = crate::cmd::equation::source_excerpt(text); + let fit = h / line_h; + let n = if fit >= MAX_FALLBACK_LINES as f32 { + MAX_FALLBACK_LINES + } else if fit >= 1.0 { + fit as usize + } else { + 1 + }; + text.lines().take(n) +} + fn anchor_rect(sh: &Sheet, a: &Anchor) -> (f64, f64, f64, f64) { (sh.col_left(a.cell.col) + a.dx as f64, sh.row_top(a.cell.row) + a.dy as f64, a.width.max(0.0) as f64, a.height.max(0.0) as f64) } @@ -79,6 +99,25 @@ pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, continue; } let (x, y, w, h) = place(r); + if shp.kind == ShapeKind::Equation { + let ink = rgb_of(shp.line, wb).unwrap_or([0, 0, 0]); + match shp.math.get(&shp.text) { + Some(Ok(list)) => crate::cmd::equation::draw_pdf(pg, list, (x, y, w, h), crate::cmd::equation::PADDING * b.k, ink), + _ => { + // No layout (the source does not parse, or the file was past the layout + // budget): the source, one text run per line, as many as the frame holds. + let line_h = 12.0 * b.scale; + // A long line stays inside the frame; this clip nests in the block's. + pg.save(); + pg.clip_rect(x, y, w, h); + for (i, line) in fallback_lines(&shp.text, h, line_h).enumerate() { + pg.text(x + 2.0 * b.k, y + line_h * (i + 1) as f32, 10.0 * b.scale, Font::Courier, ink, line); + } + pg.restore(); + } + } + continue; + } draw_shape(pg, wb, shp, b, (x, y, w, h)); } for ch in &sh.charts { diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 51760c4a60..cd25606b9b 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -16,6 +16,25 @@ fn contains(hay: &[u8], needle: &str) -> bool { hay.windows(needle.len()).any(|w| w == needle.as_bytes()) } +#[test] +fn chart_data_table_prints_formatted_values_and_follows_recalculation() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "Sales"], ["Q1", 1234], ["Q2", 5678]]})).unwrap(); + s.execute("home.numberFormat", json!({"range": "B2:B3", "format": "#,##0.00"})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:B3", "at": "D2", "type": "column"})).unwrap(); + let (off, pages) = pdf_of(&mut s, json!({"fitToPage": true})); + assert_eq!(pages, 1); + let count = |bytes: &[u8], text: &str| String::from_utf8_lossy(bytes).matches(text).count(); + s.execute("chart.set", json!({"dataTable": true})).unwrap(); + let (on, _) = pdf_of(&mut s, json!({"fitToPage": true})); + assert_eq!(count(&on, "(1,234.00) Tj"), count(&off, "(1,234.00) Tj") + 1); + assert_eq!(count(&on, "(5,678.00) Tj"), count(&off, "(5,678.00) Tj") + 1); + s.execute("cell.set", json!({"cell": "B2", "input": "=1000+111"})).unwrap(); + let (updated, _) = pdf_of(&mut s, json!({"fitToPage": true})); + assert!(!contains(&updated, "(1,234.00) Tj")); + assert!(count(&updated, "(1,111.00) Tj") >= 2, "cell and chart data table both print the new value"); +} + #[test] fn pdf_export_keeps_safe_links_on_their_printed_pages() { let mut s = s(); @@ -148,6 +167,142 @@ fn wide_sheet_goes_down_then_over() { assert_eq!(pv["pageList"][2]["range"], "K1:O45"); } +/// The ranges of the printed pages, in print order. +fn page_ranges(s: &mut Session) -> Vec { + let pv = s.execute("file.printPreview", json!({})).unwrap(); + let list = pv["pageList"].as_array().unwrap(); + assert_eq!(pv["pages"], list.len()); + for (i, page) in list.iter().enumerate() { + assert_eq!(page["page"], i + 1); + assert_eq!(page["pageOrder"], s.doc().unwrap().wb.active().unwrap().print.page_order.id()); + } + list.iter().map(|p| p["range"].as_str().unwrap().to_string()).collect() +} + +/// The content streams of an exported PDF's pages, in page order (pages without pictures are the +/// file's only streams). +fn pdf_pages(s: &mut Session) -> Vec { + let (pdf, pages) = pdf_of(s, json!({})); + let text = String::from_utf8_lossy(&pdf); + let streams: Vec = text.split("endstream").filter(|part| part.contains("stream\n")).map(str::to_string).collect(); + assert_eq!(streams.len() as u64, pages); + streams +} + +/// The page order measured in Excel: print area A1:D4 with a row break before row 3 and a column +/// break before column C, so four pages two tall and two wide, each filled and labelled in its +/// own colour, with `Page &P of &N` in the footer. +fn two_by_two_pages() -> Session { + let mut s = s(); + for (range, color, label) in + [("A1:B2", "#FF0000", "red"), ("A3:B4", "#00FF00", "green"), ("C1:D2", "#0000FF", "blue"), ("C3:D4", "#FFFF00", "yellow")] + { + s.execute("home.fillColor", json!({"range": range, "color": color})).unwrap(); + s.execute("cell.set", json!({"cell": &range[..2], "input": label})).unwrap(); + } + s.execute("pageLayout.pageSetup", json!({"printArea": "A1:D4", "rowBreaks": [3], "colBreaks": ["C"], "footer": "Page &P of &N"})).unwrap(); + s +} + +/// The colour of each printed page, read from its fill and label; each page's footer must +/// number it in print order. +fn printed_colours(s: &mut Session) -> Vec<&'static str> { + let pages = pdf_pages(s); + let n = pages.len(); + pages + .iter() + .enumerate() + .map(|(i, page)| { + assert!(page.contains(&format!("(Page {} of {n}) Tj", i + 1)), "page {}: {page}", i + 1); + let found: Vec<&str> = [("red", "1 0 0 rg"), ("green", "0 1 0 rg"), ("blue", "0 0 1 rg"), ("yellow", "1 1 0 rg")] + .into_iter() + .filter(|(label, fill)| page.contains(&format!("({label}) Tj")) && page.contains(&format!("\n{fill}\n"))) + .map(|(label, _)| label) + .collect(); + assert_eq!(found.len(), 1, "page {}: {found:?}", i + 1); + found[0] + }) + .collect() +} + +#[test] +fn page_order_sets_the_sequence_of_the_pages_as_measured_in_excel() { + let mut s = two_by_two_pages(); + // Down, then over is the default: down the first column of pages, then the next. + assert_eq!(s.doc().unwrap().wb.active().unwrap().print.page_order, PageOrder::DownThenOver); + assert_eq!(s.execute("pageLayout.pageSetup", json!({})).unwrap()["page_order"], "downThenOver"); + let down = ["A1:B2", "A3:B4", "C1:D2", "C3:D4"]; + assert_eq!(page_ranges(&mut s), down); + assert_eq!(printed_colours(&mut s), ["red", "green", "blue", "yellow"]); + // Over, then down: across the first row of pages, then the next. + let r = s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap(); + assert_eq!(r["page_order"], "overThenDown"); + let over = ["A1:B2", "C1:D2", "A3:B4", "C3:D4"]; + assert_eq!(page_ranges(&mut s), over); + assert_eq!(printed_colours(&mut s), ["red", "blue", "green", "yellow"]); + assert_eq!(s.execute("file.printPreview", json!({"page": 2})).unwrap()["page"]["range"], "C1:D2"); + // One undo step. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(page_ranges(&mut s), down); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(page_ranges(&mut s), over); + // Anything but the two orders is refused and changes nothing, even next to a good value. + for bad in [json!("sideways"), json!("OverThenDown"), json!(""), json!(2), json!(null), json!(true), json!(["downThenOver"])] { + let e = s.execute("pageLayout.pageSetup", json!({"pageOrder": bad, "orientation": "landscape"})).unwrap_err(); + assert!(e.to_string().contains("pageOrder"), "{bad}: {e}"); + } + let pr = &s.doc().unwrap().wb.active().unwrap().print; + assert_eq!((pr.page_order, pr.orientation), (PageOrder::OverThenDown, Orientation::Portrait)); + assert!(s.take_ui_requests().is_empty(), "a programmatic call never opens a dialog"); + // First-page and odd/even headers go by the printed sequence too. + s.execute( + "pageLayout.headerFooter", + json!({"header": "&COdd &P", "evenHeader": "&CEven &P", "firstHeader": "&CCover", "differentFirst": true, "differentOddEven": true}), + ) + .unwrap(); + let pages = pdf_pages(&mut s); + for (page, (header, label)) in pages.iter().zip([("Cover", "red"), ("Even 2", "blue"), ("Odd 3", "green"), ("Even 4", "yellow")]) { + assert!(page.contains(&format!("({header}) Tj")) && page.contains(&format!("({label}) Tj")), "{header}: {page}"); + } + s.execute("pageLayout.pageSetup", json!({"pageOrder": "downThenOver"})).unwrap(); + assert_eq!(page_ranges(&mut s), down); + let pages = pdf_pages(&mut s); + for (page, (header, label)) in pages.iter().zip([("Cover", "red"), ("Even 2", "green"), ("Odd 3", "blue"), ("Even 4", "yellow")]) { + assert!(page.contains(&format!("({header}) Tj")) && page.contains(&format!("({label}) Tj")), "{header}: {page}"); + } +} + +#[test] +fn page_order_without_breaks_and_with_print_titles() { + let mut s = s(); + // Every cell shows its own address: 60 rows and 15 columns are two pages tall and two wide. + let rows: Vec> = (1..=60).map(|r| (0..15).map(|c| json!(format!("{}{r}", gridcraft_core::col_to_letters(c)))).collect()).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap(); + for titles in [false, true] { + if titles { + s.execute("pageLayout.pageSetup", json!({"titleRows": "1:1", "titleCols": "A:A"})).unwrap(); + } + s.execute("pageLayout.pageSetup", json!({"pageOrder": "downThenOver"})).unwrap(); + let down = page_ranges(&mut s); + if !titles { + assert_eq!(down, ["A1:J45", "A46:J60", "K1:O45", "K46:O60"]); + } + s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap(); + let over = page_ranges(&mut s); + assert_eq!(over, [down[0].clone(), down[2].clone(), down[1].clone(), down[3].clone()], "titles: {titles}"); + // Each printed page starts with its own top-left cell; the title row and column (A1 is in + // both) repeat on every page in either order. + for (order, ranges) in [("overThenDown", &over), ("downThenOver", &down)] { + s.execute("pageLayout.pageSetup", json!({"pageOrder": order})).unwrap(); + for (i, (page, range)) in pdf_pages(&mut s).iter().zip(ranges.iter()).enumerate() { + let top_left = range.split(':').next().unwrap(); + assert!(page.contains(&format!("({top_left}) Tj")), "{order} page {}: no {top_left}", i + 1); + assert_eq!(page.contains("(A1) Tj"), titles || i == 0, "{order} page {}, titles: {titles}", i + 1); + } + } + } +} + #[test] fn first_and_even_pages_print_their_own_headers() { let mut s = s(); @@ -174,6 +329,14 @@ fn first_and_even_pages_print_their_own_headers() { assert!(contains(&pdf, "(Odd 1) Tj") && contains(&pdf, "(Odd 2) Tj") && !contains(&pdf, "(Cover) Tj")); } +/// The y position of the first `(text) Tj` in a PDF (PDF space: larger is higher on the page). +fn text_y(pdf: &[u8], text: &str) -> Option { + let s = String::from_utf8_lossy(pdf); + let before = &s[..s.find(&format!("({text}) Tj"))?]; + let tm = before.rfind(" Tm")?; + before[..tm].rsplit([' ', '\n']).next()?.parse().ok() +} + /// The x position and font size of the first `(text) Tj` in a PDF. fn text_at(pdf: &[u8], text: &str) -> Option<(f32, f32)> { let s = String::from_utf8_lossy(pdf); @@ -473,6 +636,11 @@ fn hostile_settings_never_panic_and_cap_pages() { assert_eq!(pv["pages"].as_u64().unwrap(), MAX_PAGES as u64); let r = s.execute("file.exportPdf", json!({})).unwrap(); assert_eq!(r["pages"], MAX_PAGES); + // Over, then down stops at the cap as well, along the first row of pages. + s.execute("pageLayout.pageSetup", json!({"pageOrder": "overThenDown"})).unwrap(); + let pv = s.execute("file.printPreview", json!({})).unwrap(); + assert_eq!(pv["pages"].as_u64().unwrap(), MAX_PAGES as u64); + assert_eq!(pv["pageList"][1]["rows"], pv["pageList"][0]["rows"], "the second page is beside the first"); s.execute("pageLayout.pageSetup", json!({"fitWidth": 1, "fitHeight": 1, "titleRows": "1:1048576", "titleCols": "A:XFD", "headings": true})) .unwrap(); let pv = s.execute("file.printPreview", json!({})).unwrap(); @@ -581,3 +749,113 @@ fn checkbox_cells_print_as_boxes_not_true_false() { assert!(contains(&pdf, "0.063 0.486 0.255 rg"), "the checked box is not filled"); assert!(contains(&pdf, "0.431 0.431 0.431 RG"), "the unchecked box is not outlined"); } + +#[test] +fn an_equation_without_a_layout_prints_its_source_one_line_per_line() { + use super::objects::{MAX_FALLBACK_LINES, fallback_lines}; + let mut s = s(); + s.execute("insert.equation", json!({"latex": "x", "cell": "B2"})).unwrap(); + // A file can carry a source the layout engine refuses: two lines here, in a frame 100 px + // (75 pt) tall, which holds six 12 pt lines. + let with_source = |text: &str| { + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + for x in sh.shapes.iter_mut() { + x.text = text.into(); + x.anchor.height = 100.0; + } + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + pdf_of(&mut t, json!({})).0 + }; + let pdf = with_source("frac{\nsecond line"); + assert!(contains(&pdf, "(frac{) Tj"), "the first line is its own text run"); + assert!(contains(&pdf, "(second line) Tj"), "and so is the second"); + assert!(!contains(&pdf, "(frac{?second line) Tj"), "the newline is not printed as ?"); + let (y1, y2) = (text_y(&pdf, "frac{").unwrap(), text_y(&pdf, "second line").unwrap()); + assert!(y1 > y2 && y1 - y2 < 13.0, "the second line sits one line below the first: {y1} {y2}"); + // Lines the frame cannot hold are not printed. + let pdf = with_source(&"l\n".repeat(10_000)); + assert_eq!(String::from_utf8_lossy(&pdf).matches("(l) Tj").count(), 6); + // Whatever the frame, the count is capped; a frame too low for one line still shows the first. + let tall = "l\n".repeat(10_000); + assert_eq!(fallback_lines(&tall, f32::INFINITY, 12.0).count(), MAX_FALLBACK_LINES); + assert_eq!(fallback_lines(&tall, 1.0e9, 12.0).count(), MAX_FALLBACK_LINES); + assert_eq!(fallback_lines("a\nb\nc", 30.0, 12.0).count(), 2); + assert_eq!(fallback_lines("a\nb", 0.0, 12.0).count(), 1); + assert_eq!(fallback_lines("a\nb", f32::NAN, 12.0).count(), 1); +} + +#[test] +fn the_fallback_text_is_clipped_to_the_equation_frame() { + // A long line of a source that does not lay out, in a narrow frame (40 by 100 px, 30 by + // 75 pt): the lines are drawn inside a clip of the frame, nested in the block's, so they + // cannot run over neighbours, and the clip is lifted again before the next object (a text + // box below the equation in the same block) is drawn. + let mut s = s(); + s.execute("insert.equation", json!({"latex": "x", "cell": "B2"})).unwrap(); + s.execute("insert.textBox", json!({"at": "B12", "text": "later box"})).unwrap(); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + for x in sh.shapes.iter_mut().filter(|x| x.kind == gridcraft_model::ShapeKind::Equation) { + x.text = format!("frac{{{}", "l".repeat(200)); + x.anchor.width = 40.0; + x.anchor.height = 100.0; + } + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let (pdf, _) = pdf_of(&mut t, json!({})); + let text = String::from_utf8_lossy(&pdf); + let clip = text.find("30 75 re W n").expect("a clip the size of the frame"); + let run = text.find("(frac{llll").expect("the source line"); + let later = text.find("(later box) Tj").expect("the text box after the equation"); + assert!(clip < run && run < later, "clip, then the text, then the later object"); + // The net number of saved graphics states (`q` less `Q`) before an operator. + let depth = |at: usize| text[..at].lines().filter(|l| *l == "q").count() as i64 - text[..at].lines().filter(|l| *l == "Q").count() as i64; + assert_eq!(depth(run), depth(clip), "the text is drawn under the frame's clip"); + assert_eq!(depth(later), depth(clip) - 1, "the later object is drawn with the frame's state restored"); +} + +#[test] +#[allow(clippy::disallowed_methods)] // tests run only off wasm, where the clock exists +fn an_equation_source_of_a_megabyte_prints_a_bounded_excerpt() { + // A file can carry a source far past `MAX_SOURCE_BYTES` (the drawing part may be 512 MiB). It + // never lays out, so the fallback prints the first 4,096 bytes and does no work on the rest: + // the PDF holds one run of that length, not the megabyte, and export takes bounded time. + let mut s = s(); + s.execute("insert.equation", json!({"latex": "x", "cell": "B2"})).unwrap(); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + for x in sh.shapes.iter_mut() { + x.text = "l".repeat(1 << 20); + } + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let start = std::time::Instant::now(); + let (pdf, _) = pdf_of(&mut t, json!({})); + let took = start.elapsed(); + let text = String::from_utf8_lossy(&pdf); + let longest = text.split(|c| c != 'l').map(str::len).max().unwrap_or(0); + assert_eq!(longest, gridcraft_math::MAX_SOURCE_BYTES, "the run is the excerpt and no more"); + assert!(pdf.len() < 64 * 1024, "the PDF holds the excerpt, not the megabyte: {} bytes", pdf.len()); + assert!(took < std::time::Duration::from_secs(5), "{took:?}"); +} + +#[test] +fn equations_print_with_the_symbol_font() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("insert.equation", json!({"latex": "\\sum_{i=1}^{n} \\alpha_i \\le \\infty \\pm \\sqrt{x} \\times \\partial y", "cell": "B2"})) + .unwrap(); + s.execute("insert.equation", json!({"latex": "\\mathbb{R} \\oplus \\text{\u{4E2D}}", "cell": "B8"})).unwrap(); + let (pdf, _) = pdf_of(&mut s, json!({})); + assert!(contains(&pdf, "/BaseFont /Symbol >>"), "maths symbols use the Symbol font"); + assert!(contains(&pdf, "/BaseFont /Times-Italic"), "variables are italic"); + // The summation (0xE5) and alpha (0x61) codes in Symbol. + assert!(contains(&pdf, "(\\345) Tj") && contains(&pdf, "(a) Tj")); + // A glyph no standard font has is a [?] box. + assert!(contains(&pdf, "(?) Tj")); +} diff --git a/crates/engine/src/cmd/python.rs b/crates/engine/src/cmd/python.rs new file mode 100644 index 0000000000..02d0ccb4e5 --- /dev/null +++ b/crates/engine/src/cmd/python.rs @@ -0,0 +1,137 @@ +//! Python in cells: making and editing Python cells, and their return type. This build stores +//! the code and the last result a file cached; it doesn't run Python, so a cell with new or +//! changed code shows `#BLOCKED!`. + +use std::sync::Arc; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{Cell, PyCode, python::MAX_FORMULA_CHARS}; +use serde_json::{Value as Json, json}; + +use super::{CommandSpec, bad, cell_param_on, cmd, edit, has_doc, str_param, target_sheet}; +use crate::{EngineError, Result, Session}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "python.set", + "Set Python Code", + [], + None, + "{cell?, code, output?: object|value} makes the cell (default: the active cell) a Python cell with this code; the code must fit in Excel's 8,192-character formula once written as PY(…). `output` is the return type: `value` (an Excel value, the default) or `object` (a Python object)", + has_doc, + set + ), + cmd!( + "python.output", + "Python Output", + [], + Some("Ctrl+Alt+Shift+M"), + "{cell?, mode?: object|value} sets the return type of a Python cell (default: the active cell): `object` (a Python object) or `value` (an Excel value). Without `mode` it switches to the other one. The cell keeps its code; a cached result of the old return type goes, as with `python.set`, so the cell shows #BLOCKED! until it runs", + has_doc, + output + ), + ] +} + +fn target_cell(s: &Session, p: &Json) -> Result<(usize, CellRef)> { + let sheet = target_sheet(s, p)?; + let at = match cell_param_on(s, p, "cell", sheet)? { + Some(c) => c, + None => s.doc()?.selection.active, + }; + Ok((sheet, at)) +} + +fn existing(s: &Session, sheet: usize, at: CellRef) -> Result> { + Ok(s.doc()?.wb.sheet(sheet).and_then(|sh| sh.cell(at)).and_then(|c| c.py.as_deref()).cloned()) +} + +fn output_mode(cmd: &str, p: &Json, key: &str) -> Result> { + match p.get(key) { + None | Some(Json::Null) => return Ok(None), + Some(Json::String(_)) => {} + Some(_) => return Err(bad(cmd, format!("`{key}` is `object` or `value`"))), + } + match str_param(p, key) { + None => Ok(None), + Some(m) if m.eq_ignore_ascii_case("object") => Ok(Some(true)), + Some(m) if m.eq_ignore_ascii_case("value") => Ok(Some(false)), + Some(m) => Err(bad(cmd, format!("`{key}` is `object` or `value`, not `{m}`"))), + } +} + +fn set(s: &mut Session, p: &Json) -> Result { + let (sheet, at) = target_cell(s, p)?; + let code = match p.get("code") { + Some(Json::String(c)) => c.as_str(), + Some(_) => return Err(bad("python.set", "`code` must be text")), + None => return Err(bad("python.set", "missing `code`")), + }; + let mode = output_mode("python.set", p, "output")?; + let old = existing(s, sheet, at)?; + let object = mode.or(old.as_ref().map(|o| o.object)).unwrap_or(false); + store(s, "python.set", sheet, at, PyCode { object, ..PyCode::new(code) }, old)?; + let d = s.doc()?; + let shown = d.wb.sheet(sheet).map(|sh| sh.value(at)).unwrap_or_default(); + Ok(json!({"cell": at.a1(), "value": crate::cmd::inspect::value_json(&shown)})) +} + +/// Writes `py` into the cell, which held `old`: what `python.set` and `python.output` share. The +/// code must fit in one cell and a table header takes none; a locked cell on a protected sheet is +/// refused by the edit itself. +fn store(s: &mut Session, cmd: &str, sheet: usize, at: CellRef, mut py: PyCode, old: Option) -> Result<()> { + if !py.fits() { + return Err(bad( + cmd, + format!("the code doesn't fit in one cell: written as PY(…) it would be longer than Excel's {MAX_FORMULA_CHARS}-character formula limit"), + )); + } + // A table header is the column's name, never a formula or code (as in Excel). + let header = + s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.header_row && t.range.start.row == at.row && t.range.contains(at))); + if header { + return Err(EngineError::Other(format!("{} is a table header; Python cells can't go in a table's header row", at.a1()))); + } + // Unchanged code with the same return type keeps its result (and its value); new code, or a + // new return type, has none until it runs: a result of the other type would show a value and + // preview that don't belong to the cell. + let keep = old.filter(|o| o.code == py.code && o.object == py.object); + let value = match &keep { + Some(o) => { + py.output = o.output.clone(); + py.stale = o.stale; + None + } + None => Some(gridcraft_model::python::BLOCKED), + }; + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + let style = sh.style_id(at); + let value = value.unwrap_or_else(|| sh.cell(at).map(|c| c.value.clone()).unwrap_or(Value::Empty)); + // A spill the cell had (a formula's, or the old result's) is left to the recalculation, + // which removes it and recalculates what read it. + sh.set_cell(at, Cell { value, formula: None, style, py: Some(Arc::new(py)) }); + cx.touch(sheet, at); + Ok(()) + }) +} + +/// `python.output`: the cell's return type. The code stays; a cached result belongs to the old +/// return type, so it goes, as with `python.set` and a new return type: the cell shows +/// `#BLOCKED!` until it runs, and its old spill goes with its readers recalculated. +fn output(s: &mut Session, p: &Json) -> Result { + let (sheet, at) = target_cell(s, p)?; + let Some(old) = existing(s, sheet, at)? else { + return Err(EngineError::Other(format!("{} isn't a Python cell, so it has no Python output to change", at.a1()))); + }; + let object = output_mode("python.output", p, "mode")?.unwrap_or(!old.object); + let mode = |object: bool| if object { "object" } else { "value" }; + if object != old.object { + let py = PyCode { code: old.code.clone(), object, output: None, stale: false }; + store(s, "python.output", sheet, at, py, Some(old))?; + } + let d = s.doc()?; + let shown = d.wb.sheet(sheet).map(|sh| sh.value(at)).unwrap_or_default(); + Ok(json!({"cell": at.a1(), "output": mode(object), "value": crate::cmd::inspect::value_json(&shown)})) +} diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index d1aea3cc7f..de9c98ecde 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -35,6 +35,7 @@ pub fn specs() -> Vec { label: "Allow Edit Ranges…", menu: &["Review", "Protect"], shortcut: None, + shortcut_mac: None, params: "{action?: list (default) | add | modify | delete | unlock, title?, range?, password?, newTitle?, sheet?} → ranges", enabled: has_doc, run: allow_edit_ranges, diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 32122abd60..69e04dae62 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -141,14 +141,7 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: }; // Floating objects: snapshot their bottom-right corners against the pre-shift geometry, so a // re-fit after the shift measures against the grid the object actually lands on. - let obj_corners: Vec<(u32, u32, f32, f32)> = sh - .charts - .iter() - .map(|o| &o.anchor) - .chain(sh.images.iter().map(|o| &o.anchor)) - .chain(sh.shapes.iter().map(|o| &o.anchor)) - .map(|a| anchor_corner(sh, a)) - .collect(); + let obj_corners: Vec<(u32, u32, f32, f32)> = sh.object_anchors().map(|a| anchor_corner(sh, a)).collect(); // Line info. let lines = if axis == Axis::Rows { &mut sh.rows } else { &mut sh.cols }; let old = std::mem::take(lines); @@ -193,22 +186,13 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: std::mem::take(&mut sh.cell_pictures).into_iter().filter_map(|(c, v)| map_cell(c).filter(CellRef::is_valid).map(|c| (c, v))).collect(); sh.comments = std::mem::take(&mut sh.comments).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect(); sh.hyperlinks = std::mem::take(&mut sh.hyperlinks).into_iter().filter_map(|(c, v)| map_cell(c).map(|c| (c, v))).collect(); - // Floating objects follow their anchor lines per their [`AnchorMode`]. Corners were snapshotted - // as charts ++ images ++ shapes, matching the three slices below. New anchors are computed - // against the post-shift grid first (the re-fit needs its sizes), then written back. - let anchored = |ui: usize, a: Anchor| -> Anchor { obj_corners.get(ui).map_or(a, |&corner| shift_anchor(sh, a, corner, axis, at, &map_line)) }; - let new_charts: Vec = sh.charts.iter().enumerate().map(|(i, o)| anchored(i, o.anchor)).collect(); - let new_images: Vec = sh.images.iter().enumerate().map(|(i, o)| anchored(new_charts.len() + i, o.anchor)).collect(); - let base = new_charts.len() + new_images.len(); - let new_shapes: Vec = sh.shapes.iter().enumerate().map(|(i, o)| anchored(base + i, o.anchor)).collect(); - for (o, a) in sh.charts.iter_mut().zip(new_charts) { - o.anchor = a; - } - for (o, a) in sh.images.iter_mut().zip(new_images) { - o.anchor = a; - } - for (o, a) in sh.shapes.iter_mut().zip(new_shapes) { - o.anchor = a; + // Floating objects follow their anchor lines per their [`AnchorMode`]. New anchors are + // computed against the post-shift grid first (the re-fit needs its sizes), then written back + // in the same `object_anchors` order the corners were snapshotted in. + let new_anchors: Vec = + sh.object_anchors().zip(&obj_corners).map(|(a, &corner)| shift_anchor(sh, *a, corner, axis, at, &map_line)).collect(); + for (a, n) in sh.object_anchors_mut().zip(new_anchors) { + *a = n; } sh.sparklines.retain_mut(|sp| match map_cell(sp.cell) { Some(c) => { @@ -231,11 +215,12 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: } } -/// Rewrites every formula reference (and chart series) for a structural edit on `target`. -pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) { +/// Rewrites every formula reference (chart series included), sparkline source and PivotTable +/// source for a structural edit on `target`. +pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { cx.edits.push((target.to_string(), e.clone())); let wb = &mut cx.wb; - super::edit::rewrite_all_formulas(wb, target, e); + super::edit::rewrite_all_formulas(wb, target, e)?; for si in 0..wb.sheets.len() { let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); let Some(sh) = wb.sheet_mut(si) else { continue }; @@ -245,15 +230,6 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) { Err(_) => text.to_string(), } }; - for ch in sh.charts.iter_mut() { - // The source block moves with its cells; one that was deleted is dropped. - ch.source = ch.source.as_deref().map(fix).filter(|s| !s.contains("#REF!")); - for se in ch.series.iter_mut() { - se.values = fix(&se.values); - se.categories = se.categories.as_deref().map(fix); - se.name = se.name.as_deref().map(fix); - } - } for sp in sh.sparklines.iter_mut() { sp.source = fix(&sp.source); } @@ -270,6 +246,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) { } } } + Ok(()) } /// Inserting or deleting cells moves the copied block away from the stored source range, so, like @@ -327,7 +304,7 @@ fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result { // New lines take the format of the line before (Excel's "Format Same As Above"). inherit_line_format(sh, axis, at, count); } - rewrite(cx, &name, &Edit::Insert { axis, at, count }); + rewrite(cx, &name, &Edit::Insert { axis, at, count })?; cx.structural = true; Ok(Json::Null) })?; @@ -392,7 +369,7 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result { } shift_sheet_features(sh, axis, at, count, false); } - rewrite(cx, &name, &Edit::Delete { axis, at, count }); + rewrite(cx, &name, &Edit::Delete { axis, at, count })?; } cx.structural = true; Ok(Json::Null) @@ -444,7 +421,7 @@ fn move_columns(s: &mut Session, p: &Json) -> Result { sh.cells.shift_cols(before, count as i64); shift_sheet_features(sh, Axis::Cols, before, count, true); } - rewrite(cx, &name, &Edit::Insert { axis: Axis::Cols, at: before, count }); + rewrite(cx, &name, &Edit::Insert { axis: Axis::Cols, at: before, count })?; let mut touched = Vec::new(); { @@ -482,14 +459,14 @@ fn move_columns(s: &mut Session, p: &Json) -> Result { for cell in touched { cx.touch(sheet, cell); } - rewrite(cx, &name, &Edit::Move { from: source, to_row: 0, to_col: destination }); + rewrite(cx, &name, &Edit::Move { from: source, to_row: 0, to_col: destination })?; { let sh = cx.sheet_mut(sheet)?; sh.cells.shift_cols(delete_at + count, -(count as i64)); shift_sheet_features(sh, Axis::Cols, delete_at, count, false); } - rewrite(cx, &name, &Edit::Delete { axis: Axis::Cols, at: delete_at, count }); + rewrite(cx, &name, &Edit::Delete { axis: Axis::Cols, at: delete_at, count })?; *cx.sel = crate::Selection { active: CellRef::new(active_row, final_start), anchor: CellRef::new(active_row, final_start), @@ -520,7 +497,7 @@ fn insert_cells(s: &mut Session, p: &Json) -> Result { } else { RangeRef::new(CellRef::new(r.start.row.max(MAX_ROWS.saturating_sub(r.height())), r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col)) }; - if sh.cells.iter_range(doomed).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) { + if sh.cells.iter_range(doomed).any(|(_, x)| x.has_content()) { return Err(EngineError::Other("To prevent possible loss of data, GridCraft cannot shift nonblank cells off of the worksheet.".into())); } } @@ -534,7 +511,7 @@ fn insert_cells(s: &mut Session, p: &Json) -> Result { } shift_cell_features(sh, &e); let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default(); - rewrite(cx, &name, &e); + rewrite(cx, &name, &e)?; cx.structural = true; Ok(Json::Null) })?; @@ -569,7 +546,7 @@ fn delete_cells(s: &mut Session, p: &Json) -> Result { shift_cell_features(sh, &e); } // References into the deleted cells become #REF!; the rest move. - rewrite(cx, &name, &e); + rewrite(cx, &name, &e)?; cx.structural = true; Ok(Json::Null) })?; diff --git a/crates/engine/src/cmd/sheet/tabs.rs b/crates/engine/src/cmd/sheet/tabs.rs index 13956e35ce..0c3925d22f 100644 --- a/crates/engine/src/cmd/sheet/tabs.rs +++ b/crates/engine/src/cmd/sheet/tabs.rs @@ -63,6 +63,9 @@ pub(super) fn delete_sheet(s: &mut Session, p: &Json) -> Result { } } } + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order))?; + // Chart series into the deleted sheet become #REF!, like formulas. + crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::delete_sheet(e, &name, &order)); cx.wb.names.retain(|n| n.scope != Some(i)); for n in cx.wb.names.iter_mut() { if let Some(sc) = n.scope.as_mut() @@ -116,17 +119,7 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { } } } - let fix = |t: &str| { - gridcraft_formula::parse(t) - .map(|e| gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &old, &name))) - .unwrap_or_else(|_| t.to_string()) - }; for ch in sh.charts.iter_mut() { - for se in ch.series.iter_mut() { - se.values = fix(&se.values); - se.categories = se.categories.as_deref().map(fix); - se.name = se.name.as_deref().map(fix); - } // A PivotChart follows its PivotTable's sheet. if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link) && sheet.eq_ignore_ascii_case(&old) @@ -135,11 +128,13 @@ pub(super) fn rename_sheet(s: &mut Session, p: &Json) -> Result { } } } + crate::cmd::edit::rewrite_cell_links(&mut cx.wb, |_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name)); for n in cx.wb.names.iter_mut() { if let Ok(e) = gridcraft_formula::parse_name(&n.formula) { n.formula = gridcraft_formula::print(&gridcraft_formula::adjust::rename_sheet(e, &old, &name)); } } + crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|_, e| gridcraft_formula::adjust::rename_sheet(e, &old, &name))?; cx.structural = true; Ok(Json::Null) }) @@ -157,6 +152,8 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result { let Some(src) = cx.wb.sheets.get(i).cloned() else { return Err(bad("sheet.move", "no such sheet")) }; if copy { let mut sh = (*src).clone(); + // The copy is a sheet of its own, not the one it was copied from. + sh.uid = gridcraft_model::SheetUid::fresh(); let base = sh.name.clone(); // `Name (2)`: the name is shortened so the suffix fits in Excel's 31 characters. let name = (2..) @@ -170,6 +167,20 @@ pub(super) fn move_sheet(s: &mut Session, p: &Json) -> Result { sh.name = name; sh.tables.clear(); // table names must be unique sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original + // Object ids are unique across the workbook (selection and the `{kind, id}` commands + // rely on it), so the copied objects get fresh ones (free ones, even when a file used + // the largest id). + let count = sh.charts.len() + sh.images.len() + sh.shapes.len() + sh.slicers.len(); + let ids = cx.wb.free_object_ids(count); + if ids.len() < count { + return Err(bad("sheet.move", "no free object ids are left for the copied objects")); + } + let mut ids = ids.into_iter(); + let mut fresh = || ids.next().unwrap_or(u32::MAX); + sh.charts.iter_mut().for_each(|o| o.id = fresh()); + sh.images.iter_mut().for_each(|o| o.id = fresh()); + sh.shapes.iter_mut().for_each(|o| o.id = fresh()); + sh.slicers.iter_mut().for_each(|o| o.id = fresh()); let at = to.min(n); // The copy gets its own copies of the sheet's names, referring to the copy. let copies: Vec = cx diff --git a/crates/engine/src/cmd/solver.rs b/crates/engine/src/cmd/solver.rs index 95c0cb1460..c2d4b28c93 100644 --- a/crates/engine/src/cmd/solver.rs +++ b/crates/engine/src/cmd/solver.rs @@ -40,15 +40,16 @@ mod model_range; mod nlp; mod problem; mod reports; +mod sensitivity; use evolutionary::{EvoEnd, evolutionary}; -use lp::{Outcome, Sense, branch_and_bound, linearize, solve_lp}; -pub use model::saved_model; +use lp::{Outcome, SimplexProgram, branch_and_bound, simplex_program, solve_lp}; use model::{Goal, Method, Model, model_params, parse_model, save_model}; +pub use model::{saved_model, sensitivity_applies, sensitivity_status}; use model_range::{load_model_cells, reset_model, save_model_cells}; use nlp::{nlp, project}; use problem::{Evaluator, as_num, build_problem}; -use reports::{ReportInput, insert_report_selections, prepare_reports, report, report_kinds, write_reports}; +use reports::{NotOptimal, ReportInput, insert_report_selections, prepare_reports, report, report_kinds, write_reports}; const CMD: &str = "data.solver"; const REPORT_CMD: &str = "data.solverReport"; @@ -78,7 +79,7 @@ pub fn specs() -> Vec { "Solver…", ["Data", "Analysis"], None, - "{objective: \"B10\" (formula cell), goal?: max|min|value (default max), value?: number (for goal value), variables: \"B2:B4,D1\" (≤200 constant cells, same sheet), constraints?: [\"B5 <= 10\", \"B2:B4 >= C2:C4\", \"B2 int\", \"B3 bin\", {lhs: \"B6\", op: \"=\", rhs: 3 | \"C6\"}], nonNegative?: bool (default true: variables without a lower bound get 0), method?: grg|simplex|evolutionary (default grg), populationSize?: 100, mutationRate?: 0.075, randomSeed?: 0 (a fixed seed, so runs repeat), convergence?: 0.0001, generationsWithoutImprovement?: 50, requireBounds?: bool (default true: every variable needs both bounds; false searches within ±100 of the start) (Evolutionary options), keep?: bool (default true; false restores the original values), saveModel?: bool (default true: hidden names, solver_* as Excel names them, with the options; the evaluation limit and generations without improvement, which Excel lacks, as gridcraft_solver_evals and gridcraft_solver_stall), maxEvaluations?: 20000 (at most 200000), integerOptimality?: percent (default 0), saved?: bool (solve the sheet's saved model; other params override), reports?: [answer|limits] (written on new sheets when a solution is found)} → {status: optimal|converged|cannotImprove|iterationLimit|infeasible|unbounded|notLinear, message, objective, values: {cell: value}, original: {cell: value}, model: the model as params, evaluations, changed, reports?: [sheet names]}. No `objective` → {model: the saved model} (the menu opens the dialog).", + "{objective: \"B10\" (formula cell), goal?: max|min|value (default max), value?: number (for goal value), variables: \"B2:B4,D1\" (≤200 constant cells, same sheet), constraints?: [\"B5 <= 10\", \"B2:B4 >= C2:C4\", \"B2 int\", \"B3 bin\", {lhs: \"B6\", op: \"=\", rhs: 3 | \"C6\"}], nonNegative?: bool (default true: variables without a lower bound get 0), method?: grg|simplex|evolutionary (default grg), populationSize?: 100, mutationRate?: 0.075, randomSeed?: 0 (a fixed seed, so runs repeat), convergence?: 0.0001, generationsWithoutImprovement?: 50, requireBounds?: bool (default true: every variable needs both bounds; false searches within ±100 of the start) (Evolutionary options), keep?: bool (default true; false restores the original values), saveModel?: bool (default true: hidden names, solver_* as Excel names them, with the options; the evaluation limit and generations without improvement, which Excel lacks, as gridcraft_solver_evals and gridcraft_solver_stall), maxEvaluations?: 20000 (at most 200000), integerOptimality?: percent (default 0), saved?: bool (solve the sheet's saved model; other params override), reports?: [answer|sensitivity|limits] (written on new sheets when a solution is found)} → {status: optimal|converged|cannotImprove|iterationLimit|infeasible|unbounded|notLinear, message, objective, values: {cell: value}, original: {cell: value}, model: the model as params, evaluations, changed, reports?: [sheet names], skippedReports?: [{report: \"sensitivity\", reason}] (a Sensitivity report left out because the run did not reach an optimum or the values are not one; the solve and the other reports still apply)}. No `objective` → {model: the saved model} (the menu opens the dialog).", has_doc, run ), @@ -87,7 +88,7 @@ pub fn specs() -> Vec { "Solver Reports", [], None, - "{reports: [answer|limits], values?: {cell: number} (the solution; default the variable cells' current values), original?: {cell: number} (the values before solving; default `values`), message?: text (the result line), model?: data.solver params (default the sheet's saved model, with any data.solver params given here over it)} → {sheets: [names]}. Writes Answer and Limits reports on new sheets before the model's sheet; Limits needs Simplex LP or GRG Nonlinear and no integer constraints. data.solver's result can be passed as is.", + "{reports: [answer|sensitivity|limits], values?: {cell: number} (the solution; default the variable cells' current values), original?: {cell: number} (the values before solving; default `values`), message?: text (the result line), skipNotOptimal?: bool (default false: a Sensitivity report for values that are not optimal refuses the call; true leaves it out and writes the others), model?: data.solver params (default the sheet's saved model, with any data.solver params given here over it)} → {sheets: [names], skippedReports?: [{report, reason}]}. Writes Answer, Sensitivity and Limits reports on new sheets before the model's sheet; Sensitivity and Limits need Simplex LP or GRG Nonlinear and no integer constraints, and Sensitivity a Max or Min objective. data.solver's result can be passed as is.", has_doc, report ), @@ -146,24 +147,13 @@ fn optimise(ev: &mut Evaluator, m: &Model, goal: Goal, x0: &[f64], bounds: Bound Outcome::Infeasible } else { match m.method { - Method::Simplex => match linearize(ev, x0) { + Method::Simplex => match simplex_program(ev, goal, x0) { Err("nonlinear") | Err("error") => { not_linear = true; Outcome::Infeasible } Err(_) => Outcome::Limit, - Ok(((cf, f_const), lin)) => { - let mut rows: Vec<(Vec, Sense, f64)> = lin.iter().zip(&ev.rows).map(|((a, k), r)| (a.clone(), r.sense, -k)).collect(); - let c: Vec = match goal { - Goal::Max => cf.iter().map(|v| -v).collect(), - Goal::Min => cf.clone(), - Goal::Value(v) => { - rows.push((cf.clone(), Sense::Eq, v - f_const)); - vec![0.0; cf.len()] - } - }; - let size = (rows.len() as u64 + 2 * x0.len() as u64 + 1) * (4 * x0.len() as u64 + 2 * rows.len() as u64 + 1); - let mut work = LP_WORK.max(size); + Ok(SimplexProgram { c, rows, mut work, .. }) => { let mut relax = |l: &[f64], h: &[f64]| solve_lp(&c, &rows, l, h, &mut work); if any_int { branch_and_bound(lo, hi, integer, MAX_NODES_LP, gap, &mut relax).0 } else { relax(lo, hi) } } @@ -218,6 +208,14 @@ fn run(s: &mut Session, p: &Json) -> Result { let save = bool_param(¶ms, "saveModel").unwrap_or(true); let reports = report_kinds(CMD, ¶ms)?; let prob = build_problem(&model); + // A Sensitivity report the model has none of (integer, Evolutionary, Value Of) fails the + // call, so it is refused before the solve runs rather than after it. + if let Some(kinds) = &reports + && kinds.contains(&reports::ReportKind::Sensitivity) + && let Some(why) = sensitivity::sensitivity_refusal(&model, &prob) + { + return Err(EngineError::Other(why.into())); + } let d = s.doc()?; let sh = d.wb.sheet(model.sheet).ok_or(EngineError::NoDocument)?; let x0: Vec = model.vars.iter().map(|c| as_num(&sh.value(*c))).map(|v| if v.is_finite() { v } else { 0.0 }).collect(); @@ -277,12 +275,14 @@ fn run(s: &mut Session, p: &Json) -> Result { } let original: serde_json::Map = model.vars.iter().zip(&x0).map(|(c, v)| (c.a1(), json!(v))).collect(); let changed = keep && solution.is_some(); - let built = match (&reports, &solution) { + // A Sensitivity report the solution doesn't support is left out (with its reason), so the + // solve and the other reports still apply. + let (built, skipped) = match (&reports, &solution) { (Some(kinds), Some(x)) => { let inp = ReportInput { model: &model, prob: &prob, original: x0, solution: x.clone(), message: message.to_string(), budget }; - prepare_reports(s.doc()?, kinds, &inp)? + prepare_reports(s.doc()?, kinds, &inp, NotOptimal::Skip { optimum: sensitivity_status(status) })? } - _ => Vec::new(), + _ => (Vec::new(), Vec::new()), }; let count = built.len(); let before = s.doc()?.wb.clone(); @@ -303,7 +303,7 @@ fn run(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; for (c, v) in model.vars.iter().zip(x) { let style = sh.style_id(*c); - sh.set_cell(*c, Cell { value: Value::number(*v), formula: None, style }); + sh.set_cell(*c, Cell { value: Value::number(*v), formula: None, style, py: None }); } for c in &model.vars { cx.touch(sheet + count, *c); @@ -325,6 +325,9 @@ fn run(s: &mut Session, p: &Json) -> Result { if reports.is_some() && solution.is_some() { out["reports"] = json!(names); } + if !skipped.is_empty() { + out["skippedReports"] = json!(skipped); + } Ok(out) } diff --git a/crates/engine/src/cmd/solver/lp.rs b/crates/engine/src/cmd/solver/lp.rs index dc67d7746a..af5e2e6f80 100644 --- a/crates/engine/src/cmd/solver/lp.rs +++ b/crates/engine/src/cmd/solver/lp.rs @@ -1,10 +1,14 @@ +use super::model::Goal; use super::problem::Evaluator; -use super::{CellRef, EPS}; +use super::{CellRef, EPS, LP_WORK}; // ---------------------------------------------------------------- evaluation type BoundRow = (Vec<(usize, f64)>, Sense, f64); +/// A row of an LP: coefficients, sense and right side. +pub(super) type LpRow = (Vec, Sense, f64); + /// Objective (gradient, constant) and per-row (gradient, constant). pub(super) type Linearized = ((Vec, f64), Vec<(Vec, f64)>); @@ -34,9 +38,10 @@ pub(super) enum Outcome { Limit, } -struct Map { - var: usize, - sign: f64, +/// A column of the simplex tableau standing for a variable: `x_var = offset + Σ sign·y`. +pub(super) struct Map { + pub(super) var: usize, + pub(super) sign: f64, } struct VariableMap { @@ -45,6 +50,23 @@ struct VariableMap { bound_rows: Vec, } +/// The final tableau of an optimal LP, for the Sensitivity report. +pub(super) struct FinalTableau { + /// Rows `B⁻¹A | B⁻¹b`. + pub(super) t: Vec>, + pub(super) basis: Vec, + /// The phase-2 reduced costs. + pub(super) obj: Vec, + pub(super) width: usize, + /// The first artificial column. + pub(super) first_art: usize, + pub(super) cols: Vec, + /// Per input row: the column that started as its unit column, and whether the row was + /// negated to make its right side non-negative. + pub(super) ident: Vec, + pub(super) flipped: Vec, +} + struct Tableau { rows: Vec>, basis: Vec, @@ -82,7 +104,9 @@ fn map_variables(n: usize, lo: &[f64], hi: &[f64]) -> VariableMap { VariableMap { columns, offset, bound_rows } } -fn normalize_rows(rows: &[(Vec, Sense, f64)], bound_rows: Vec, columns: &[Map], offset: &[f64]) -> Vec<(Vec, Sense, f64)> { +/// The rows over the tableau's columns, each with a non-negative right side, and per row +/// whether it was negated to get there. +fn normalize_rows(rows: &[(Vec, Sense, f64)], bound_rows: Vec, columns: &[Map], offset: &[f64]) -> (Vec, Vec) { let width = columns.len(); let mut transformed = Vec::with_capacity(rows.len() + bound_rows.len()); for (coefficients, sense, rhs) in rows { @@ -105,7 +129,8 @@ fn normalize_rows(rows: &[(Vec, Sense, f64)], bound_rows: Vec, co transformed.push((row, sense, rhs)); } // Rows with a negative right side are negated so every right side is >= 0. - transformed + let flipped = transformed.iter().map(|row| row.2 < 0.0).collect(); + let normalized = transformed .into_iter() .map(|(row, sense, rhs)| { if rhs < 0.0 { @@ -119,7 +144,8 @@ fn normalize_rows(rows: &[(Vec, Sense, f64)], bound_rows: Vec, co (row, sense, rhs) } }) - .collect() + .collect(); + (normalized, flipped) } fn build_tableau(normalized: &[(Vec, Sense, f64)], decision_cols: usize, slack_cols: usize, artificial_cols: usize) -> Tableau { @@ -388,20 +414,33 @@ fn simplex(t: &mut [Vec], basis: &mut [usize], obj: &mut [f64], allowed: &[ /// Minimises `c·x` subject to `rows` (coefficients, sense, rhs) and `lo ≤ x ≤ hi`. pub(super) fn solve_lp(c: &[f64], rows: &[(Vec, Sense, f64)], lo: &[f64], hi: &[f64], budget: &mut u64) -> Outcome { + solve_lp_tableau(c, rows, lo, hi, budget).0 +} + +/// [`solve_lp`], with the final tableau when it is optimal. +pub(super) fn solve_lp_tableau( + c: &[f64], + rows: &[(Vec, Sense, f64)], + lo: &[f64], + hi: &[f64], + budget: &mut u64, +) -> (Outcome, Option) { if lo.iter().zip(hi).any(|(l, h)| l > h) { - return Outcome::Infeasible; + return (Outcome::Infeasible, None); } // x_j = offset + Σ sign·y_k with y ≥ 0. let mapping = map_variables(c.len(), lo, hi); let VariableMap { columns: cols, offset, bound_rows: extra } = mapping; let ny = cols.len(); // Rows over y: (coefficients, sense, rhs). - let normalized = normalize_rows(rows, extra, &cols, &offset); + let (normalized, flipped) = normalize_rows(rows, extra, &cols, &offset); let n_slack = normalized.iter().filter(|row| row.1 != Sense::Eq).count(); let n_art = normalized.iter().filter(|row| row.1 != Sense::Le).count(); let mut tableau = build_tableau(&normalized, ny, n_slack, n_art); + // Each row's starting basic column is its unit column. + let ident = tableau.basis.clone(); if let Err(outcome) = phase_one(&mut tableau, &normalized, budget) { - return outcome; + return (outcome, None); } let Tableau { rows: mut t, mut basis, width, decision_cols: ny, slack_cols: n_slack, .. } = tableau; let is_art = |column: usize| column >= ny + n_slack && column < width; @@ -423,8 +462,8 @@ pub(super) fn solve_lp(c: &[f64], rows: &[(Vec, Sense, f64)], lo: &[f64], h } let allowed: Vec = (0..width).map(|j| !is_art(j)).collect(); match simplex(&mut t, &mut basis, &mut obj, &allowed, budget) { - Step::Limit => return Outcome::Limit, - Step::Unbounded => return Outcome::Unbounded, + Step::Limit => return (Outcome::Limit, None), + Step::Unbounded => return (Outcome::Unbounded, None), Step::Optimal => {} } let mut y = vec![0.0; width]; @@ -442,7 +481,43 @@ pub(super) fn solve_lp(c: &[f64], rows: &[(Vec, Sense, f64)], lo: &[f64], h } } let val: f64 = c.iter().zip(&x).map(|(a, b)| a * b).sum(); - Outcome::Solved(x, val, true) + let tableau = FinalTableau { t, basis, obj, width, first_art: ny + n_slack, cols, ident, flipped }; + (Outcome::Solved(x, val, true), Some(tableau)) +} + +/// The LP to minimise for `goal`, from the linearised model: the costs, and the rows +/// (coefficients, sense, right side) in the order of `model_rows`. +pub(super) fn linear_program(goal: Goal, cf: &[f64], f_const: f64, lin: &[(Vec, f64)], model_rows: &[Row]) -> (Vec, Vec) { + let mut rows: Vec = lin.iter().zip(model_rows).map(|((a, k), r)| (a.clone(), r.sense, -k)).collect(); + let c = match goal { + Goal::Max => cf.iter().map(|v| -v).collect(), + Goal::Min => cf.to_vec(), + Goal::Value(v) => { + rows.push((cf.to_vec(), Sense::Eq, v - f_const)); + vec![0.0; cf.len()] + } + }; + (c, rows) +} + +/// The linear program Simplex LP solves: the model linearised at `x0`, its objective +/// coefficients, the costs and rows for the goal, and the work limit for its size. +pub(super) struct SimplexProgram { + pub(super) cf: Vec, + pub(super) c: Vec, + pub(super) rows: Vec, + pub(super) work: u64, +} + +/// Builds the [`SimplexProgram`] at `x0`. The solve and the Sensitivity report both build it +/// here from the start values, so the report's solve repeats the solve's pivots and returns the +/// same vertex: linearising at another point changes the coefficients in their last bits, and +/// that can break a tie between pivots the other way. +pub(super) fn simplex_program(ev: &mut Evaluator, goal: Goal, x0: &[f64]) -> std::result::Result { + let ((cf, f_const), lin) = linearize(ev, x0)?; + let (c, rows) = linear_program(goal, &cf, f_const, &lin, &ev.rows); + let size = (rows.len() as u64 + 2 * x0.len() as u64 + 1) * (4 * x0.len() as u64 + 2 * rows.len() as u64 + 1); + Ok(SimplexProgram { cf, c, rows, work: LP_WORK.max(size) }) } /// Linearises the model at `x0` (n + 1 evaluations) and checks it at one more point. Returns the diff --git a/crates/engine/src/cmd/solver/model.rs b/crates/engine/src/cmd/solver/model.rs index d6b7d9b8c0..c7ccd6c96b 100644 --- a/crates/engine/src/cmd/solver/model.rs +++ b/crates/engine/src/cmd/solver/model.rs @@ -263,7 +263,8 @@ pub(super) fn parse_model(s: &Session, p: &Json) -> Result { } let mut seen = std::collections::HashSet::new(); vars.retain(|c| seen.insert(*c)); - if vars.iter().any(|c| sh.cell(*c).is_some_and(|c| c.formula.is_some())) { + // Python cells count as formulas: a solution written over one would lose its code. + if vars.iter().any(|c| sh.cell(*c).is_some_and(|c| c.formula.is_some() || c.py.is_some())) { return Err(EngineError::Other("Variable cells must hold constants, not formulas.".into())); } let mut cons = Vec::new(); @@ -305,6 +306,32 @@ pub(super) fn parse_model(s: &Session, p: &Json) -> Result { Ok(Model { sheet, objective, goal, vars, vars_text, cons, non_negative, method, evo: evo_options(p), max_evals, gap }) } +/// Whether a `data.solver` result status is a solution the Sensitivity report can describe: an +/// optimum (Simplex LP) or a converged local optimum (GRG Nonlinear). A run that stopped at its +/// evaluation limit, or an Evolutionary run, has none. +pub fn sensitivity_status(status: &str) -> bool { + matches!(status, "optimal" | "converged") +} + +/// Whether `data.solver` params (such as the `model` of its result) describe a model that can +/// have a Sensitivity report: Simplex LP or GRG Nonlinear, a Max or Min objective and no +/// integer or binary constraints. +pub fn sensitivity_applies(p: &Json) -> bool { + let method = str_param(p, "method").unwrap_or("grg").to_ascii_lowercase().replace([' ', '_', '-'], ""); + let goal = str_param(p, "goal").or_else(|| str_param(p, "to")).unwrap_or("max").to_ascii_lowercase(); + let integer = p.get("constraints").and_then(Json::as_array).is_some_and(|list| { + list.iter().any(|c| { + let rel = match c { + Json::String(t) => split_constraint(t).map(|(_, rel, _)| rel), + Json::Object(_) => str_param(c, "op").or_else(|| str_param(c, "relation")).and_then(Rel::parse), + _ => None, + }; + matches!(rel, Some(Rel::Int | Rel::Bin)) + }) + }); + !integer && !matches!(method.as_str(), "evolutionary" | "evo" | "genetic") && !matches!(goal.as_str(), "value" | "valueof" | "value of") +} + // ---------------------------------------------------------------- saved model /// `"B2:B4,D1"` as absolute references, each qualified by `sheet_name` when given. diff --git a/crates/engine/src/cmd/solver/model_range.rs b/crates/engine/src/cmd/solver/model_range.rs index 7d47b71763..b68b8bfb9e 100644 --- a/crates/engine/src/cmd/solver/model_range.rs +++ b/crates/engine/src/cmd/solver/model_range.rs @@ -107,12 +107,12 @@ fn check_column_spills(sheet: &Sheet, column: RangeRef, ours: &[CellRef]) -> Res Ok(()) } -/// Refused, unless `overwrite`, when a cell of the model's column holds a value or a formula -/// (a model saved there before included): Save Model then asks before it replaces data, as -/// Excel does. The message carries [`OVERWRITE_ERROR`], which the dialog turns into its +/// Refused, unless `overwrite`, when a cell of the model's column holds a value, a formula or +/// Python code (a model saved there before included): Save Model then asks before it replaces +/// data, as Excel does. The message carries [`OVERWRITE_ERROR`], which the dialog turns into its /// question. fn check_column_empty(sheet: &Sheet, column: RangeRef, overwrite: bool) -> Result<()> { - let taken = column.iter().find(|c| sheet.cell(*c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some())); + let taken = column.iter().find(|c| sheet.cell(*c).is_some_and(Cell::has_content)); match taken { Some(c) if !overwrite => Err(EngineError::Other(format!( "The range {} {OVERWRITE_ERROR} ({} isn't empty); pass overwrite: true to replace it.", @@ -176,7 +176,7 @@ pub(super) fn save_model_cells(s: &mut Session, p: &Json) -> Result { } for c in &stale { let style = sh.style_id(*c); - sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style }); + sh.set_cell(*c, Cell { value: Value::Empty, formula: None, style, py: None }); } for c in cells.into_iter().chain(stale) { cx.touch(sheet, c); diff --git a/crates/engine/src/cmd/solver/reports.rs b/crates/engine/src/cmd/solver/reports.rs index d3916b8961..19500cab0d 100644 --- a/crates/engine/src/cmd/solver/reports.rs +++ b/crates/engine/src/cmd/solver/reports.rs @@ -1,9 +1,10 @@ use super::lp::Outcome; use super::model::{Constraint, Goal, Method, Model, Rel, Rhs, parse_model, saved_model}; use super::problem::{Evaluator, Problem, as_num, build_problem}; +use super::sensitivity::{sensitivity_refusal, sensitivity_report}; use super::{ - Cell, CellRef, Ctx, DocState, EngineError, Json, PRECISION, REPORT_CMD, Result, Session, Sheet, Trial, Value, bad, edit, json, optimise, - str_param, + Cell, CellRef, Ctx, DocState, EngineError, Json, PRECISION, REPORT_CMD, Result, Session, Sheet, Trial, Value, bad, bool_param, edit, json, + optimise, str_param, }; // ---------------------------------------------------------------- reports @@ -11,6 +12,7 @@ use super::{ #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum ReportKind { Answer, + Sensitivity, Limits, } @@ -18,6 +20,7 @@ impl ReportKind { fn title(self) -> &'static str { match self { ReportKind::Answer => "Answer", + ReportKind::Sensitivity => "Sensitivity", ReportKind::Limits => "Limits", } } @@ -26,13 +29,14 @@ impl ReportKind { /// The `reports` list (`None` when absent). pub(super) fn report_kinds(cmd: &'static str, p: &Json) -> Result>> { let Some(list) = p.get("reports") else { return Ok(None) }; - let list = list.as_array().ok_or_else(|| bad(cmd, "`reports` must be an array of answer and limits"))?; + let list = list.as_array().ok_or_else(|| bad(cmd, "`reports` must be an array of answer, sensitivity and limits"))?; let mut kinds = Vec::new(); for k in list { let kind = match k.as_str().map(|t| t.trim().to_ascii_lowercase()).as_deref() { Some("answer") => ReportKind::Answer, + Some("sensitivity") => ReportKind::Sensitivity, Some("limits") => ReportKind::Limits, - _ => return Err(bad(cmd, format!("unknown report {k} (answer or limits)"))), + _ => return Err(bad(cmd, format!("unknown report {k} (answer, sensitivity or limits)"))), }; if !kinds.contains(&kind) { kinds.push(kind); @@ -42,14 +46,14 @@ pub(super) fn report_kinds(cmd: &'static str, p: &Json) -> Result; +pub(super) type Lines = Vec<(u32, u32, Value, bool)>; -fn abs_ref(c: CellRef) -> String { +pub(super) fn abs_ref(c: CellRef) -> String { format!("${}${}", gridcraft_core::col_to_letters(c.col), u64::from(c.row) + 1) } /// A cell's name in the reports: the nearest text to its left and the nearest text above it. -fn cell_name(sh: &Sheet, c: CellRef) -> String { +pub(super) fn cell_name(sh: &Sheet, c: CellRef) -> String { let text = |c: CellRef| match sh.value(c) { Value::Text(t) if !t.trim().is_empty() => Some(t.to_string()), _ => None, @@ -68,7 +72,7 @@ fn method_name(m: Method) -> &'static str { } /// Header labels in bold from column 1, then the rows below them; returns the next free row. -fn table(out: &mut Lines, row: u32, headers: &[&str], rows: Vec>) -> u32 { +pub(super) fn table(out: &mut Lines, row: u32, headers: &[&str], rows: Vec>) -> u32 { for (k, h) in headers.iter().enumerate() { out.push((row, 1 + k as u32, Value::text(*h), true)); } @@ -92,7 +96,7 @@ pub(super) struct ReportInput<'a> { pub(super) budget: u64, } -fn title(out: &mut Lines, kind: ReportKind, sheet: &str) -> u32 { +pub(super) fn title(out: &mut Lines, kind: ReportKind, sheet: &str) -> u32 { out.push((0, 0, Value::text(format!("GridCraft {} Report", kind.title())), true)); out.push((1, 0, Value::text(format!("Worksheet: {sheet}")), false)); 3 @@ -255,18 +259,67 @@ fn limits_report(d: &DocState, sh: &Sheet, inp: &ReportInput) -> Result { } /// Builds every report before the solution or saved model can change. -pub(super) fn prepare_reports(d: &DocState, kinds: &[ReportKind], inp: &ReportInput) -> Result> { +/// What happens to a Sensitivity report the model allows but the solution doesn't: `Refuse` +/// fails the call before anything changes; `Skip` leaves the report out, with its reason, and +/// writes the others. `optimum` is false when the solve stopped before an optimum, so the +/// report isn't attempted. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum NotOptimal { + Refuse, + Skip { optimum: bool }, +} + +/// The reports left out under [`NotOptimal::Skip`], as `{report, reason}`. +pub(super) type Skipped = Vec; + +pub(super) fn prepare_reports( + d: &DocState, + kinds: &[ReportKind], + inp: &ReportInput, + not_optimal: NotOptimal, +) -> Result<(Vec<(String, Lines)>, Skipped)> { if kinds.is_empty() { - return Ok(Vec::new()); + return Ok((Vec::new(), Vec::new())); } - if d.wb.protected_structure { - return Err(EngineError::Other("The workbook is protected and cannot be changed.".into())); + // A request that must write a sheet is refused before any report is built (a Limits report + // runs two optimisations per variable); only a Sensitivity report that may be skipped waits + // for the check after the loop. + let must_write = kinds.iter().any(|k| *k != ReportKind::Sensitivity || not_optimal == NotOptimal::Refuse); + if must_write && d.wb.protected_structure { + return Err(protected()); + } + // A model that has no Sensitivity report (integer, Evolutionary, Value Of) is refused in + // both modes before any report is built: a Limits report listed first would otherwise run + // its two optimisations per variable for an error. Only the solution's own refusal (not + // optimal) waits for the loop, where `Skip` may leave the report out. + if kinds.contains(&ReportKind::Sensitivity) + && let Some(why) = sensitivity_refusal(inp.model, inp.prob) + { + return Err(EngineError::Other(why.into())); } let sh = d.wb.sheet(inp.model.sheet).ok_or(EngineError::NoDocument)?; let mut built = Vec::new(); + let mut skipped = Vec::new(); for k in kinds { let lines = match k { ReportKind::Answer => answer_report(d, sh, inp), + ReportKind::Sensitivity => match not_optimal { + NotOptimal::Skip { optimum } => { + let got = if optimum { + sensitivity_report(d, sh, inp).map_err(|e| e.to_string()) + } else { + Err("Solver did not reach an optimal solution, so the Sensitivity report was not written.".to_string()) + }; + match got { + Ok(lines) => lines, + Err(reason) => { + skipped.push(json!({"report": "sensitivity", "reason": reason})); + continue; + } + } + } + NotOptimal::Refuse => sensitivity_report(d, sh, inp)?, + }, ReportKind::Limits => limits_report(d, sh, inp)?, }; let name = (1..=10_000u32) @@ -275,7 +328,16 @@ pub(super) fn prepare_reports(d: &DocState, kinds: &[ReportKind], inp: &ReportIn .ok_or_else(|| EngineError::Other("Too many report sheets.".into()))?; built.push((name, lines)); } - Ok(built) + // Only a report sheet changes the workbook's structure, so a request whose reports were all + // skipped still succeeds in a protected workbook. + if !built.is_empty() && d.wb.protected_structure { + return Err(protected()); + } + Ok((built, skipped)) +} + +fn protected() -> EngineError { + EngineError::Other("The workbook is protected and cannot be changed.".into()) } /// Inserts prepared reports before the model's sheet, which stays active. @@ -290,9 +352,9 @@ pub(super) fn write_reports(cx: &mut Ctx, at: usize, built: Vec<(String, Lines)> let mut sheet = Sheet::new(name); for (r, c, v, b) in lines { let style = if b { bold } else { gridcraft_model::StyleId::DEFAULT }; - sheet.set_cell(CellRef::new(r, c), Cell { value: v, formula: None, style }); + sheet.set_cell(CellRef::new(r, c), Cell { value: v, formula: None, style, py: None }); } - for (c, w) in [(0u32, 14.0f32), (1, 110.0), (2, 140.0), (3, 120.0), (4, 120.0), (5, 120.0), (6, 120.0), (7, 120.0)] { + for (c, w) in [(0u32, 14.0f32), (1, 110.0), (2, 140.0), (3, 120.0), (4, 120.0), (5, 155.0), (6, 140.0), (7, 140.0)] { sheet.cols.insert(c, gridcraft_model::LineInfo { size: Some(w), ..Default::default() }); } cx.wb.sheets.insert(at + i, std::sync::Arc::new(sheet)); @@ -321,9 +383,9 @@ pub(super) fn insert_report_selections(s: &mut Session, at: usize, count: usize) /// `data.solverReport`: reports for a solution of the sheet's saved model. pub(super) fn report(s: &mut Session, p: &Json) -> Result { - let kinds = report_kinds(REPORT_CMD, p)?.ok_or_else(|| bad(REPORT_CMD, "missing `reports` (answer, limits)"))?; + let kinds = report_kinds(REPORT_CMD, p)?.ok_or_else(|| bad(REPORT_CMD, "missing `reports` (answer, sensitivity, limits)"))?; if kinds.is_empty() { - return Err(bad(REPORT_CMD, "`reports` is empty (answer, limits)")); + return Err(bad(REPORT_CMD, "`reports` is empty (answer, sensitivity, limits)")); } let d = s.doc()?; // The given model as is, else the saved model with any params given here over it. @@ -365,8 +427,14 @@ pub(super) fn report(s: &mut Session, p: &Json) -> Result { let budget = model.max_evals; let message = str_param(p, "message").unwrap_or("").chars().take(500).collect(); let inp = ReportInput { model: &model, prob: &prob, original, solution, message, budget }; - let built = prepare_reports(s.doc()?, &kinds, &inp)?; - let sheets = edit(s, |cx| Ok(write_reports(cx, model.sheet, built)))?; + let not_optimal = if bool_param(p, "skipNotOptimal").unwrap_or(false) { NotOptimal::Skip { optimum: true } } else { NotOptimal::Refuse }; + let (built, skipped) = prepare_reports(s.doc()?, &kinds, &inp, not_optimal)?; + // Nothing left to write (every report skipped): no edit, so no Undo step. + let sheets = if built.is_empty() { Vec::new() } else { edit(s, |cx| Ok(write_reports(cx, model.sheet, built)))? }; insert_report_selections(s, model.sheet, sheets.len()); - Ok(json!({"sheets": sheets})) + let mut out = json!({"sheets": sheets}); + if !skipped.is_empty() { + out["skippedReports"] = json!(skipped); + } + Ok(out) } diff --git a/crates/engine/src/cmd/solver/sensitivity.rs b/crates/engine/src/cmd/solver/sensitivity.rs new file mode 100644 index 0000000000..5e047fe420 --- /dev/null +++ b/crates/engine/src/cmd/solver/sensitivity.rs @@ -0,0 +1,614 @@ +//! The Sensitivity report. Simplex LP: each variable's reduced cost and the range of its +//! objective coefficient over which the basis stays optimal, and each constraint's shadow price +//! and the range of its right side over which the shadow price holds, from the final tableau of +//! the LP linearised at the solution. GRG Nonlinear: the reduced gradients and the Lagrange +//! multipliers of the binding constraints at the solution, from difference gradients. + +use super::lp::{FinalTableau, LpRow, Outcome, Row, Sense, SimplexProgram, simplex_program, solve_lp_tableau}; +use super::model::{Goal, Method, Model}; +use super::problem::{Evaluator, Point, Problem, as_num}; +use super::reports::{Lines, ReportInput, ReportKind, abs_ref, cell_name, table, title}; +use super::{CellRef, DocState, EPS, EngineError, Result, Sheet, Trial, Value}; + +/// Excel prints an unlimited allowable change as 1E+30. +const NO_LIMIT: f64 = 1e30; + +/// Most arithmetic the Lagrange multipliers of a nonlinear model may take (about a second): a +/// pass over k binding rows and f free variables costs about 3·k²·f (the normal equations and +/// each multiplier's noise), and each pass drops at most one row, so a model at the constraint +/// limit could otherwise take minutes. +#[cfg(not(test))] +const MULTIPLIER_WORK: u64 = 1_000_000_000; +/// A low limit in tests, so the refusal is reachable with a small model. +#[cfg(test)] +const MULTIPLIER_WORK: u64 = 20_000; + +/// Why a model has no Sensitivity report (`None` when it has one). +pub(super) fn sensitivity_refusal(m: &Model, prob: &Problem) -> Option<&'static str> { + if prob.integer.iter().any(|b| *b) { + Some("The Sensitivity report doesn't apply to models with integer or binary constraints.") + } else if m.method == Method::Evolutionary { + Some("The Sensitivity report is available for Simplex LP and GRG Nonlinear.") + } else if matches!(m.goal, Goal::Value(_)) { + Some("The Sensitivity report needs an objective to maximise or minimise.") + } else { + None + } +} + +/// A sensitivity figure: values within `noise` of zero (rounding) print as 0, unlimited ones +/// as 1E+30. The noise level is local to the figure: it comes from the terms the figure is a +/// sum of (the rounding error of a sum scales with the sum of its terms' sizes), never from +/// the model's largest coefficient or gradient component, so a small price or gradient keeps +/// its value beside a large unrelated one, and never from the objective's value, so adding a +/// constant to the objective changes nothing the report shows. +fn sens_num(v: f64, noise: f64) -> Value { + if !v.is_finite() || v >= NO_LIMIT { + Value::number(NO_LIMIT) + } else if v.abs() <= noise { + Value::number(0.0) + } else { + Value::number(v) + } +} + +fn num(v: f64) -> Value { + if v.is_finite() { Value::number(v) } else { Value::Error(gridcraft_core::CellError::Value) } +} + +/// The smallest ratio `num / den` over the `den` above zero (the step to the first bound). +fn min_ratio(pairs: impl Iterator) -> f64 { + pairs.filter(|(_, den)| *den > EPS).map(|(num, den)| num.max(0.0) / den).fold(f64::INFINITY, f64::min) +} + +/// Solves the square system `a·x = b` by Gaussian elimination with partial pivoting; unknowns +/// of a singular system that have no pivot are 0. +fn solve_dense(mut a: Vec>, mut b: Vec) -> Vec { + let n = b.len(); + let scale = a.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE); + let mut pivots: Vec> = vec![None; n]; + let mut row = 0; + for col in 0..n { + let Some(p) = (row..n).max_by(|i, k| { + let v = |r: &usize| a.get(*r).and_then(|x| x.get(col)).map_or(0.0, |v| v.abs()); + v(i).total_cmp(&v(k)) + }) else { + break; + }; + if a.get(p).and_then(|x| x.get(col)).is_none_or(|v| v.abs() <= 1e-12 * scale) { + continue; + } + a.swap(row, p); + b.swap(row, p); + let (Some(prow), Some(pb)) = (a.get(row).cloned(), b.get(row).copied()) else { break }; + let pv = prow.get(col).copied().unwrap_or(1.0); + for (i, (r, bi)) in a.iter_mut().zip(b.iter_mut()).enumerate() { + if i == row { + continue; + } + let f = r.get(col).copied().unwrap_or(0.0) / pv; + if f != 0.0 { + for (v, p) in r.iter_mut().zip(&prow) { + *v -= f * p; + } + *bi -= f * pb; + } + } + if let Some(e) = pivots.get_mut(col) { + *e = Some(row); + } + row += 1; + } + pivots + .iter() + .enumerate() + .map(|(col, p)| match p { + Some(r) => b.get(*r).copied().unwrap_or(0.0) / a.get(*r).and_then(|x| x.get(col)).copied().unwrap_or(1.0), + None => 0.0, + }) + .collect() +} + +fn out_of_evaluations() -> EngineError { + EngineError::Other("Solver ran out of evaluations.".into()) +} + +fn not_optimal() -> EngineError { + EngineError::Other("The Sensitivity report needs an optimal solution: these values are not optimal for the model. Solve it first.".into()) +} + +/// What both report bodies share: the model, the solution, its objective value and the rows' +/// final values and right sides. +struct At<'a> { + inp: &'a ReportInput<'a>, + sh: &'a Sheet, + point: Point, + finals: Vec<(f64, f64)>, +} + +impl At<'_> { + fn var_head(&self, j: usize, c: CellRef) -> Vec { + vec![Value::text(abs_ref(c)), Value::text(cell_name(self.sh, c)), num(self.inp.solution.get(j).copied().unwrap_or(f64::NAN))] + } + fn row_head(&self, i: usize, r: &Row) -> Vec { + let fin = self.finals.get(i).map_or(f64::NAN, |f| f.0); + vec![Value::text(abs_ref(r.lhs)), Value::text(cell_name(self.sh, r.lhs)), num(fin)] + } +} + +/// The variable rows, the constraint rows and their headers. +type Body = (Vec>, Vec>, Vec<&'static str>, Vec<&'static str>); + +pub(super) fn sensitivity_report(d: &DocState, sh: &Sheet, inp: &ReportInput) -> Result { + let m = inp.model; + if let Some(why) = sensitivity_refusal(m, inp.prob) { + return Err(EngineError::Other(why.into())); + } + let n = m.vars.len(); + let x = &inp.solution; + let mut ev = Evaluator { + trial: Trial::new(d), + sheet: m.sheet, + vars: m.vars.clone(), + objective: m.objective, + rows: inp.prob.rows.clone(), + evals: 0, + // Room for the gradients (GRG) or two linearisations (Simplex LP) at the least. + budget: inp.budget.max(3 * n as u64 + 4), + target: None, + }; + let point = ev.eval(x).ok_or_else(out_of_evaluations)?; + // The rows' final values and right sides at the solution. + let mut cells = Vec::new(); + for r in &inp.prob.rows { + cells.push(r.lhs); + cells.extend(r.rhs); + } + let mut trial = Trial::new(d); + let sets: Vec<(usize, CellRef, Value)> = m.vars.iter().zip(x).map(|(c, v)| (m.sheet, *c, Value::number(*v))).collect(); + let reads: Vec<(usize, CellRef)> = cells.iter().map(|c| (m.sheet, *c)).collect(); + let mut vals = trial.run(&sets, &reads).into_iter().map(|v| as_num(&v)); + let finals: Vec<(f64, f64)> = inp + .prob + .rows + .iter() + .map(|r| { + let l = vals.next().unwrap_or(f64::NAN); + (l, if r.rhs.is_some() { vals.next().unwrap_or(f64::NAN) } else { r.rhs_const }) + }) + .collect(); + let at = At { inp, sh, point, finals }; + let (var_rows, con_rows, var_headers, con_headers) = + if m.method == Method::Simplex { simplex_body(&mut ev, &at)? } else { nonlinear_body(&mut ev, &at)? }; + let mut out = Lines::new(); + let r = title(&mut out, ReportKind::Sensitivity, &sh.name); + out.push((r, 0, Value::text("Variable Cells"), true)); + let r = table(&mut out, r + 1, &var_headers, var_rows); + out.push((r, 0, Value::text("Constraints"), true)); + table(&mut out, r + 1, &con_headers, con_rows); + Ok(out) +} + +/// Simplex LP: reduced costs, shadow prices and their ranges from the final tableau. +fn simplex_body(ev: &mut Evaluator, at: &At) -> Result { + let (inp, m) = (at.inp, at.inp.model); + // The program the solve built, from the same start values (data.solver's x0, which Solver + // Results passes back as `original`), so the solve below repeats its pivots. Start values + // the model can't be evaluated at (given only to the report) fall back to the solution. + let start: Vec = inp.original.iter().map(|v| if v.is_finite() { *v } else { 0.0 }).collect(); + let built = match simplex_program(ev, m.goal, &start) { + Err("nonlinear" | "error") if start != inp.solution => simplex_program(ev, m.goal, &inp.solution), + other => other, + }; + let SimplexProgram { cf, c, rows, mut work } = built.map_err(|e| { + if e == "budget" { + out_of_evaluations() + } else { + EngineError::Other("The model isn't linear in the variable cells, so Simplex LP can't report its sensitivity.".into()) + } + })?; + let (outcome, tab) = solve_lp_tableau(&c, &rows, &inp.prob.lo, &inp.prob.hi, &mut work); + let (Outcome::Solved(vertex, best, _), Some(tab)) = (outcome, tab) else { + return Err(EngineError::Other("Solver could not find an optimal basis for the Sensitivity report.".into())); + }; + // The report describes the optimum, so the values it shows must be one. + if !optimal_point(&c, &rows, (&inp.prob.lo, &inp.prob.hi), &inp.solution, best) { + return Err(not_optimal()); + } + // The prices and ranges come from the tableau of `vertex`, so the values shown must be that + // vertex. Another optimum with the same objective (when the optimum is not unique) has other + // ranges, so it is refused too, although it is optimal. + let near = |a: f64, b: f64| (a - b).abs() <= super::PRECISION * (1.0 + a.abs().max(b.abs())); + if vertex.len() != inp.solution.len() || !vertex.iter().zip(&inp.solution).all(|(a, b)| near(*a, *b)) { + return Err(EngineError::Other( + "The Sensitivity report needs the values at the Simplex LP solution: these values are another optimal solution, whose ranges differ. Solve the model with Simplex LP first." + .into(), + )); + } + // Minimising `sign · objective`. + let sign = if m.goal == Goal::Max { -1.0 } else { 1.0 }; + // A shadow price is the dual yᵢ = Σᵣ c_B(r)·B⁻¹(r, i): the row's unit column of the final + // tableau holds B⁻¹'s column i, and c_B(r) is the cost of the column basic in row r (a + // slack or artificial costs nothing). The rounding error of a sum scales with the sum of + // its terms' sizes, so a price below 1E-9 of Σᵣ |c_B(r)·B⁻¹(r, i)| is noise. The bound is + // the row's own: a small price keeps its value beside a large coefficient that plays no + // part in it, and a constant in the objective (no coefficient) changes no bound. Allowable + // changes to a coefficient or a right side are ratios the tableau's own pivot tolerance + // (`EPS`) already bounds. + let cost_size = |b: usize| tab.cols.get(b).map_or(0.0, |mp| cf.get(mp.var).copied().unwrap_or(0.0).abs()); + let price_terms = |col: usize| (0..tab.t.len()).map(|r| tab.basis.get(r).map_or(0.0, |b| cost_size(*b)) * entry(&tab, r, col).abs()).sum::(); + let (shadow, terms): (Vec, Vec) = (0..rows.len()) + .map(|i| { + let col = tab.ident.get(i).copied().unwrap_or(usize::MAX); + (sign * flip(&tab, i) * -tab.obj.get(col).copied().unwrap_or(0.0), price_terms(col)) + }) + .unzip(); + let noise = |terms: f64| 1e-9 * terms.max(f64::MIN_POSITIVE); + let con_rows = ev + .rows + .iter() + .enumerate() + .map(|(i, r)| { + // The basic values move along the row's unit column as its right side changes. + let col = tab.ident.get(i).copied().unwrap_or(usize::MAX); + let dir: Vec<(f64, f64)> = + (0..tab.t.len()).filter(|r| real_basic(&tab, *r)).map(|r| (entry(&tab, r, tab.width), flip(&tab, i) * entry(&tab, r, col))).collect(); + // An artificial still basic after phase one stands for a row the others make + // redundant, and it is zero there. When this right side moves it, any change alone + // leaves no solution, so both ranges are 0. + let pinned = (0..tab.t.len()).any(|r| !real_basic(&tab, r) && entry(&tab, r, col).abs() > EPS); + let (increase, decrease) = + if pinned { (0.0, 0.0) } else { (min_ratio(dir.iter().map(|(v, d)| (*v, -d))), min_ratio(dir.iter().map(|(v, d)| (*v, *d)))) }; + let b = at.finals.get(i).map_or(f64::NAN, |f| f.1); + let mut row = at.row_head(i, r); + let price = sens_num(shadow.get(i).copied().unwrap_or(0.0), noise(terms.get(i).copied().unwrap_or(0.0))); + row.extend([price, num(b), sens_num(increase, EPS), sens_num(decrease, EPS)]); + row + }) + .collect(); + let nonbasic: Vec = (0..tab.first_art).filter(|l| !tab.basis.contains(l)).collect(); + let var_rows = m + .vars + .iter() + .enumerate() + .map(|(j, c)| { + let coef = cf.get(j).copied().unwrap_or(0.0); + let used: f64 = rows.iter().zip(&shadow).map(|((a, _, _), p)| a.get(j).copied().unwrap_or(0.0) * p).sum(); + // The reduced cost cf_j − Σᵢ a_ij·yᵢ is a sum of cf_j and the prices' terms times + // a_ij: the prices' terms rather than the prices, since a price that is a small + // difference of large terms carries their rounding error into every reduced cost + // it is used in. + let used_terms: f64 = rows.iter().zip(&terms).map(|((a, _, _), t)| a.get(j).copied().unwrap_or(0.0).abs() * t).sum(); + // A change Δ in the coefficient changes each nonbasic reduced cost by Δ·e. + let own = |col: usize| tab.cols.get(col).filter(|mp| mp.var == j).map_or(0.0, |mp| mp.sign); + let moves: Vec<(f64, f64)> = nonbasic + .iter() + .map(|&l| { + let through_basis: f64 = (0..tab.t.len()).map(|r| tab.basis.get(r).map_or(0.0, |b| own(*b)) * entry(&tab, r, l)).sum(); + (tab.obj.get(l).copied().unwrap_or(0.0), sign * (own(l) - through_basis)) + }) + .collect(); + let increase = min_ratio(moves.iter().map(|(d, e)| (*d, -e))); + let decrease = min_ratio(moves.iter().map(|(d, e)| (*d, *e))); + let mut row = at.var_head(j, *c); + row.extend([sens_num(coef - used, noise(coef.abs() + used_terms)), num(coef), sens_num(increase, EPS), sens_num(decrease, EPS)]); + row + }) + .collect(); + Ok(( + var_rows, + con_rows, + vec!["Cell", "Name", "Final Value", "Reduced Cost", "Objective Coefficient", "Allowable Increase", "Allowable Decrease"], + vec!["Cell", "Name", "Final Value", "Shadow Price", "Constraint R.H. Side", "Allowable Increase", "Allowable Decrease"], + )) +} + +/// Whether `x` satisfies the LP (rows and bounds) and reaches its optimum `best` (minimising +/// `c·x`), within the constraint precision. +fn optimal_point(c: &[f64], rows: &[LpRow], (lo, hi): (&[f64], &[f64]), x: &[f64], best: f64) -> bool { + let near = |v: f64, size: f64| v <= super::PRECISION * (1.0 + size); + let dot = |a: &[f64]| a.iter().zip(x).fold((0.0, 0.0), |(s, m), (p, q)| (s + p * q, m + (p * q).abs())); + let rows_hold = rows.iter().all(|(a, sense, b)| { + let (lhs, size) = dot(a); + let size = size + b.abs(); + match sense { + Sense::Le => near(lhs - b, size), + Sense::Ge => near(b - lhs, size), + Sense::Eq => near((lhs - b).abs(), size), + } + }); + let bounds_hold = x.iter().enumerate().all(|(j, v)| { + let (l, h) = (lo.get(j).copied().unwrap_or(f64::NEG_INFINITY), hi.get(j).copied().unwrap_or(f64::INFINITY)); + v.is_finite() && near(l - v, v.abs()) && near(v - h, v.abs()) + }); + let (value, size) = dot(c); + // Two-sided: a point just outside a bound can beat the optimum by far more than the + // precision when its costs are large. + rows_hold && bounds_hold && near((value - best).abs(), size + best.abs()) +} + +fn entry(tab: &FinalTableau, r: usize, col: usize) -> f64 { + tab.t.get(r).and_then(|row| row.get(col)).copied().unwrap_or(0.0) +} + +fn real_basic(tab: &FinalTableau, r: usize) -> bool { + tab.basis.get(r).is_some_and(|b| *b < tab.first_art) +} + +/// -1 for a row the tableau negated, else 1. +fn flip(tab: &FinalTableau, i: usize) -> f64 { + if tab.flipped.get(i).copied().unwrap_or(false) { -1.0 } else { 1.0 } +} + +/// Central-difference gradients, inside the bounds, of the objective and of each row's +/// `lhs − rhs` at the solution. +fn gradients(ev: &mut Evaluator, inp: &ReportInput) -> Result<(Vec, Vec>)> { + let x = &inp.solution; + let n = x.len(); + let mut df = vec![0.0; n]; + let mut dg = vec![vec![0.0; n]; ev.rows.len()]; + for j in 0..n { + let xj = x.get(j).copied().unwrap_or(0.0); + let (l, u) = (inp.prob.lo.get(j).copied().unwrap_or(f64::NEG_INFINITY), inp.prob.hi.get(j).copied().unwrap_or(f64::INFINITY)); + let h = 1e-6 * xj.abs().max(1.0); + let (a, b) = ((xj - h).max(l), (xj + h).min(u)); + if b <= a { + continue; + } + let mut point = |v: f64| { + let mut p = x.clone(); + if let Some(e) = p.get_mut(j) { + *e = v; + } + ev.eval(&p).ok_or_else(out_of_evaluations) + }; + let (pa, pb) = (point(a)?, point(b)?); + if let Some(e) = df.get_mut(j) { + *e = (pb.f - pa.f) / (b - a); + } + for (row, (ga, gb)) in dg.iter_mut().zip(pa.g.iter().zip(&pb.g)) { + if let Some(e) = row.get_mut(j) { + *e = (gb - ga) / (b - a); + } + } + } + Ok((df, dg)) +} + +/// The rounding noise in the Lagrange multiplier of row `i`, one of the `active` rows whose +/// multipliers `lambda` solve the normal equations of ∇f = Σ λₖ ∇gₖ over the `free` variables. +/// Row i's equation gives λᵢ = (Σⱼ gᵢⱼ·dfⱼ − Σ_{k≠i} λₖ·Σⱼ gᵢⱼ·gₖⱼ) / Σⱼ gᵢⱼ²; the difference +/// gradients are good to about 1E-6 of each component, and the rounding error of a sum scales +/// with the sum of its terms' sizes, so the noise is 1E-6 of the terms' sizes over the row's +/// own squared norm. The bound is local to the row: another row enters only through its +/// coupling term with this one, so a row whose gradient is orthogonal to the others has a bound +/// from its own gradient alone, and a large component of ∇f that the row's gradient doesn't +/// touch hides nothing. Nearly parallel active gradients make the normal equations +/// ill-conditioned and amplify every multiplier's error beyond any bound local to a row; such +/// multipliers are ill-determined whatever the bound, and they print as computed. +fn multiplier_noise(i: usize, active: &[usize], lambda: &[f64], free: &[usize], (df, dg): (&[f64], &[Vec])) -> f64 { + let grad = |i: usize, j: usize| dg.get(i).and_then(|r| r.get(j)).copied().unwrap_or(0.0); + let own: f64 = free.iter().map(|&j| grad(i, j) * grad(i, j)).sum(); + let objective: f64 = free.iter().map(|&j| (grad(i, j) * df.get(j).copied().unwrap_or(0.0)).abs()).sum(); + let coupling: f64 = active + .iter() + .zip(lambda) + .filter(|(k, _)| **k != i) + .map(|(&k, l)| free.iter().map(|&j| (grad(i, j) * grad(k, j) * l).abs()).sum::()) + .sum(); + 1e-6 * (objective + coupling) / own.max(f64::MIN_POSITIVE) +} + +/// Least squares on the free variables: ∇f = Σ λᵢ ∇gᵢ over the `active` rows. An inequality's +/// multiplier has the sign that tightening it costs (λ ≥ 0 for `lhs ≤ rhs` when maximising); a +/// row whose multiplier has the other sign beyond its own noise ([`multiplier_noise`], the +/// criterion the report rounds it with) isn't binding, so it leaves and the rest are solved +/// again; the objective's value plays no part. Returns each row's multiplier and its noise (0 +/// and 0 for a row that doesn't bind). The work is bounded by `budget` (see +/// [`MULTIPLIER_WORK`]); past it the report is refused. +fn multipliers( + rows: &[Row], + goal: Goal, + mut active: Vec, + free: &[usize], + (df, dg): (&[f64], &[Vec]), + budget: u64, +) -> Result<(Vec, Vec)> { + let grad = |i: usize, j: usize| dg.get(i).and_then(|r| r.get(j)).copied().unwrap_or(0.0); + let goal_sign = if goal == Goal::Max { 1.0 } else { -1.0 }; + let mut lambda = vec![0.0; rows.len()]; + let mut noise = vec![0.0; rows.len()]; + let mut work = 0u64; + while !active.is_empty() { + let (k, f) = (active.len() as u64, (free.len() as u64).max(1)); + work = work.saturating_add(3u64.saturating_mul(k).saturating_mul(k).saturating_mul(f)); + if work > budget { + return Err(EngineError::Other( + "The Sensitivity report of this nonlinear model has too many binding constraints to work out in reasonable time.".into(), + )); + } + let normal: Vec> = + active.iter().map(|&i| active.iter().map(|&k| free.iter().map(|&j| grad(i, j) * grad(k, j)).sum()).collect()).collect(); + let rhs: Vec = active.iter().map(|&i| free.iter().map(|&j| grad(i, j) * df.get(j).copied().unwrap_or(0.0)).sum()).collect(); + let solved = solve_dense(normal, rhs); + let bounds: Vec = active.iter().map(|&i| multiplier_noise(i, &active, &solved, free, (df, dg))).collect(); + let wrong = active + .iter() + .zip(&solved) + .zip(&bounds) + .enumerate() + .filter_map(|(k, ((&i, l), bound))| { + let want = match rows.get(i).map_or(Sense::Eq, |r| r.sense) { + Sense::Le => goal_sign, + Sense::Ge => -goal_sign, + Sense::Eq => return None, + }; + (want * l < -bound).then_some((k, want * l)) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)); + match wrong { + Some((k, _)) => { + active.remove(k); + } + None => { + for ((i, l), bound) in active.iter().zip(solved).zip(bounds) { + if let (Some(e), Some(n)) = (lambda.get_mut(*i), noise.get_mut(*i)) { + *e = l; + *n = bound; + } + } + break; + } + } + } + Ok((lambda, noise)) +} + +/// Whether the solution is a Karush-Kuhn-Tucker point of the model, from the gradients the +/// report computed: every row and bound holds, and each reduced gradient (the objective's +/// gradient less what the binding rows' multipliers explain) is near zero relative to `terms`, +/// the sizes of the terms it is made of, or, for a variable at a bound, points only out of that +/// bound in the objective's direction. A binding row whose multiplier had the wrong sign was +/// dropped by [`multipliers`], so the part of the gradient it would have explained remains in +/// the reduced gradients and the point is refused here. Every tolerance is local to the row or +/// variable it tests: a large right side or gradient component elsewhere in the model excuses +/// nothing here. +fn kkt_point(at: &At, rows: &[Row], terms: &[f64], reduced: &[f64]) -> bool { + let (inp, x) = (at.inp, &at.inp.solution); + // Feasibility: each row within ten times the constraint precision of its own right side. + // The nonlinear method accepts a solution within that of the model's largest constant right + // side, which lets a small row go by its own size; a row over by more than its own + // precision isn't satisfied, whatever the other rows' sizes, so the report refuses it. + let rows_hold = rows.iter().enumerate().all(|(i, r)| { + let (g, b) = (at.point.g.get(i).copied().unwrap_or(f64::NAN), at.finals.get(i).map_or(f64::NAN, |f| f.1)); + let over = match r.sense { + Sense::Le => g, + Sense::Ge => -g, + Sense::Eq => g.abs(), + }; + over <= 10.0 * super::PRECISION * (1.0 + b.abs()) + }); + if !rows_hold || !at.point.f.is_finite() { + return false; + } + // Stationarity: each reduced gradient relative to the terms it is made of (the objective's + // component and the multipliers' parts, at least 1). At optima the nonlinear method solves, + // a reduced gradient is below about 1E-6 of those terms; 1E-3 leaves a wide margin for the + // method's stopping test and for rounding in the difference gradients of badly scaled + // models, and still refuses a point whose objective improves visibly along a direction the + // constraints allow. The bound is the variable's own: with a bound from the gradient's + // largest component, max 1E9·x + y at (1, 0.5) passed, although raising y gains 1 per unit + // against a tolerance of 1E6. + // Moving up a variable improves a maximum by +r and a minimum by −r per unit. + let sign = if inp.model.goal == Goal::Max { 1.0 } else { -1.0 }; + x.iter().enumerate().all(|(j, &v)| { + let (l, h) = (inp.prob.lo.get(j).copied().unwrap_or(f64::NEG_INFINITY), inp.prob.hi.get(j).copied().unwrap_or(f64::INFINITY)); + let near = super::PRECISION * (1.0 + v.abs()); + if !v.is_finite() || v < l - near || v > h + near { + return false; + } + // The same test for "at a bound" as the choice of free variables above. + let edge = 1e-6 * v.abs().max(1.0); + let (at_lo, at_hi) = (v <= l + edge, v >= h - edge); + let gain = reduced.get(j).map_or(f64::NAN, |r| sign * r); + let tol = 1e-3 * terms.get(j).copied().unwrap_or(0.0).max(1.0); + gain.is_finite() && (at_hi || gain <= tol) && (at_lo || gain >= -tol) + }) +} + +/// GRG Nonlinear: reduced gradients and the binding rows' Lagrange multipliers. +fn nonlinear_body(ev: &mut Evaluator, at: &At) -> Result { + let (inp, m) = (at.inp, at.inp.model); + let x = &inp.solution; + let (df, dg) = gradients(ev, inp)?; + // Binding rows (within the nonlinear method's accuracy) and the variables strictly inside + // their bounds. + let active: Vec = ev + .rows + .iter() + .enumerate() + .filter(|(i, r)| { + let (g, b) = (at.point.g.get(*i).copied().unwrap_or(f64::NAN), at.finals.get(*i).map_or(0.0, |f| f.1)); + r.sense == Sense::Eq || g.abs() <= 1e-4 * (1.0 + b.abs()) + }) + .map(|(i, _)| i) + .collect(); + let free: Vec = (0..x.len()) + .filter(|&j| { + let v = x.get(j).copied().unwrap_or(0.0); + let tol = 1e-6 * v.abs().max(1.0); + v > inp.prob.lo.get(j).copied().unwrap_or(f64::NEG_INFINITY) + tol && v < inp.prob.hi.get(j).copied().unwrap_or(f64::INFINITY) - tol + }) + .collect(); + let (lambda, lambda_noise) = multipliers(&ev.rows, m.goal, active, &free, (&df, &dg), MULTIPLIER_WORK)?; + let grad = |i: usize, j: usize| dg.get(i).and_then(|r| r.get(j)).copied().unwrap_or(0.0); + let reduced: Vec = + (0..x.len()).map(|j| df.get(j).copied().unwrap_or(0.0) - lambda.iter().enumerate().map(|(i, l)| l * grad(i, j)).sum::()).collect(); + // A reduced gradient dfⱼ − Σᵢ λᵢ·gᵢⱼ is a sum of the gradient's own component and the + // multipliers' terms; the sizes of those terms bound its rounding error and scale the test + // of whether it is zero. + let terms: Vec = (0..x.len()) + .map(|j| df.get(j).copied().unwrap_or(0.0).abs() + lambda.iter().enumerate().map(|(i, l)| (l * grad(i, j)).abs()).sum::()) + .collect(); + // The report describes the optimum, so the values it shows must be one. + if !kkt_point(at, &ev.rows, &terms, &reduced) { + return Err(not_optimal()); + } + // Difference gradients are good to about 1E-6 of each component, so a reduced gradient's + // noise is 1E-6 of its terms' sizes, plus each multiplier's own noise + // ([`multiplier_noise`]) times |gᵢⱼ|. The bound is the variable's own: a small gradient + // keeps its value beside a large component of another variable. + let reduced_noise = |j: usize| { + let carried: f64 = lambda_noise.iter().enumerate().map(|(i, n)| if grad(i, j) == 0.0 { 0.0 } else { n * grad(i, j).abs() }).sum(); + 1e-6 * terms.get(j).copied().unwrap_or(0.0) + carried + }; + let var_rows = m + .vars + .iter() + .enumerate() + .map(|(j, c)| { + let mut row = at.var_head(j, *c); + row.push(sens_num(reduced.get(j).copied().unwrap_or(f64::NAN), reduced_noise(j))); + row + }) + .collect(); + let con_rows = ev + .rows + .iter() + .enumerate() + .map(|(i, r)| { + let mut row = at.row_head(i, r); + row.push(sens_num(lambda.get(i).copied().unwrap_or(0.0), lambda_noise.get(i).copied().unwrap_or(0.0))); + row + }) + .collect(); + Ok((var_rows, con_rows, vec!["Cell", "Name", "Final Value", "Reduced Gradient"], vec!["Cell", "Name", "Final Value", "Lagrange Multiplier"])) +} + +#[cfg(test)] +mod tests { + use super::{Goal, MULTIPLIER_WORK, Row, Sense, multipliers}; + use gridcraft_core::CellRef; + + #[test] + fn multipliers_at_the_constraint_limit_stop_at_the_work_limit() { + // 1,000 binding `<=` rows over 200 free variables, each multiplier with the wrong sign: + // without a limit every pass would drop one row and solve again, about 4·10⁸ operations + // a pass for up to 1,000 passes. The limit (lowered in tests) refuses it at once. + let (k, f) = (1000usize, 200usize); + let rows: Vec = (0..k).map(|_| Row { lhs: CellRef::new(0, 0), sense: Sense::Le, rhs: None, rhs_const: 0.0 }).collect(); + let dg: Vec> = (0..k).map(|i| (0..f).map(|j| if j == i % f { 1.0 } else { 0.0 }).collect()).collect(); + let df = vec![-1.0; f]; + let free: Vec = (0..f).collect(); + let got = multipliers(&rows, Goal::Max, (0..k).collect(), &free, (&df, &dg), MULTIPLIER_WORK); + assert!(got.is_err()); + // A small model within the limit still gets its multipliers: ∇f = (1, 2) on two + // binding rows with unit gradients. + let dg2 = vec![vec![1.0, 0.0], vec![0.0, 1.0]]; + let (got, noise) = multipliers(&rows[..2], Goal::Max, vec![0, 1], &free[..2], (&[1.0, 2.0], &dg2), MULTIPLIER_WORK).unwrap(); + assert_eq!(got, vec![1.0, 2.0]); + // Each multiplier's noise is 1E-6 of its own row's term (1 · 1 and 1 · 2 over a unit + // norm): the rows are orthogonal, so neither enters the other's bound. + assert_eq!(noise, vec![1e-6, 2e-6]); + } +} diff --git a/crates/engine/src/cmd/solver/tests.rs b/crates/engine/src/cmd/solver/tests.rs index 816f38ceb4..b0f0eb3c9e 100644 --- a/crates/engine/src/cmd/solver/tests.rs +++ b/crates/engine/src/cmd/solver/tests.rs @@ -283,6 +283,8 @@ fn refused_solver_reports_preserve_the_document_and_history() { (true, "simplex", json!(["A1 <= 4"]), json!(["answer"]), "workbook is protected"), (false, "simplex", json!(["A1 <= 4", "A1 int"]), json!(["answer", "limits"]), "integer or binary"), (false, "evolutionary", json!(["A1 <= 4"]), json!(["answer", "limits"]), "Simplex LP and GRG"), + (false, "simplex", json!(["A1 <= 4", "A1 int"]), json!(["answer", "sensitivity"]), "integer or binary"), + (false, "evolutionary", json!(["A1 <= 4"]), json!(["sensitivity"]), "Simplex LP and GRG"), ] { for (keep, save) in [(true, true), (false, true), (true, false), (false, false)] { let mut s = s(); @@ -400,6 +402,823 @@ fn solver_report_insertion_keeps_variable_edit_guards() { } } +/// The numbers from column D on in the row below the one holding `text` on report `name`. +fn report_row(s: &Session, name: &str, text: &str, cols: &[&str]) -> Vec { + let r = row_of(s, name, text) + 1; + cols.iter().map(|c| at(s, name, &format!("{c}{r}")).as_f64().unwrap()).collect() +} + +fn close(got: &[f64], want: &[f64], tol: f64) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol * (1.0 + w.abs())) +} + +#[test] +fn sensitivity_report_gives_the_wyndor_glass_shadow_prices_and_ranges() { + // Hillier & Lieberman's Wyndor Glass sensitivity analysis: shadow prices 0, 1.5 and 1 + // for the three plants; plant 1's hours may fall by 2 and rise without limit, plants 2's + // and 3's by 6 either way; the doors' profit 3 may range over 0..7.5, the windows' 5 over + // 2 and up. + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [[null, "Doors", "Windows", "Used", "Available"], ["Batches", 0, 0, null, null], ["Plant 1", 1, 0, null, 4], ["Plant 2", 0, 2, null, 12], ["Plant 3", 3, 2, null, 18], ["Profit", 3, 5, null, null]]}), + ) + .unwrap(); + for r in 3..=6 { + set(&mut s, &[(&format!("D{r}"), &format!("=SUMPRODUCT(B{r}:C{r},$B$2:$C$2)"))]); + } + let solved = s + .execute( + "data.solver", + json!({"objective": "D6", "variables": "B2:C2", "constraints": ["D3:D5 <= E3:E5"], "method": "simplex", "reports": ["sensitivity"]}), + ) + .unwrap(); + assert_eq!(solved["reports"], json!(["Sensitivity Report 1"]), "{solved}"); + let rep = "Sensitivity Report 1"; + assert_eq!(at(&s, rep, "A1"), Value::text("GridCraft Sensitivity Report")); + let r = row_of(&s, rep, "Reduced Cost"); + assert_eq!(at(&s, rep, &format!("F{}", r + 1)), Value::text("Objective Coefficient")); + let cols = ["D", "E", "F", "G", "H"]; + // Final value, reduced cost, objective coefficient, allowable increase and decrease. + assert!(close(&report_row(&s, rep, "$B$2", &cols)[1..], &[0.0, 3.0, 4.5, 3.0], 1e-9)); + assert!(close(&report_row(&s, rep, "$C$2", &cols), &[6.0, 0.0, 5.0, 1e30, 3.0], 1e-9)); + // Final value, shadow price, right side, allowable increase and decrease. + assert!(close(&report_row(&s, rep, "$D$3", &cols), &[2.0, 0.0, 4.0, 1e30, 2.0], 1e-9)); + assert!(close(&report_row(&s, rep, "$D$4", &cols), &[12.0, 1.5, 12.0, 6.0, 6.0], 1e-9)); + assert!(close(&report_row(&s, rep, "$D$5", &cols), &[18.0, 1.0, 18.0, 6.0, 6.0], 1e-9)); + // A minimisation with `>=` rows: min 2x + 3y, x + y ≥ 4, x + 3y ≥ 6 → (3, 1), cost 9. + // The duals 1.5 and 0.5 solve u + v = 2, u + 3v = 3; the basis holds for 2 ≤ b₁ ≤ 6, + // 4 ≤ b₂ ≤ 12, 1 ≤ c₁ ≤ 3 and 2 ≤ c₂ ≤ 6. + set(&mut s, &[("H1", "0"), ("H2", "0"), ("I1", "=2*H1+3*H2"), ("I2", "=H1+H2"), ("I3", "=H1+3*H2")]); + let r = s + .execute( + "data.solver", + json!({"objective": "I1", "goal": "min", "variables": "H1:H2", "constraints": ["I2 >= 4", "I3 >= 6"], "method": "simplex", "reports": ["sensitivity"]}), + ) + .unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$H$1", &cols), &[3.0, 0.0, 2.0, 1.0, 1.0], 1e-9), "{r}"); + assert!(close(&report_row(&s, &rep, "$H$2", &cols), &[1.0, 0.0, 3.0, 3.0, 1.0], 1e-9)); + assert!(close(&report_row(&s, &rep, "$I$2", &cols), &[4.0, 1.5, 4.0, 2.0, 2.0], 1e-9)); + assert!(close(&report_row(&s, &rep, "$I$3", &cols), &[6.0, 0.5, 6.0, 6.0, 2.0], 1e-9)); + // A variable held at zero has a reduced cost: min 2x + 3y with x + y ≥ 4 alone uses + // only x; y would add 3 − 2 = 1 per unit. + let r = s + .execute( + "data.solver", + json!({"objective": "I1", "goal": "min", "variables": "H1:H2", "constraints": ["I2 >= 4"], "method": "simplex", "reports": ["sensitivity"]}), + ) + .unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$H$2", &cols), &[0.0, 1.0, 3.0, 1e30, 1.0], 1e-9), "{r}"); + // Integer models, the Evolutionary method and Value Of goals have no Sensitivity report. + s.execute("data.solver", json!({"objective": "D6", "variables": "B2:C2", "constraints": ["D3:D5 <= E3:E5"], "method": "simplex"})).unwrap(); + for p in [ + json!({"reports": ["sensitivity"], "constraints": ["D3:D5 <= E3:E5", "B2:C2 int"]}), + json!({"reports": ["sensitivity"], "method": "evolutionary", "constraints": ["D3:D5 <= E3:E5", "B2:C2 <= 10"]}), + json!({"reports": ["sensitivity"], "goal": "value", "value": 30}), + ] { + assert!(s.execute("data.solverReport", p.clone()).is_err(), "{p}"); + } + // data.solver refuses a Value Of goal's Sensitivity report before it changes anything. + set(&mut s, &[("B2", "1"), ("C2", "1")]); + let undo = s.doc().unwrap().undo.len(); + let p = json!({"objective": "D6", "goal": "value", "value": 30, "variables": "B2:C2", "constraints": ["D3:D5 <= E3:E5"], "method": "simplex", "reports": ["sensitivity"]}); + let err = s.execute("data.solver", p).unwrap_err(); + assert!(err.to_string().contains("maximise or minimise"), "{err}"); + assert_eq!((at(&s, "Sheet1", "B2"), at(&s, "Sheet1", "C2")), (Value::number(1.0), Value::number(1.0))); + assert_eq!(s.doc().unwrap().undo.len(), undo); +} + +#[test] +fn simplex_sensitivity_ranges_of_a_redundant_equality_are_zero() { + // max x with x = 2 and 2x = 4: the second row repeats the first, so any change to either + // right side alone has no solution, and both ranges of each row are 0. With x = 2 alone the + // right side may rise without limit and fall by 2 (to x = 0). + let mut s = s(); + set(&mut s, &[("A1", "0"), ("B1", "=A1"), ("C1", "=A1"), ("C2", "=2*A1")]); + let cols = ["D", "F", "G", "H"]; + let r = s + .execute( + "data.solver", + json!({"objective": "B1", "variables": "A1", "constraints": ["C1 = 2", "C2 = 4"], "method": "simplex", "reports": ["sensitivity"]}), + ) + .unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$C$1", &cols), &[2.0, 2.0, 0.0, 0.0], 1e-9), "{:?}", report_row(&s, &rep, "$C$1", &cols)); + assert!(close(&report_row(&s, &rep, "$C$2", &cols), &[4.0, 4.0, 0.0, 0.0], 1e-9), "{:?}", report_row(&s, &rep, "$C$2", &cols)); + // The redundant row doesn't restrict the objective coefficient: x = 2 stays the only + // solution whatever its profit. + assert!(close(&report_row(&s, &rep, "$A$1", &["D", "F", "G", "H"]), &[2.0, 1.0, 1e30, 1e30], 1e-9)); + let r = s + .execute( + "data.solver", + json!({"objective": "B1", "variables": "A1", "constraints": ["C1 = 2"], "method": "simplex", "reports": ["sensitivity"]}), + ) + .unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$C$1", &cols), &[2.0, 2.0, 1e30, 2.0], 1e-9), "{:?}", report_row(&s, &rep, "$C$1", &cols)); +} + +#[test] +fn simplex_sensitivity_report_needs_an_optimal_point() { + // Wyndor Glass: (2, 6) is the optimum (36). (0, 0) is feasible but not optimal; (4, 4.8) + // reaches 36 but breaks plant 3's hours (21.6 > 18). + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [[null, "Doors", "Windows", "Used", "Available"], ["Batches", 0, 0, null, null], ["Plant 1", 1, 0, null, 4], ["Plant 2", 0, 2, null, 12], ["Plant 3", 3, 2, null, 18], ["Profit", 3, 5, null, null]]}), + ) + .unwrap(); + for r in 3..=6 { + set(&mut s, &[(&format!("D{r}"), &format!("=SUMPRODUCT(B{r}:C{r},$B$2:$C$2)"))]); + } + let model = json!({"objective": "D6", "variables": "B2:C2", "constraints": ["D3:D5 <= E3:E5"], "method": "simplex"}); + let report = |b: f64, c: f64| json!({"reports": ["sensitivity"], "model": model, "values": {"B2": b, "C2": c}}); + for (b, c) in [(0.0, 0.0), (4.0, 4.8)] { + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", report(b, c)).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "({b}, {c}): {err}"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &before.wb)); + } + let r = s.execute("data.solverReport", report(2.0, 6.0)).unwrap(); + assert_eq!(r["sheets"], json!(["Sensitivity Report 1"]), "{r}"); +} + +#[test] +fn simplex_sensitivity_report_describes_the_vertex_the_solver_returns() { + // max x + y with x + y <= 4, x <= 3, y <= 3: every point from (3, 1) to (1, 3) is optimal, + // but the ranges belong to one vertex. The vertex Simplex LP returns is reported (from + // several starting values, as Solver Results passes the solve's result on); the other vertex + // and the midpoint are refused. + let model = json!({"objective": "D1", "variables": "A1:A2", "constraints": ["C1 <= 4", "A1 <= 3", "A2 <= 3"], "method": "simplex"}); + let mut found = Vec::new(); + for (x, y) in [("0", "0"), ("0.1", "0.7"), ("2.9", "0.3"), ("1", "1"), ("-5", "12.25")] { + let mut s = s(); + set(&mut s, &[("A1", x), ("A2", y), ("C1", "=A1+A2"), ("D1", "=A1+A2")]); + let mut p = model.clone(); + p["keep"] = json!(false); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": r["model"], "values": r["values"]})).unwrap(); + assert_eq!(rep["sheets"], json!(["Sensitivity Report 1"]), "from ({x}, {y}): {rep}"); + found.push((r["values"]["A1"].as_f64().unwrap(), r["values"]["A2"].as_f64().unwrap())); + } + let (vx, vy) = found[0]; + assert!(found.iter().all(|v| *v == (vx, vy)), "{found:?}"); + let other = if vx == 3.0 { (1.0, 3.0) } else { (3.0, 1.0) }; + assert!([(3.0, 1.0), (1.0, 3.0)].contains(&(vx, vy)), "{found:?}"); + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("C1", "=A1+A2"), ("D1", "=A1+A2")]); + for (x, y) in [other, (2.0, 2.0)] { + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": x, "A2": y}})).unwrap_err(); + assert!(err.to_string().contains("another optimal solution"), "({x}, {y}): {err}"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &before.wb)); + // data.solver's Skip mode (as Solver Results passes) skips only the Sensitivity report. + let r = s + .execute( + "data.solverReport", + json!({"reports": ["answer", "sensitivity"], "model": model, "values": {"A1": x, "A2": y}, "skipNotOptimal": true}), + ) + .unwrap(); + assert_eq!(r["skippedReports"][0]["report"], "sensitivity", "{r}"); + assert_eq!(r["sheets"].as_array().map(Vec::len), Some(1), "{r}"); + } + let r = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": vx, "A2": vy}})).unwrap(); + assert!(r["sheets"][0].as_str().unwrap().starts_with("Sensitivity Report"), "{r}"); +} + +#[test] +fn simplex_sensitivity_report_repeats_the_solve_from_its_start_values() { + // max 0.1x + 0.1y with 0.1x + 0.1y <= 0.4, 0.7x + 0.7y <= 2.8, x <= 3, y <= 3: the optimum is + // not unique, and the difference coefficients of these formulas differ in their last bits + // with the point they are taken at. From these starts the solve returns (3, 1) or (1, 3); + // linearised at that solution instead, the report's solve broke the tie the other way and + // refused the solve's own values. Built from the same start values, the program is the + // same to the bit, so each solve's own report is written. + let model = + json!({"objective": "D1", "variables": "A1:A2", "constraints": ["C1 <= 0.4", "E1 <= 2.8", "A1 <= 3", "A2 <= 3"], "method": "simplex"}); + let formulas = [("C1", "=A1*0.1+A2*0.1"), ("D1", "=A1*0.1+A2*0.1"), ("E1", "=A1*0.7+A2*0.7")]; + let program = |s: &Session, x: &[f64]| { + let m = super::parse_model(s, &model).unwrap(); + let prob = super::build_problem(&m); + let mut ev = super::Evaluator { + trial: super::Trial::new(s.doc().unwrap()), + sheet: m.sheet, + vars: m.vars.clone(), + objective: m.objective, + rows: prob.rows.clone(), + evals: 0, + budget: 100, + target: None, + }; + let p = super::lp::simplex_program(&mut ev, m.goal, x).unwrap(); + let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::>(); + let rows: Vec<(Vec, u64)> = p.rows.iter().map(|(a, _, b)| (bits(a), b.to_bits())).collect(); + (bits(&p.cf), bits(&p.c), rows, p.work) + }; + let mut vertices = Vec::new(); + for (x, y) in [("-3", "-5"), ("-3", "2.42"), ("-3", "6.13"), ("-3", "9.84"), ("-3", "13.55"), ("0.37", "0.3"), ("2.55", "-1.2")] { + let mut s = s(); + set(&mut s, &[("A1", x), ("A2", y)]); + set(&mut s, &formulas); + let start: Vec = [x, y].iter().map(|v| v.parse().unwrap()).collect(); + let before = program(&s, &start); + let r = s.execute("data.solver", model.clone()).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + // The program the report builds after the solve (cells now at the solution) from the + // solve's `original`, as Solver Results passes it, equals the solve's. + let original: Vec = ["A1", "A2"].iter().map(|c| r["original"][c].as_f64().unwrap()).collect(); + assert_eq!(original, start); + assert_eq!(program(&s, &original), before, "from ({x}, {y})"); + let rep = s + .execute("data.solverReport", json!({"reports": ["sensitivity"], "model": r["model"], "values": r["values"], "original": r["original"]})) + .unwrap(); + assert_eq!(rep["sheets"], json!(["Sensitivity Report 1"]), "from ({x}, {y}): {rep}"); + let v = (r["values"]["A1"].as_f64().unwrap(), r["values"]["A2"].as_f64().unwrap()); + vertices.push(if v.0 > v.1 { "(3, 1)" } else { "(1, 3)" }); + } + // Both vertices occur, so the starts exercise the tie. + assert!(vertices.contains(&"(3, 1)") && vertices.contains(&"(1, 3)"), "{vertices:?}"); +} + +#[test] +fn simplex_sensitivity_report_refuses_a_point_that_beats_the_optimum() { + // min 1E+9·A1 with A1 ≥ 0: the optimum is 0. A1 = -1E-7 is outside the bound by less than + // the precision, yet its objective is -100, far from the optimum. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("B1", "=1E+9*A1")]); + let model = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 5"], "method": "simplex"}); + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": -1e-7}})).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "{err}"); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().wb, &before.wb)); + let r = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": 0}})).unwrap(); + assert_eq!(r["sheets"], json!(["Sensitivity Report 1"]), "{r}"); +} + +#[test] +fn sensitivity_report_of_a_nonlinear_model_gives_lagrange_multipliers() { + // The largest rectangle with perimeter at most 20: the area (P/4)² grows by P/8 = 2.5 per + // unit of perimeter, and both reduced gradients are 0. + let mut s = s(); + set(&mut s, &[("A1", "1"), ("A2", "1"), ("B1", "=A1*A2"), ("B2", "=2*A1+2*A2")]); + let r = + s.execute("data.solver", json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 20"], "reports": ["sensitivity"]})).unwrap(); + let rep = "Sensitivity Report 1"; + assert_eq!(r["reports"], json!([rep]), "{r}"); + assert_eq!(at(&s, rep, &format!("E{}", row_of(&s, rep, "$A$1"))), Value::text("Reduced Gradient")); + assert!(close(&report_row(&s, rep, "$A$1", &["D", "E"]), &[5.0, 0.0], 1e-4)); + assert!(close(&report_row(&s, rep, "$B$2", &["D", "E"]), &[20.0, 2.5], 1e-4)); + // min (x + 1)² + (y − 2)² with x + y ≤ 1 and x, y ≥ 0: (0, 1). The constraint's + // multiplier is −2; x sits at its bound, where raising it costs 2(x + 1) + 2 = 4. + set(&mut s, &[("C1", "0.5"), ("C2", "0.5"), ("D1", "=(C1+1)^2+(C2-2)^2"), ("D2", "=C1+C2")]); + let r = s + .execute( + "data.solver", + json!({"objective": "D1", "goal": "min", "variables": "C1:C2", "constraints": ["D2 <= 1"], "reports": ["sensitivity"]}), + ) + .unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$C$1", &["D", "E"]), &[0.0, 4.0], 1e-4), "{r}"); + assert!(close(&report_row(&s, &rep, "$C$2", &["D", "E"]), &[1.0, 0.0], 1e-4)); + assert!(close(&report_row(&s, &rep, "$D$2", &["D", "E"]), &[1.0, -2.0], 1e-4)); +} + +#[test] +fn nonlinear_sensitivity_report_needs_an_optimal_point() { + let mut s = s(); + set(&mut s, &[("A1", "1"), ("B1", "=A1^2")]); + set(&mut s, &[("C1", "0"), ("D1", "=(C1-2)^2")]); + set(&mut s, &[("E1", "1"), ("E2", "1"), ("F1", "=E1*E2"), ("F2", "=2*E1+2*E2")]); + set(&mut s, &[("G1", "0"), ("G2", "1"), ("H1", "=(G1+1)^2+(G2-2)^2"), ("H2", "=G1+G2")]); + let square = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 5"]}); + let shifted = json!({"objective": "D1", "goal": "min", "variables": "C1", "constraints": ["C1 <= 5"]}); + let rectangle = json!({"objective": "F1", "variables": "E1:E2", "constraints": ["F2 <= 20"]}); + let bounded = json!({"objective": "H1", "goal": "min", "variables": "G1:G2", "constraints": ["H2 <= 1"]}); + let report = |model: &serde_json::Value, values: serde_json::Value| json!({"reports": ["sensitivity"], "model": model, "values": values}); + for (model, values, why) in [ + // min A1² at A1 = 1: the free variable's reduced gradient is 2, not 0. + (&square, json!({"A1": 1}), "free gradient"), + // The rectangle at 6 × 6 has a larger area than the optimum but a perimeter of 24 > 20. + (&rectangle, json!({"E1": 6, "E2": 6}), "infeasible"), + // At 4 × 6 the perimeter binds, but its multiplier can't explain the gradient (6, 4). + (&rectangle, json!({"E1": 4, "E2": 6}), "unexplained gradient"), + // min (C1 − 2)² at the bound C1 = 0: raising C1 lowers the objective. + (&shifted, json!({"C1": 0}), "wrong-way bound"), + // (1, 0) in the bounded model: the binding row's multiplier would be +4, the wrong sign + // for a `<=` row when minimising, so the row is dropped and the gradient is unexplained. + (&bounded, json!({"G1": 1, "G2": 0}), "wrong-sign multiplier"), + ] { + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", report(model, values)).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "{why}: {err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb), "{why}"); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len()), "{why}"); + } + // The optima are still reported. + for (k, (model, values)) in + [(&square, json!({"A1": 0})), (&shifted, json!({"C1": 2})), (&rectangle, json!({"E1": 5, "E2": 5})), (&bounded, json!({"G1": 0, "G2": 1}))] + .into_iter() + .enumerate() + { + let r = s.execute("data.solverReport", report(model, values)).unwrap(); + assert_eq!(r["sheets"], json!([format!("Sensitivity Report {}", k + 1)]), "{r}"); + } +} + +#[test] +fn solver_writes_the_other_reports_when_the_run_stops_before_an_optimum() { + // Rosenbrock's function from (-1.2, 1) with 60 evaluations: the run stops at the limit with + // a solution that is not the optimum (1, 1). The solve applies and the Answer report is + // written; the Sensitivity report is left out with its reason. + let mut s = s(); + set(&mut s, &[("A1", "-1.2"), ("A2", "1"), ("B1", "=(1-A1)^2+100*(A2-A1^2)^2")]); + let undo = s.doc().unwrap().undo.len(); + let r = s + .execute( + "data.solver", + json!({"objective": "B1", "goal": "min", "variables": "A1:A2", "nonNegative": false, "maxEvaluations": 60, "reports": ["answer", "sensitivity"]}), + ) + .unwrap(); + assert_eq!(r["status"], "iterationLimit", "{r}"); + assert_eq!(r["changed"], true); + assert_eq!(n(&s, "A1"), r["values"]["A1"].as_f64().unwrap()); + assert_eq!(r["reports"], json!(["Answer Report 1"]), "{r}"); + assert_eq!(r["skippedReports"][0]["report"], "sensitivity", "{r}"); + assert!(r["skippedReports"][0]["reason"].as_str().unwrap().contains("optimal"), "{r}"); + assert_eq!(s.doc().unwrap().undo.len(), undo + 1); + // A solve that reaches the optimum still writes the Sensitivity report and skips nothing. + let r = s + .execute("data.solver", json!({"objective": "B1", "goal": "min", "variables": "A1:A2", "nonNegative": false, "reports": ["sensitivity"]})) + .unwrap(); + assert_eq!(r["status"], "converged", "{r}"); + assert_eq!(r["reports"], json!(["Sensitivity Report 1"]), "{r}"); + assert!(r.get("skippedReports").is_none(), "{r}"); +} + +#[test] +fn solver_report_can_skip_a_sensitivity_report_the_values_do_not_support() { + // min A1² at A1 = 1 is not an optimum. Called directly, data.solverReport refuses it; with + // skipNotOptimal (as Solver Results passes) the Answer report is still written. + let mut s = s(); + set(&mut s, &[("A1", "1"), ("B1", "=A1^2")]); + let model = json!({"objective": "B1", "goal": "min", "variables": "A1", "constraints": ["A1 <= 5"]}); + let p = |reports: serde_json::Value, skip: bool| json!({"reports": reports, "model": model, "values": {"A1": 1}, "skipNotOptimal": skip}); + let err = s.execute("data.solverReport", p(json!(["answer", "sensitivity"]), false)).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "{err}"); + let undo = s.doc().unwrap().undo.len(); + let r = s.execute("data.solverReport", p(json!(["answer", "sensitivity"]), true)).unwrap(); + assert_eq!(r["sheets"], json!(["Answer Report 1"]), "{r}"); + assert!(r["skippedReports"][0]["reason"].as_str().unwrap().contains("not optimal"), "{r}"); + assert_eq!(s.doc().unwrap().undo.len(), undo + 1); + // With nothing left to write, nothing changes and no Undo step is added. + let before = s.doc().unwrap().clone(); + let r = s.execute("data.solverReport", p(json!(["sensitivity"]), true)).unwrap(); + assert_eq!(r["sheets"], json!([]), "{r}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); + // A model with no Sensitivity report is still refused, skipNotOptimal or not. + let err = s.execute("data.solverReport", json!({"reports": ["answer", "sensitivity"], "model": {"objective": "B1", "variables": "A1", "constraints": ["A1 <= 5", "A1 int"]}, "skipNotOptimal": true})).unwrap_err(); + assert!(err.to_string().contains("integer or binary"), "{err}"); + // In a workbook whose structure is protected, a request whose only report is skipped + // writes no sheet, so it succeeds; one that would write a sheet is still refused. + let d = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut d.wb).protected_structure = true; + let before = s.doc().unwrap().clone(); + let r = s.execute("data.solverReport", p(json!(["sensitivity"]), true)).unwrap(); + assert_eq!(r["sheets"], json!([]), "{r}"); + assert!(r["skippedReports"][0]["reason"].as_str().unwrap().contains("not optimal"), "{r}"); + let err = s.execute("data.solverReport", p(json!(["answer", "sensitivity"]), true)).unwrap_err(); + assert!(err.to_string().contains("protected"), "{err}"); + // A request that must write a sheet is refused before its reports are built, so an + // integer model's Limits report gives the protection message, not the report's own refusal. + let int_model = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 5", "A1 int"]}); + let err = s.execute("data.solverReport", json!({"reports": ["limits"], "model": int_model, "values": {"A1": 1}})).unwrap_err(); + assert!(err.to_string().contains("protected"), "{err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); +} + +#[test] +fn a_sensitivity_refusal_of_the_model_comes_before_any_report_is_built() { + // The refusals that apply to the model (integer or binary constraints, the Evolutionary + // method, a Value Of goal) are checked before any report is built, in both modes and from + // both commands: a Limits report listed first would otherwise run its two optimisations per + // variable, and data.solver its whole solve, for an error. An integer model asking for + // limits and sensitivity gets the Sensitivity refusal, not the Limits report's, which the + // report loop reached first; a Value Of model, whose Limits report is not refused, gets the + // Sensitivity refusal with no sheet written and the workbook as it was. + let mut s = s(); + set(&mut s, &[("A1", "1"), ("B1", "=2*A1")]); + let before = s.doc().unwrap().clone(); + let int_model = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 5", "A1 int"]}); + let value_model = json!({"objective": "B1", "goal": "value", "value": 4, "variables": "A1", "constraints": ["A1 <= 5"]}); + for (model, values, why) in + [(&int_model, json!({"A1": 1}), "The Sensitivity report doesn't apply"), (&value_model, json!({"A1": 2}), "maximise or minimise")] + { + for skip in [false, true] { + let p = json!({"reports": ["limits", "sensitivity"], "model": model, "values": values, "skipNotOptimal": skip}); + let err = s.execute("data.solverReport", p).unwrap_err(); + assert!(err.to_string().contains(why), "{skip}: {err}"); + } + } + let p = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 5", "A1 int"], "method": "simplex", "reports": ["limits", "sensitivity"]}); + let err = s.execute("data.solver", p).unwrap_err(); + assert!(err.to_string().contains("The Sensitivity report doesn't apply"), "{err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); +} + +#[test] +fn nonlinear_sensitivity_with_too_many_binding_constraints_is_refused_without_change() { + // 80 binding rows on two free variables pass the work limit (lowered in tests); 40 don't. + let mut s = s(); + set(&mut s, &[("A1", "5"), ("A2", "5"), ("B1", "=A1*A2")]); + for r in 1..=80 { + set(&mut s, &[(&format!("D{r}"), "=A1+A2")]); + } + let report = |rows: u32| json!({"reports": ["sensitivity"], "model": {"objective": "B1", "variables": "A1:A2", "constraints": [format!("D1:D{rows} <= 10")]}}); + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", report(80)).unwrap_err(); + assert!(err.to_string().contains("too many binding constraints"), "{err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); + let r = s.execute("data.solverReport", report(40)).unwrap(); + assert_eq!(r["sheets"], json!(["Sensitivity Report 1"]), "{r}"); +} + +#[test] +fn sensitivity_applies_agrees_with_the_report() { + let mut s = s(); + set(&mut s, &[("A1", "1"), ("B1", "=3*A1")]); + for (extra, ok) in [ + (json!({}), true), + (json!({"goal": "min"}), true), + (json!({"method": "grg"}), true), + (json!({"goal": "value", "value": 3}), false), + (json!({"constraints": ["A1 <= 4", "A1 int"]}), false), + (json!({"constraints": ["A1 <= 4", {"lhs": "A1", "op": "bin"}]}), false), + (json!({"method": "evolutionary"}), false), + ] { + let mut p = json!({"objective": "B1", "variables": "A1", "constraints": ["A1 <= 4"], "method": "simplex", "keep": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + assert_eq!(super::sensitivity_applies(&p), ok, "{p}"); + let r = s.execute("data.solver", p.clone()).unwrap(); + assert_eq!(super::sensitivity_applies(&r["model"]), ok, "{p}"); + let rep = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": r["model"], "values": r["values"]})); + assert_eq!(rep.is_ok(), ok, "{p}: {rep:?}"); + } +} + +/// How many cells of sheet `name` hold `text`. +fn count_of(s: &Session, name: &str, text: &str) -> usize { + let d = s.doc().unwrap(); + let sh = d.wb.sheet(d.wb.sheet_index(name).unwrap()).unwrap(); + (0..60).flat_map(|r| (0..8).map(move |c| (r, c))).filter(|(r, c)| sh.value(CellRef::new(*r, *c)) == Value::text(text)).count() +} + +#[test] +fn sensitivity_report_is_the_same_whatever_constant_the_objective_adds() { + // A constant in the objective changes no price: max 1E9 + x with x ≤ 10 (a row) has the + // same report as max x with x ≤ 10. At x = 10 the row's shadow price is 1 (one more unit + // of right side adds one to the objective); x is basic, with reduced cost 0 and + // coefficient 1, which may rise without limit and fall by 1 (to 0, where the slack ties); + // the right side 10 may rise without limit and fall by 10 (to x = 0). A tolerance taken + // from the objective's value (1E-9 · 1E9 = 1) wrote the shadow price as 0. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("B1", "=1000000000+A1"), ("C1", "=A1"), ("E1", "0"), ("F1", "=E1"), ("G1", "=E1")]); + let cols = ["D", "E", "F", "G", "H"]; + let mut rows = Vec::new(); + for (obj, var, con, v, c) in [("B1", "A1", "C1", "$A$1", "$C$1"), ("F1", "E1", "G1", "$E$1", "$G$1")] { + let p = json!({"objective": obj, "variables": var, "constraints": [format!("{con} <= 10")], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + rows.push((report_row(&s, &rep, v, &cols), report_row(&s, &rep, c, &cols))); + } + assert!(close(&rows[0].0, &[10.0, 0.0, 1.0, 1e30, 1.0], 1e-9), "{rows:?}"); + assert!(close(&rows[0].1, &[10.0, 1.0, 10.0, 1e30, 10.0], 1e-9), "{rows:?}"); + assert_eq!(rows[0], rows[1]); +} + +#[test] +fn nonlinear_sensitivity_report_is_the_same_whatever_constant_the_objective_adds() { + // min 1E6 + (x − 3)² with x ≤ 2.75 has the same report as min (x − 3)² with x ≤ 2.75. At + // x = 2.75 the objective's gradient is 2(2.75 − 3) = −0.5. As a bound on the variable cell + // (no constraint row) it is x's reduced gradient, −0.5; as a row y = x ≤ 2.75 it is the + // row's Lagrange multiplier, −0.5 (∇f = λ∇y with ∇y = 1), and x's reduced gradient is 0. + // A tolerance taken from the objective's value (1E-6 · 1E6 = 1) wrote both as 0. The + // difference gradients of the model with the constant lose about four digits to rounding, + // so the figures agree to 1E-3. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("B1", "=1000000+(A1-3)^2"), ("C1", "=A1"), ("E1", "0"), ("F1", "=(E1-3)^2"), ("G1", "=E1")]); + let mut figures = Vec::new(); + for (obj, var, con, v, c) in [("B1", "A1", "C1", "$A$1", "$C$1"), ("F1", "E1", "G1", "$E$1", "$G$1")] { + let solve = |s: &mut Session, bound: String| { + let p = json!({"objective": obj, "goal": "min", "variables": var, "constraints": [bound], "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "converged", "{r}"); + r["reports"][0].as_str().unwrap().to_string() + }; + let rep = solve(&mut s, format!("{var} <= 2.75")); + let at_bound = report_row(&s, &rep, v, &["D", "E"]); + assert_eq!(count_of(&s, &rep, c), 0, "a bound has no constraint row"); + let rep = solve(&mut s, format!("{con} <= 2.75")); + figures.push((at_bound, report_row(&s, &rep, v, &["D", "E"]), report_row(&s, &rep, c, &["D", "E"]))); + } + let (at_bound, free, row) = &figures[0]; + assert!(close(at_bound, &[2.75, -0.5], 1e-3), "{figures:?}"); + assert!(close(free, &[2.75, 0.0], 1e-3), "{figures:?}"); + assert!(close(row, &[2.75, -0.5], 1e-3), "{figures:?}"); + assert!(close(&figures[1].0, at_bound, 1e-3) && close(&figures[1].1, free, 1e-3) && close(&figures[1].2, row, 1e-3), "{figures:?}"); +} + +#[test] +fn simplex_sensitivity_keeps_a_small_price_beside_a_large_coefficient() { + // max 1E9·x + y with x ≤ 1 and y ≤ 1 as rows and x, y ≥ 0: (1, 1). Both rows bind, the + // basis is {x, y} with B = I, so the shadow prices are the coefficients, 1E9 and 1, and both + // reduced costs are 0. x's coefficient may rise without limit and fall by 1E9 (to 0, where + // its row's slack ties), y's without limit and by 1. Each right side may rise without limit + // (the other row doesn't involve the variable) and fall by 1 (to 0). The second row's price + // is the single term 1 · 1, so the first row's coefficient 1E9 is no rounding error in it; a + // noise level taken from the largest coefficient (1E-9 · 1E9 = 1) wrote it as 0. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=1000000000*A1+A2"), ("C1", "=A1"), ("C2", "=A2")]); + let p = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["C1 <= 1", "C2 <= 1"], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + let cols = ["D", "E", "F", "G", "H"]; + let row = |c: &str| report_row(&s, &rep, c, &cols); + assert!(close(&row("$A$1"), &[1.0, 0.0, 1e9, 1e30, 1e9], 1e-9), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[1.0, 0.0, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$A$2")); + assert!(close(&row("$C$1"), &[1.0, 1e9, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$C$1")); + assert!(close(&row("$C$2"), &[1.0, 1.0, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$C$2")); +} + +#[test] +fn simplex_sensitivity_keeps_a_small_reduced_cost_beside_a_large_coefficient() { + // max 1E9·x + y − z with x ≤ 1 and y ≤ 1 as rows and x, y, z ≥ 0 (z's bound is the only + // constraint on it): (1, 1, 0). z is nonbasic at zero with reduced cost −1 − 0 = −1 (no + // row involves it): its coefficient must rise by 1 before z is made, so the Allowable + // Increase is 1 and the Allowable Decrease 1E+30, as for a maximum's variable at zero in + // `simplex_sensitivity_gives_the_dakota_furniture_report`. The other rows are those of + // `simplex_sensitivity_keeps_a_small_price_beside_a_large_coefficient`. The reduced cost + // is the coefficient alone, so x's coefficient 1E9 is no rounding error in it; a noise + // level taken from the largest coefficient wrote it as 0. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("A3", "0"), ("B1", "=1000000000*A1+A2-A3"), ("C1", "=A1"), ("C2", "=A2")]); + let p = json!({"objective": "B1", "variables": "A1:A3", "constraints": ["C1 <= 1", "C2 <= 1"], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + let cols = ["D", "E", "F", "G", "H"]; + let row = |c: &str| report_row(&s, &rep, c, &cols); + assert!(close(&row("$A$1"), &[1.0, 0.0, 1e9, 1e30, 1e9], 1e-9), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[1.0, 0.0, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$A$2")); + assert!(close(&row("$A$3"), &[0.0, -1.0, -1.0, 1.0, 1e30], 1e-9), "{:?}", row("$A$3")); + assert!(close(&row("$C$1"), &[1.0, 1e9, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$C$1")); + assert!(close(&row("$C$2"), &[1.0, 1.0, 1.0, 1e30, 1.0], 1e-9), "{:?}", row("$C$2")); +} + +#[test] +fn nonlinear_sensitivity_keeps_a_small_multiplier_beside_a_large_gradient() { + // The model of `simplex_sensitivity_keeps_a_small_price_beside_a_large_coefficient` under + // GRG Nonlinear: at (1, 1) both rows bind; with ∇f = (1E9, 1) and unit row gradients the + // Lagrange multipliers are 1E9 and 1, and both reduced gradients are 0. The second row's + // multiplier is the single term 1 · 1, so the gradient's large first component is no + // rounding error in it; a noise level taken from the gradient's size (1E-6 · 1E9 = 1000) + // wrote it as 0. The difference gradient of y is the difference of two values near 1E9, + // where the last place is 2⁻²² ≈ 2.4E-7: the step 1E-6 rounds to 4 places, 9.54E-7, so + // df_y ≈ 0.954 and the multiplier is checked to 0.1. The nonlinear method stops on this + // model from (0, 0) with "unbounded", so the report is asked for at the optimum (1, 1). + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=1000000000*A1+A2"), ("C1", "=A1"), ("C2", "=A2")]); + let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["C1 <= 1", "C2 <= 1"]}); + let r = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": 1, "A2": 1}})).unwrap(); + let rep = r["sheets"][0].as_str().unwrap().to_string(); + let row = |c: &str| report_row(&s, &rep, c, &["D", "E"]); + assert!(close(&row("$A$1"), &[1.0, 0.0], 1e-3), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[1.0, 0.0], 1e-3), "{:?}", row("$A$2")); + assert!(close(&row("$C$1"), &[1.0, 1e9], 1e-3), "{:?}", row("$C$1")); + assert!(close(&row("$C$2"), &[1.0, 1.0], 0.1), "{:?}", row("$C$2")); +} + +#[test] +fn nonlinear_sensitivity_keeps_a_small_reduced_gradient_beside_a_large_gradient() { + // The model of `simplex_sensitivity_keeps_a_small_reduced_cost_beside_a_large_coefficient` + // under GRG Nonlinear: z sits at its bound 0, where its reduced gradient is its own + // gradient −1 (no row involves it); a noise level taken from the gradient's size (1000) + // wrote it as 0. Its difference gradient is one-sided at the bound, over the step 1E-6 + // from a value near 1E9 that rounds as in + // `nonlinear_sensitivity_keeps_a_small_multiplier_beside_a_large_gradient`: about −0.954, + // checked to 0.1. As there, the report is asked for at the optimum (1, 1, 0). + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("A3", "0"), ("B1", "=1000000000*A1+A2-A3"), ("C1", "=A1"), ("C2", "=A2")]); + let model = json!({"objective": "B1", "variables": "A1:A3", "constraints": ["C1 <= 1", "C2 <= 1"]}); + let r = s.execute("data.solverReport", json!({"reports": ["sensitivity"], "model": model, "values": {"A1": 1, "A2": 1, "A3": 0}})).unwrap(); + let rep = r["sheets"][0].as_str().unwrap().to_string(); + let row = |c: &str| report_row(&s, &rep, c, &["D", "E"]); + assert!(close(&row("$A$1"), &[1.0, 0.0], 1e-3), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[1.0, 0.0], 1e-3), "{:?}", row("$A$2")); + assert!(close(&row("$A$3"), &[0.0, -1.0], 0.1), "{:?}", row("$A$3")); + assert!(close(&row("$C$1"), &[1.0, 1e9], 1e-3), "{:?}", row("$C$1")); + assert!(close(&row("$C$2"), &[1.0, 1.0], 0.1), "{:?}", row("$C$2")); +} + +#[test] +fn nonlinear_sensitivity_refuses_a_point_that_is_not_optimal_in_a_small_variable() { + // max 1E9·x + y with x ≤ 1 and y ≤ 1 as rows, at (1, 0.5): the second row doesn't bind, y + // is free and its reduced gradient is its own gradient, about 1 (0.954 with the rounding + // in `nonlinear_sensitivity_keeps_a_small_multiplier_beside_a_large_gradient`), so raising + // y to 1 gains 0.5 and the point is not optimal: the report is refused and the workbook + // left as it was. A stationarity tolerance taken from the largest gradient component + // (1E-3 · 1E9 = 1E6) accepted the point and wrote the report. The optimum (1, 1) is + // reported. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=1000000000*A1+A2"), ("C1", "=A1"), ("C2", "=A2")]); + let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["C1 <= 1", "C2 <= 1"]}); + let report = |values: serde_json::Value| json!({"reports": ["sensitivity"], "model": model, "values": values}); + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", report(json!({"A1": 1, "A2": 0.5}))).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "{err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); + let r = s.execute("data.solverReport", report(json!({"A1": 1, "A2": 1}))).unwrap(); + assert_eq!(r["sheets"], json!(["Sensitivity Report 1"]), "{r}"); +} + +#[test] +fn nonlinear_sensitivity_refuses_a_point_that_breaks_a_small_row_beside_a_large_one() { + // max y − (x − 2)² with x ≤ 1E9 and y ≤ 1 as rows: (2, 1). At (2, 1.0001) the second row + // is over by 1E-4, more than ten times the constraint precision of its own right side + // (1E-5 · (1 + 1) = 2E-5), so the point is infeasible and the report is refused; it is + // stationary (x's gradient is 0 and the row, within the binding tolerance, explains y's), + // so feasibility alone decides. A feasibility tolerance relative to the largest constant + // right side (1E-5 · 1E9 = 1E4) accepted the point. The optimum (2, 1) is reported. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=A2-(A1-2)^2"), ("C1", "=A1"), ("C2", "=A2")]); + let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["C1 <= 1000000000", "C2 <= 1"]}); + let report = |values: serde_json::Value| json!({"reports": ["sensitivity"], "model": model, "values": values}); + let before = s.doc().unwrap().clone(); + let err = s.execute("data.solverReport", report(json!({"A1": 2, "A2": 1.0001}))).unwrap_err(); + assert!(err.to_string().contains("not optimal"), "{err}"); + let d = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&d.wb, &before.wb)); + assert_eq!((d.undo.len(), d.redo.len()), (before.undo.len(), before.redo.len())); + let r = s.execute("data.solverReport", report(json!({"A1": 2, "A2": 1}))).unwrap(); + assert_eq!(r["sheets"], json!(["Sensitivity Report 1"]), "{r}"); + assert!(close(&report_row(&s, "Sensitivity Report 1", "$C$2", &["D", "E"]), &[1.0, 1.0], 1e-3), "{r}"); +} + +#[test] +fn simplex_sensitivity_of_a_variable_at_its_upper_bound() { + // max 3x + 2y with x + y ≤ 4 (a row), x ≤ 3 and y ≤ 5 (bounds on the variable cells, which + // have no row in the Constraints table): x = 3, y = 1, objective 11. The row's shadow price + // is y's coefficient 2 (y is basic in it). x, held at its upper bound, has reduced cost + // 3 − 1·2 = 1: one more unit of its bound adds 1. This is the convention of Frontline's + // "Excel Solver - Interpreting the Sensitivity Report" (solver.com): a variable's dual + // value is nonzero only at a bound, measures the objective's change per unit increase in + // the variable, and a bound on a variable cell has no row in the Constraints section, its + // reduced cost standing for the bound's shadow price. Its coefficient may rise without limit + // and fall by 1 (to 2, a tie with y): for a maximum's variable at its upper bound the + // Allowable Increase is 1E+30 and the Allowable Decrease the reduced cost, the mirror + // image of a variable at zero (`simplex_sensitivity_gives_the_dakota_furniture_report`). + // y's coefficient may rise by 1 (to 3, a tie with x) and fall by 2 (to 0, where the row's + // slack ties). The right side 4 may rise by 4 (y reaches its bound 5 at 8) and fall by 1 + // (y reaches 0 at 3). + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=3*A1+2*A2"), ("C1", "=A1+A2")]); + let p = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["C1 <= 4", "A1 <= 3", "A2 <= 5"], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + let cols = ["D", "E", "F", "G", "H"]; + let row = |c: &str| report_row(&s, &rep, c, &cols); + assert!(close(&row("$A$1"), &[3.0, 1.0, 3.0, 1e30, 1.0], 1e-9), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[1.0, 0.0, 2.0, 1.0, 2.0], 1e-9), "{:?}", row("$A$2")); + assert!(close(&row("$C$1"), &[4.0, 2.0, 4.0, 4.0, 1.0], 1e-9), "{:?}", row("$C$1")); + assert_eq!((count_of(&s, &rep, "$A$1"), count_of(&s, &rep, "$A$2"), count_of(&s, &rep, "$C$1")), (1, 1, 1)); +} + +#[test] +fn simplex_sensitivity_of_a_minimum_with_a_greater_row_and_a_bound() { + // min 2x + 3y with x + y ≥ 5 (a row) and x ≤ 2 (a bound): x = 2, y = 3, cost 13. The row's + // shadow price is 3: one more unit of right side costs one more y. x, at its upper bound, + // has reduced cost 2 − 1·3 = −1 (one more unit of its bound saves 1). Its coefficient may + // rise by 1 (to 3, a tie with y) and fall without limit: for a minimum's variable at its + // upper bound the Allowable Increase is the reduced cost's size and the Allowable Decrease + // 1E+30, the mirror image of a minimum's variable at zero (the reduced cost 1 with + // Allowable Increase 1E+30 and Allowable Decrease 1 in + // `sensitivity_report_gives_the_wyndor_glass_shadow_prices_and_ranges`). y's coefficient + // may rise without limit (x can take no more) and fall by 1 (to 2, a tie with x). The right + // side 5 may rise without limit and fall by 3 (y reaches 0 at 2). + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=2*A1+3*A2"), ("C1", "=A1+A2")]); + let p = json!({"objective": "B1", "goal": "min", "variables": "A1:A2", "constraints": ["C1 >= 5", "A1 <= 2"], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + let cols = ["D", "E", "F", "G", "H"]; + let row = |c: &str| report_row(&s, &rep, c, &cols); + assert!(close(&row("$A$1"), &[2.0, -1.0, 2.0, 1.0, 1e30], 1e-9), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[3.0, 0.0, 3.0, 1e30, 1.0], 1e-9), "{:?}", row("$A$2")); + assert!(close(&row("$C$1"), &[5.0, 3.0, 5.0, 1e30, 3.0], 1e-9), "{:?}", row("$C$1")); +} + +#[test] +fn simplex_sensitivity_gives_the_dakota_furniture_report() { + // Winston, Operations Research: Applications and Algorithms, the Dakota Furniture problem: + // max 60x₁ + 30x₂ + 20x₃ (desks, tables, chairs) with 8x₁ + 6x₂ + x₃ ≤ 48 (lumber), + // 4x₁ + 2x₂ + 1.5x₃ ≤ 20 (finishing) and 2x₁ + 1.5x₂ + 0.5x₃ ≤ 8 (carpentry): x = (2, 0, 8), + // revenue 280. For the basis {s₁, x₃, x₁} the rows of B⁻¹ are (1, 2, −8), (0, 2, −4) and + // (0, −0.5, 1.5), so the basic values are B⁻¹b = (24, 8, 2) and the shadow prices + // c_B·B⁻¹ = (0, 20, 60)·B⁻¹ = (0, 10, 10). Tables, at zero, have reduced cost + // 30 − (6·0 + 2·10 + 1.5·10) = −5: their price must rise by 5 before they are made, so the + // Allowable Increase is 5 and the Allowable Decrease 1E+30, as Excel's report shows a + // maximum's variable at zero. A change Δ in a basic variable's coefficient moves each + // nonbasic reduced cost by Δ times that variable's row of the final tableau; the tables' + // column there is B⁻¹(6, 2, 1.5) = (−2, −2, 1.25) and the slacks' columns are B⁻¹'s. Desks + // (row 3): −5 − 1.25Δ ≤ 0, −10 + 0.5Δ ≤ 0 and −10 − 1.5Δ ≤ 0 hold for −4 ≤ Δ ≤ 20. Chairs + // (row 2): −5 + 2Δ ≤ 0, −10 − 2Δ ≤ 0 and −10 + 4Δ ≤ 0 hold for −5 ≤ Δ ≤ 2.5. A right side + // moves the basic values along its column of B⁻¹: lumber (24 + Δ, 8, 2) ≥ 0 for Δ ≥ −24; + // finishing (24 + 2Δ, 8 + 2Δ, 2 − 0.5Δ) ≥ 0 for −4 ≤ Δ ≤ 4; carpentry + // (24 − 8Δ, 8 − 4Δ, 2 + 1.5Δ) ≥ 0 for −4/3 ≤ Δ ≤ 2. + let mut s = s(); + set( + &mut s, + &[ + ("A1", "0"), + ("A2", "0"), + ("A3", "0"), + ("B1", "=60*A1+30*A2+20*A3"), + ("C1", "=8*A1+6*A2+A3"), + ("C2", "=4*A1+2*A2+1.5*A3"), + ("C3", "=2*A1+1.5*A2+0.5*A3"), + ], + ); + let p = json!({"objective": "B1", "variables": "A1:A3", "constraints": ["C1 <= 48", "C2 <= 20", "C3 <= 8"], "method": "simplex", "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + assert_eq!(r["status"], "optimal", "{r}"); + assert_eq!(r["objective"], 280.0, "{r}"); + let rep = r["reports"][0].as_str().unwrap().to_string(); + let cols = ["D", "E", "F", "G", "H"]; + let row = |c: &str| report_row(&s, &rep, c, &cols); + assert!(close(&row("$A$1"), &[2.0, 0.0, 60.0, 20.0, 4.0], 1e-9), "{:?}", row("$A$1")); + assert!(close(&row("$A$2"), &[0.0, -5.0, 30.0, 5.0, 1e30], 1e-9), "{:?}", row("$A$2")); + assert!(close(&row("$A$3"), &[8.0, 0.0, 20.0, 2.5, 5.0], 1e-9), "{:?}", row("$A$3")); + assert!(close(&row("$C$1"), &[24.0, 0.0, 48.0, 1e30, 24.0], 1e-9), "{:?}", row("$C$1")); + assert!(close(&row("$C$2"), &[20.0, 10.0, 20.0, 4.0, 4.0], 1e-9), "{:?}", row("$C$2")); + assert!(close(&row("$C$3"), &[8.0, 10.0, 8.0, 2.0, 4.0 / 3.0], 1e-9), "{:?}", row("$C$3")); +} + +#[test] +fn nonlinear_sensitivity_signs_follow_the_goal() { + // A Lagrange multiplier is the derivative of the optimal objective with respect to the + // row's right side, and a reduced gradient that with respect to the variable's bound, + // whichever way the goal points. Frontline's "Excel Solver - Interpreting the Sensitivity + // Report" (solver.com) names a binding constraint's dual value its Lagrange multiplier and a + // variable's its reduced gradient, each the objective's change per unit increase in the + // constraint's bound or the variable, valid at the optimal point alone for a nonlinear + // model. + // min (x − 3)² + (y − 1)² with x + y ≤ b: the point of the line nearest (3, 1) is + // (2.5, 0.5) at b = 3, f*(b) = (4 − b)²/2 and df*/db = −(4 − b) = −1, the multiplier; + // maximising the negated objective reaches the same point with multiplier +1. Both + // variables are interior, so their reduced gradients are 0. + let mut s = s(); + set(&mut s, &[("A1", "0"), ("A2", "0"), ("B1", "=(A1-3)^2+(A2-1)^2"), ("B2", "=0-(A1-3)^2-(A2-1)^2"), ("C1", "=A1+A2")]); + for (obj, goal, lambda) in [("B1", "min", -1.0), ("B2", "max", 1.0)] { + set(&mut s, &[("A1", "0"), ("A2", "0")]); + let p = json!({"objective": obj, "goal": goal, "variables": "A1:A2", "constraints": ["C1 <= 3"], "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$A$1", &["D", "E"]), &[2.5, 0.0], 1e-3), "{goal}: {r}"); + assert!(close(&report_row(&s, &rep, "$A$2", &["D", "E"]), &[0.5, 0.0], 1e-3), "{goal}: {r}"); + assert!(close(&report_row(&s, &rep, "$C$1", &["D", "E"]), &[3.0, lambda], 1e-3), "{goal}: {r}"); + } + // max −(x + 1)² − (y − 2)² with x + y ≤ 1 and x, y ≥ 0 mirrors the minimum in + // `sensitivity_report_of_a_nonlinear_model_gives_lagrange_multipliers`: at (0, 1) the + // multiplier is +2 (−2 there) and x's reduced gradient −4 (4 there), since raising x from + // its bound lowers the maximum by 2(x + 1) + 2 = 4 per unit. + set(&mut s, &[("D1", "0.5"), ("D2", "0.5"), ("E1", "=0-(D1+1)^2-(D2-2)^2"), ("E2", "=D1+D2")]); + let p = json!({"objective": "E1", "goal": "max", "variables": "D1:D2", "constraints": ["E2 <= 1"], "reports": ["sensitivity"]}); + let r = s.execute("data.solver", p).unwrap(); + let rep = r["reports"][0].as_str().unwrap().to_string(); + assert!(close(&report_row(&s, &rep, "$D$1", &["D", "E"]), &[0.0, -4.0], 1e-3), "{r}"); + assert!(close(&report_row(&s, &rep, "$D$2", &["D", "E"]), &[1.0, 0.0], 1e-3), "{r}"); + assert!(close(&report_row(&s, &rep, "$E$2", &["D", "E"]), &[1.0, 2.0], 1e-3), "{r}"); +} + fn formula(s: &Session, a1: &str) -> String { let d = s.doc().unwrap(); d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap_or_default() diff --git a/crates/engine/src/cmd/whatif.rs b/crates/engine/src/cmd/whatif.rs index c801c7359b..1a0866e830 100644 --- a/crates/engine/src/cmd/whatif.rs +++ b/crates/engine/src/cmd/whatif.rs @@ -213,7 +213,7 @@ impl Trial { for (si, c, v) in sets { if let Some(sh) = wb.sheet_mut(*si) { let style = sh.style_id(*c); - sh.set_cell(*c, Cell { value: v.clone(), formula: None, style }); + sh.set_cell(*c, Cell { value: v.clone(), formula: None, style, py: None }); keys.push((*si, *c)); } } @@ -329,7 +329,8 @@ fn goal_seek(s: &mut Session, p: &Json) -> Result { if !has_formula(ssi, set) { return Err(EngineError::Other("Cell must contain a formula.".into())); } - if has_formula(csi, chg) { + // A Python cell is a formula to Excel (`=PY(…)`): writing a number over it would lose its code. + if has_formula(csi, chg) || d.wb.sheet(csi).and_then(|sh| sh.cell(chg)).is_some_and(|c| c.py.is_some()) { return Err(EngineError::Other("Cell must contain a value.".into())); } let x0 = d.wb.sheet(csi).map(|sh| sh.value(chg)).and_then(|v| v.as_f64()).unwrap_or(0.0); @@ -342,7 +343,7 @@ fn goal_seek(s: &mut Session, p: &Json) -> Result { edit(s, |cx| { let sh = cx.sheet_mut(csi)?; let style = sh.style_id(chg); - sh.set_cell(chg, Cell { value: Value::number(r.x), formula: None, style }); + sh.set_cell(chg, Cell { value: Value::number(r.x), formula: None, style, py: None }); cx.touch(csi, chg); Ok(()) })?; @@ -422,7 +423,7 @@ fn data_table(s: &mut Session, p: &Json) -> Result { for (c, v) in out { let sh = cx.sheet_mut(si)?; let style = sh.style_id(c); - sh.set_cell(c, Cell { value: v, formula: None, style }); + sh.set_cell(c, Cell { value: v, formula: None, style, py: None }); cx.touch(si, c); } Ok(()) diff --git a/crates/engine/src/cmd/whatif/advanced_filter.rs b/crates/engine/src/cmd/whatif/advanced_filter.rs index e210043422..52630a3efe 100644 --- a/crates/engine/src/cmd/whatif/advanced_filter.rs +++ b/crates/engine/src/cmd/whatif/advanced_filter.rs @@ -186,7 +186,7 @@ pub(super) fn advanced_filter(s: &mut Session, p: &Json) -> Result { // The full output footprint was checked above. let to = CellRef::new(dest.row + i as u32, dest.col + c - list.start.col); let style = sh.style_id(src); - (to, Cell { value: sh.value(src), formula: None, style }) + (to, Cell { value: sh.value(src), formula: None, style, py: None }) }) }) .collect(); diff --git a/crates/engine/src/cmd/whatif/consolidate.rs b/crates/engine/src/cmd/whatif/consolidate.rs index ec5fbb54a9..149b72bc7a 100644 --- a/crates/engine/src/cmd/whatif/consolidate.rs +++ b/crates/engine/src/cmd/whatif/consolidate.rs @@ -185,7 +185,7 @@ pub(super) fn consolidate(s: &mut Session, p: &Json) -> Result { if v.is_empty() && style == StyleId::DEFAULT { sh.remove_cell(c); } else { - sh.set_cell(c, Cell { value: v, formula: None, style }); + sh.set_cell(c, Cell { value: v, formula: None, style, py: None }); } cx.touch(dsi, c); } diff --git a/crates/engine/src/cmd/whatif/scenarios.rs b/crates/engine/src/cmd/whatif/scenarios.rs index fc442f8f90..75bf147a05 100644 --- a/crates/engine/src/cmd/whatif/scenarios.rs +++ b/crates/engine/src/cmd/whatif/scenarios.rs @@ -160,7 +160,7 @@ pub(super) fn scenario_show(s: &mut Session, p: &Json) -> Result { let cell = match v.as_f64() { Some(n) => { let style = cx.wb.sheet(si).map(|sh| sh.style_id(*c)).unwrap_or_default(); - Some(Cell { value: Value::Number(n), formula: None, style }) + Some(Cell { value: Value::Number(n), formula: None, style, py: None }) } None => crate::cmd::edit::input_to_cell(&crate::cmd::edit::json_to_input(v), si, *c, &mut cx.wb)?, }; @@ -245,7 +245,7 @@ pub(super) fn scenario_summary(s: &mut Session, p: &Json) -> Result { let bold = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.font.bold = true); let mut sheet = Sheet::new(name.clone()); let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| { - sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style }); + sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style, py: None }); }; put(&mut sheet, 1, 1, Value::text("Scenario Summary"), bold); put(&mut sheet, 2, 2, Value::text("Current Values:"), bold); diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index aa8bdb22dd..2189d6c641 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -90,14 +90,14 @@ pub fn edit_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { if reads_back(&iso) { iso } else { raw } } -/// Whether `c` has a formula that must not be shown: its cell is formatted Hidden on a -/// protected sheet. A spilled cell follows its anchor. +/// Whether `c` has a formula or Python code that must not be shown: its cell is formatted +/// Hidden on a protected sheet. A spilled cell follows its anchor. pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool { if !sheet.is_protected() { return false; } let at = match sheet.cell(c) { - Some(x) if x.formula.is_some() => c, + Some(x) if x.formula.is_some() || x.py.is_some() => c, _ => match sheet.spill_ranges.iter().find(|(_, r)| r.contains(c)) { Some((anchor, _)) => *anchor, None => return false, diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rs index 1201721da2..c63d7c983f 100644 --- a/crates/engine/src/fill.rs +++ b/crates/engine/src/fill.rs @@ -171,10 +171,12 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F cell.formula = Some(Arc::new(Formula::from_expr(shifted))); cell.value = Value::Empty; } - } else if let Some(v) = match per_cell.get(src_i) { - Some(p) => p.value(k as i64 / src_cells.len() as i64 + 1, forward, 1), - None => pattern.value(step, forward, src_cells.len()), - } { + } else if cell.py.is_none() + && let Some(v) = match per_cell.get(src_i) { + Some(p) => p.value(k as i64 / src_cells.len() as i64 + 1, forward, 1), + None => pattern.value(step, forward, src_cells.len()), + } + { cell.value = v; } cell.style = style; @@ -296,7 +298,8 @@ impl Pattern { fn detect(cells: &[(CellRef, Option)], custom: &[Vec], sys: gridcraft_core::DateSystem, fmt: &str) -> Pattern { let vals: Vec = cells.iter().map(|(_, c)| c.as_ref().map(|c| c.value.clone()).unwrap_or_default()).collect(); - if cells.iter().any(|(_, c)| c.as_ref().is_some_and(|c| c.formula.is_some())) { + // Formulas and Python cells copy. + if cells.iter().any(|(_, c)| c.as_ref().is_some_and(|c| c.formula.is_some() || c.py.is_some())) { return Pattern::Copy; } // Numbers. @@ -598,7 +601,7 @@ pub fn series(cx: &mut Ctx, sheet: usize, options: SeriesOptions<'_>) -> Result< break; } let c = if rows { CellRef::new(lane, r.start.col + i) } else { CellRef::new(r.start.row + i, lane) }; - writes.push((c, Cell { value: Value::number(round15(v)), formula: None, style })); + writes.push((c, Cell { value: Value::number(round15(v)), formula: None, style, py: None })); } } let sh = cx.sheet_mut(sheet)?; @@ -657,7 +660,7 @@ pub fn flash_fill(cx: &mut Ctx, sheet: usize, at: CellRef) -> Result { } let sh = cx.sheet_mut(sheet)?; for (c, out) in &writes { - sh.set_cell(*c, Cell { value: Value::text(out.as_str()), formula: None, style }); + sh.set_cell(*c, Cell { value: Value::text(out.as_str()), formula: None, style, py: None }); } for (c, _) in writes { cx.touch(sheet, c); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 69b1ebfa73..ce1fb40b03 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -118,13 +118,142 @@ fn decrypt_message(name: &str, e: gridcraft_xlsx::DecryptError) -> String { } } -/// Parses bytes that aren't encrypted, then takes the workbook's macros out of their hidden names. +/// Parses bytes that aren't encrypted, then takes the workbook's macros out of their hidden names +/// and adopts the Python cells they hold (see [`adopt_python`]) within the limits of +/// [`enforce_python_limits`]. fn open_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook, Vec)> { let (mut wb, mut warnings) = read_plain(name, bytes, csv_as_text)?; warnings.extend(crate::macros::load(&mut wb)); + warnings.extend(adopt_python(&mut wb)); + warnings.extend(enforce_python_limits(&mut wb)); Ok((wb, warnings)) } +/// The most result cells [`adopt_python`] rebuilds from a file's cached spills, over all its +/// Python cells (each one is also limited to [`gridcraft_model::python::MAX_RESULT_CELLS`]). +pub const MAX_ADOPTED_RESULT_CELLS: u64 = 4_000_000; + +/// Python cells from a file: a cell whose formula is `PY("…",0|1)` (a format that kept it as a +/// formula) becomes a Python cell, and a Python cell whose spilled values the file cached gets +/// them back as its result, so it shows them until it runs again. Results are rebuilt for at most +/// [`MAX_ADOPTED_RESULT_CELLS`] cells in all; the rest keep only their own cached value, and the +/// values they spilled stay as plain values. Returns the warnings. +pub fn adopt_python(wb: &mut Workbook) -> Vec { + let mut budget = MAX_ADOPTED_RESULT_CELLS; + let mut skipped = 0usize; + for si in 0..wb.sheets.len() { + let Some(sh) = wb.sheets.get(si) else { continue }; + let formulas: Vec<(CellRef, gridcraft_model::PyCode)> = sh + .cells + .iter() + .filter_map(|(c, cell)| cell.formula.as_ref().and_then(|f| gridcraft_model::PyCode::from_formula(&f.text)).map(|p| (c, p))) + .collect(); + let max = gridcraft_model::python::MAX_RESULT_CELLS as u64; + let spills: Vec<(CellRef, RangeRef)> = sh + .spill_ranges + .iter() + .filter(|(a, r)| r.count() <= max && sh.cell(**a).and_then(|c| c.py.as_ref()).is_some_and(|p| p.output.is_none())) + .map(|(a, r)| (*a, *r)) + .collect(); + if formulas.is_empty() && spills.is_empty() { + continue; + } + let Some(sh) = wb.sheet_mut(si) else { continue }; + for (c, py) in formulas { + if let Some(cell) = sh.cells.get_mut(c) { + cell.formula = None; + cell.py = Some(std::sync::Arc::new(py)); + } + } + for (anchor, range) in spills { + let Some(left) = budget.checked_sub(range.count()) else { + skipped += 1; + // The cell keeps only its own value; the values it spilled stay as plain values, so + // nothing shows as a spill that no result holds, and nothing the file showed is lost. + sh.settle_spill(anchor); + continue; + }; + budget = left; + let data: Vec = + range.iter().map(|c| if c == anchor { sh.cell(c).map(|x| x.value.clone()).unwrap_or_default() } else { sh.value(c) }).collect(); + let Some(array) = gridcraft_core::Array::new(range.height() as usize, range.width() as usize, data) else { continue }; + if let Some(py) = sh.cells.get_mut(anchor).and_then(|x| x.py.as_mut()) { + std::sync::Arc::make_mut(py).output = + Some(gridcraft_model::PyOutput { value: array.into(), type_name: "list".into(), preview: String::new(), convertible: true }); + } + } + } + if skipped == 0 { + return Vec::new(); + } + vec![format!( + "The file's Python results are larger than {MAX_ADOPTED_RESULT_CELLS} cells in all, so {skipped} Python cell(s) have no result until they run again; the values they spilled were kept as plain values." + )] +} + +/// A file is somebody else's work: a Python cell whose code doesn't fit in Excel's +/// 8,192-character formula keeps only its cached value, and a kept result that is not a +/// well-formed array of at most [`gridcraft_model::python::MAX_RESULT_CELLS`] cells is dropped +/// (the cell keeps its value). Either way the values the cell spilled stay as plain values +/// ([`gridcraft_model::Sheet::settle_spill`]). Returns the warnings. +pub fn enforce_python_limits(wb: &mut Workbook) -> Vec { + let mut long = Vec::new(); + for si in 0..wb.sheets.len() { + let Some(sh) = wb.sheets.get(si) else { continue }; + let mut over = Vec::new(); + let mut bad_output = Vec::new(); + for (c, cell) in sh.cells.iter() { + let Some(py) = &cell.py else { continue }; + if !py.fits() { + long.push(format!("{}!{}", sh.name, c.a1())); + over.push(c); + } else if py.output.as_ref().is_some_and(|o| !sane_python_output(&o.value)) { + bad_output.push(c); + } + } + if over.is_empty() && bad_output.is_empty() { + continue; + } + let dropped: Vec = over.iter().chain(&bad_output).copied().collect(); + let Some(sh) = wb.sheet_mut(si) else { continue }; + for c in over { + if let Some(cell) = sh.cells.get_mut(c) { + cell.py = None; + } + } + for c in bad_output { + if let Some(py) = sh.cells.get_mut(c).and_then(|x| x.py.as_mut()) { + std::sync::Arc::make_mut(py).output = None; + } + } + // A dropped result (or code dropped to its value) leaves the values it spilled as plain + // values, as the file showed them, with no live spill. + for c in dropped { + sh.settle_spill(c); + } + } + let Some(first) = long.first() else { return vec![] }; + let more = if long.len() > 1 { format!(" (and {} more)", long.len() - 1) } else { String::new() }; + vec![format!( + "A Python cell's code is longer than Excel's {}-character formula limit, so {first}{more} kept only its last calculated value.", + gridcraft_model::python::MAX_FORMULA_CHARS + )] +} + +/// A Python result a file may hold: a scalar, or an array whose size matches its data and has at +/// most [`gridcraft_model::python::MAX_RESULT_CELLS`] cells. +fn sane_python_output(v: &gridcraft_core::Value) -> bool { + match v { + gridcraft_core::Value::Array(a) => { + a.rows >= 1 + && a.cols >= 1 + && a.rows.checked_mul(a.cols).is_some_and(|n| n == a.data.len() && n <= gridcraft_model::python::MAX_RESULT_CELLS) + } + _ => true, + } +} + +/// Parses bytes that aren't encrypted, as they are. fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook, Vec)> { let kind = FileKind::from_path(name); let sniffed = gridcraft_xlsx::sniff(bytes); diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index e4841b562b..9051c5c096 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -461,17 +461,17 @@ fn csv_writes_displayed_text() { (styled("yyyy-mm-dd"), styled("$#,##0.00"), styled("0.0%"), styled("# ?/?"), styled("@"), styled("0.00"), styled("#,##0")); let sh = wb.sheet_mut(0).unwrap(); let cells = [ - ("A1", Cell { value: Value::Number(46023.0), formula: None, style: date }), - ("B1", Cell { value: Value::Number(1234.5), formula: None, style: money }), - ("C1", Cell { value: Value::Number(0.125), formula: None, style: pct }), - ("D1", Cell { value: Value::Number(1.5), formula: None, style: frac }), - ("E1", Cell { value: Value::text("007"), formula: None, style: text }), - ("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money }), - ("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT }), + ("A1", Cell { value: Value::Number(46023.0), formula: None, style: date, py: None }), + ("B1", Cell { value: Value::Number(1234.5), formula: None, style: money, py: None }), + ("C1", Cell { value: Value::Number(0.125), formula: None, style: pct, py: None }), + ("D1", Cell { value: Value::Number(1.5), formula: None, style: frac, py: None }), + ("E1", Cell { value: Value::text("007"), formula: None, style: text, py: None }), + ("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money, py: None }), + ("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT, py: None }), ("A2", Cell { value: Value::Number(46024.0), style: date, ..Cell::formula(Formula::new("A1+1")) }), - ("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed }), - ("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT }), - ("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands }), + ("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed, py: None }), + ("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT, py: None }), + ("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands, py: None }), ]; for (a, c) in cells { sh.set_cell(CellRef::parse(a).unwrap(), c); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4ea043a68a..6f61b239e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -39,6 +39,7 @@ pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command, register_te pub use gridcraft_calc as calc; pub use gridcraft_core as core; pub use gridcraft_formula as formula; +pub use gridcraft_math as math; pub use gridcraft_model as model; pub use gridcraft_numfmt as numfmt; pub use selection::Selection; @@ -304,7 +305,9 @@ impl DocState { calc.rebuild(&wb); Self::with_calc(wb, calc, path, title, trust) } - fn with_calc(wb: Workbook, calc: Calc, path: Option, title: String, trust: Trust) -> DocState { + fn with_calc(mut wb: Workbook, calc: Calc, path: Option, title: String, trust: Trust) -> DocState { + // Equations arrive without a layout (files never store one); painting reads only the cache. + wb.refresh_equations(); let scripts_trusted = !cmd::extra::has_scripts(&wb); let wb = Arc::new(wb); let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default()); @@ -792,7 +795,7 @@ impl Session { // A toggle (Bold) is recorded with the state it set, as Excel records // `Bold = True`: playing it back sets that state rather than flipping it again. let params = match &result { - Ok(r) if params.is_object() => record::with_toggle_state(cmd::journal_params(¶ms), r), + Ok(r) if params.is_object() => record::with_toggle_state(id, cmd::journal_params(¶ms), r), _ => cmd::journal_params(¶ms), }; let kept = rec.push(record::RecordedStep { doc, sheet, sheet_name, selection, id: id.to_string(), params }); diff --git a/crates/engine/src/macros/resolve.rs b/crates/engine/src/macros/resolve.rs index 3825dcc962..c5c2da8d70 100644 --- a/crates/engine/src/macros/resolve.rs +++ b/crates/engine/src/macros/resolve.rs @@ -614,7 +614,10 @@ mod tests { let mut wb = wb(); let sh = wb.sheet_mut(0).unwrap(); let formula = Some(std::sync::Arc::new(gridcraft_model::Formula::new("\"Amo\"&\"unt\""))); - sh.set_cell(CellRef::new(1, 2), gridcraft_model::Cell { value: gridcraft_core::Value::text("Amount"), formula, style: Default::default() }); + sh.set_cell( + CellRef::new(1, 2), + gridcraft_model::Cell { value: gridcraft_core::Value::text("Amount"), formula, style: Default::default(), py: None }, + ); sh.show_formulas = true; let inputs = vec![("Input".to_string(), place("B2:D11"), true)]; let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None }; diff --git a/crates/engine/src/macros/run.rs b/crates/engine/src/macros/run.rs index fcb6768f3f..71c23aabef 100644 --- a/crates/engine/src/macros/run.rs +++ b/crates/engine/src/macros/run.rs @@ -1237,26 +1237,39 @@ pub(crate) fn pair_sheets(before: &Workbook, after: &Workbook) -> (Vec<(usize, O (pairs, spare.collect()) } -/// Only a formula's cached value changed (a recalculation, not a write). +/// Only a formula's (or a Python cell's) cached value changed (a recalculation, not a write): a +/// Python cell whose spill a step blocked shows #SPILL! with its code untouched. fn recalculated_only(b: Option<&Cell>, a: Option<&Cell>) -> bool { match (b, a) { (Some(b), Some(a)) => match (&b.formula, &a.formula) { (Some(x), Some(y)) => x.text == y.text && x.array == y.array && b.style == a.style, + (None, None) => match (&b.py, &a.py) { + (Some(x), Some(y)) => x.code == y.code && x.object == y.object && b.style == a.style, + _ => false, + }, _ => false, }, _ => false, } } +/// Python code is content, as a formula is, whatever the cell shows. fn has_content(c: &Cell) -> bool { - c.formula.is_some() || !(c.value.is_empty() || c.value.as_text() == Some("")) + c.formula.is_some() || c.py.is_some() || !(c.value.is_empty() || c.value.as_text() == Some("")) } +/// Whether a write changed what the person entered: the formula, the Python code and its return +/// type, or the value. A Python cell replaced by its own cached value, or by other code that +/// shows the same `#BLOCKED!`, has changed. fn content_differs(b: Option<&Cell>, a: Option<&Cell>) -> bool { match (b, a) { (Some(b), Some(a)) => match (&b.formula, &a.formula) { (Some(x), Some(y)) => x.text != y.text, - (None, None) => b.value != a.value, + (None, None) => match (&b.py, &a.py) { + (Some(x), Some(y)) => x.code != y.code || x.object != y.object, + (None, None) => b.value != a.value, + _ => true, + }, _ => true, }, (Some(b), None) => has_content(b), diff --git a/crates/engine/src/paper.rs b/crates/engine/src/paper.rs index 0800f4fc76..99981fc8cb 100644 --- a/crates/engine/src/paper.rs +++ b/crates/engine/src/paper.rs @@ -10,7 +10,7 @@ //! `(gap + j·(page_w + gap), gap + i·(page_h + gap))`, and its cells start at its top-left margin. use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; -use gridcraft_model::{LineIndex, Sheet, Workbook}; +use gridcraft_model::{LineIndex, PageOrder, Sheet, Workbook}; use crate::cmd::print::{self, PX_TO_PT, PrintOptions}; @@ -45,6 +45,8 @@ pub struct PageGrid { /// Bands holding printed data: `[first, last]` row bands and column bands. pub data_rows: (usize, usize), pub data_cols: (usize, usize), + /// The sheet's page order, which numbers the printed pages. + pub page_order: PageOrder, ri: LineIndex, ci: LineIndex, } @@ -96,6 +98,7 @@ impl PageGrid { col_bands, data_rows, data_cols, + page_order: printed.settings.page_order, ri: LineIndex::new(&sh.rows, sh.default_row_height, MAX_ROWS), ci: LineIndex::new(&sh.cols, sh.default_col_width, MAX_COLS), }) @@ -206,14 +209,14 @@ impl PageGrid { pub fn is_data_page(&self, i: usize, j: usize) -> bool { (self.data_rows.0..=self.data_rows.1).contains(&i) && (self.data_cols.0..=self.data_cols.1).contains(&j) } - /// Printed page number of page `(i, j)` (down, then over) and the printed page count. + /// Printed page number of page `(i, j)` (in the sheet's page order) and the printed page count. pub fn page_number(&self, i: usize, j: usize) -> Option<(usize, usize)> { if !self.is_data_page(i, j) { return None; } let rows = self.data_rows.1 - self.data_rows.0 + 1; let cols = self.data_cols.1 - self.data_cols.0 + 1; - Some(((j - self.data_cols.0) * rows + (i - self.data_rows.0) + 1, rows * cols)) + Some((self.page_order.index(i - self.data_rows.0, j - self.data_cols.0, rows, cols) + 1, rows * cols)) } /// Page rows and columns overlapping the layout rectangle `[x0, x1] × [y0, y1]`. @@ -312,6 +315,21 @@ mod tests { assert!(g.is_data_page(0, 0) && !g.is_data_page(1, 0)); } + #[test] + fn page_numbers_follow_the_page_order() { + // Two pages tall and two wide, as printed; the pages beyond are "Click to add data" pages. + let mut wb = wb_with(60, 15); + let numbers = |wb: &Workbook| { + let g = PageGrid::build(wb, 0, 200, 60).unwrap(); + assert_eq!((g.data_rows, g.data_cols), ((0, 1), (0, 1))); + assert_eq!((g.page_number(2, 0), g.page_number(0, 2)), (None, None)); + [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(i, j)| g.page_number(i, j).unwrap()) + }; + assert_eq!(numbers(&wb), [(1, 4), (2, 4), (3, 4), (4, 4)]); + wb.sheet_mut(0).unwrap().print.page_order = PageOrder::OverThenDown; + assert_eq!(numbers(&wb), [(1, 4), (3, 4), (2, 4), (4, 4)]); + } + #[test] fn header_zones_and_text_follow_scale_with_document_and_align_with_page_margins() { let mut wb = wb_with(10, 3); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index e43050c675..b07c17cc04 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -269,7 +269,7 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re } if !replace { for (c, cell) in sh.cells.iter_range(area) { - if (!cell.value.is_empty() || cell.formula.is_some()) && !pt.last_range.is_some_and(|r| r.contains(c)) { + if cell.has_content() && !pt.last_range.is_some_and(|r| r.contains(c)) { return Err(format!( "There's already data in {}!{}. Do you want to replace it? (Run again with replace: true to overwrite.)", quote_sheet(&sh.name), @@ -319,7 +319,10 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re if oc.value.is_empty() && id == StyleId::default() { continue; } - cells.push((CellRef::new(origin.row + ri as u32, origin.col + ci as u32), Cell { value: oc.value.clone(), formula: None, style: id })); + cells.push(( + CellRef::new(origin.row + ri as u32, origin.col + ci as u32), + Cell { value: oc.value.clone(), formula: None, style: id, py: None }, + )); } } // Column widths that fit the labels. diff --git a/crates/engine/src/record.rs b/crates/engine/src/record.rs index 269d11aed2..a970823309 100644 --- a/crates/engine/src/record.rs +++ b/crates/engine/src/record.rs @@ -74,15 +74,21 @@ impl Default for Recorder { /// `params` with the state a toggle set (Bold's `on`, from the command's result), as Excel /// records `Bold = True`: playing the step back sets that state rather than flipping it again. -pub(crate) fn with_toggle_state(mut params: Json, result: &Json) -> Json { - if let Some(on @ Json::Bool(_)) = result.get("on") { +/// `python.output` without `mode` is a toggle too: it keeps the return type it set (the result's +/// `output`) as its `mode`. +pub(crate) fn with_toggle_state(id: &str, mut params: Json, result: &Json) -> Json { + let state = match id { + "python.output" => result.get("output").filter(|o| o.is_string()).map(|o| ("mode", o)), + _ => result.get("on").filter(|o| o.is_boolean()).map(|o| ("on", o)), + }; + if let Some((key, state)) = state { if params.is_null() { params = Json::Object(serde_json::Map::new()); } if let Json::Object(p) = &mut params - && !p.contains_key("on") + && p.get(key).is_none_or(Json::is_null) { - p.insert("on".into(), on.clone()); + p.insert(key.into(), state.clone()); } } params diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 4df6fbe4ab..0e00e4869b 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -190,7 +190,7 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef { /// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables). pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef { - let filled = |c: CellRef| sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c); + let filled = |c: CellRef| sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col))); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 58447e36e7..22e71330ad 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5243,7 +5243,12 @@ fn a_script_cannot_switch_windows() { assert_eq!(v(&s, "A1"), Value::number(2.0)); } +mod equation; mod macros; +mod objects; +mod python_cells; +mod python_commands; +mod python_files; mod seams; #[test] diff --git a/crates/engine/src/tests/equation.rs b/crates/engine/src/tests/equation.rs new file mode 100644 index 0000000000..6b544b2acc --- /dev/null +++ b/crates/engine/src/tests/equation.rs @@ -0,0 +1,227 @@ +//! Equations: insert, edit, the layout cache and its rebuild on load. + +use gridcraft_model::{Color, Shape, ShapeKind}; +use serde_json::json; + +use super::s; +use crate::Session; + +fn equation(s: &Session, id: u32) -> Shape { + s.doc().unwrap().wb.active().unwrap().shapes.iter().find(|x| x.id == id).cloned().unwrap() +} + +fn insert(s: &mut Session, p: serde_json::Value) -> u32 { + s.execute("insert.equation", p).unwrap()["equation"].as_u64().unwrap() as u32 +} + +#[test] +fn insert_lays_the_equation_out_and_sizes_its_frame() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}", "cell": "C3"})); + let e = equation(&s, id); + assert_eq!(e.kind, ShapeKind::Equation); + assert_eq!(e.anchor.cell.a1(), "C3"); + assert_eq!(e.line, Color::Auto, "Automatic ink"); + let list = e.math.get(&e.text).unwrap().unwrap(); + let scale = crate::cmd::equation::fit_scale(list, e.anchor.width, e.anchor.height); + assert!((scale - 11.0 * 96.0 / 72.0).abs() < 0.01, "11 pt: {scale}"); + // A bigger size makes a bigger frame; `at` works like `cell`. + let big = insert(&mut s, json!({"latex": "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}", "at": "H3", "size": 22, "color": "#1F4E79"})); + let b = equation(&s, big); + assert!((b.anchor.width - 8.0) > 1.9 * (e.anchor.width - 8.0)); + assert_eq!(b.line, Color::Rgb(0x1F4E79)); + assert_eq!(b.anchor.cell.a1(), "H3"); + // One undo step each. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().shapes.iter().all(|x| x.id != big)); +} + +#[test] +fn insert_refuses_missing_bad_or_hostile_source() { + let mut s = s(); + for p in [ + json!({}), + json!({"latex": ""}), + json!({"latex": " "}), + json!({"latex": 5}), + json!({"latex": "x", "size": 0}), + json!({"latex": "x", "size": f64::MAX}), + json!({"latex": "x", "color": "nope"}), + ] { + assert!(s.execute("insert.equation", p.clone()).is_err(), "{p}"); + } + let e = s.execute("insert.equation", json!({"latex": "a + \\foo"})).unwrap_err().to_string(); + assert!(e.contains("character 5") && e.contains("\\foo"), "{e}"); + let e = s.execute("insert.equation", json!({"latex": "x".repeat(5000)})).unwrap_err().to_string(); + assert!(e.contains("4096"), "{e}"); + let e = s.execute("insert.equation", json!({"latex": format!("{}x{}", "{".repeat(40), "}".repeat(40))})).unwrap_err().to_string(); + assert!(e.contains("nest"), "{e}"); + assert!(s.doc().unwrap().wb.active().unwrap().shapes.is_empty()); + // `equation.edit` is the other way a source reaches the layout engine; it has the same caps, + // and a refused edit leaves the equation as it was. + let id = insert(&mut s, json!({"latex": "x"})); + let e = s.execute("equation.edit", json!({"id": id, "latex": "x".repeat(5000)})).unwrap_err().to_string(); + assert!(e.contains("4096"), "{e}"); + let e = s.execute("equation.edit", json!({"id": id, "latex": format!("{}x{}", "{".repeat(40), "}".repeat(40))})).unwrap_err().to_string(); + assert!(e.contains("nest"), "{e}"); + assert_eq!(equation(&s, id).text, "x"); +} + +#[test] +fn edit_keeps_the_scale_and_fits_the_frame() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x", "size": 20})); + let before = equation(&s, id); + s.execute("equation.edit", json!({"id": id, "latex": "x + y + z"})).unwrap(); + let after = equation(&s, id); + assert_eq!(after.text, "x + y + z"); + let list = after.math.get(&after.text).unwrap().unwrap(); + let scale = crate::cmd::equation::fit_scale(list, after.anchor.width, after.anchor.height); + assert!((scale - 20.0 * 96.0 / 72.0).abs() < 0.05, "{scale}"); + assert!(after.anchor.width > before.anchor.width); + // A frame the user resized keeps its new scale through an edit. + s.execute("object.move", json!({"kind": "equation", "id": id, "width": after.anchor.width * 2.0, "height": after.anchor.height * 2.0})).unwrap(); + s.execute("equation.edit", json!({"id": id, "latex": "x + y"})).unwrap(); + let e = equation(&s, id); + let scale = crate::cmd::equation::fit_scale(e.math.get(&e.text).unwrap().unwrap(), e.anchor.width, e.anchor.height); + assert!(scale > 2.0 * 20.0 * 96.0 / 72.0 * 0.95, "{scale}"); + // Undo restores the source and its layout. + s.execute("edit.undo", json!({})).unwrap(); + let e = equation(&s, id); + assert_eq!(e.text, "x + y + z"); + assert!(e.math.get(&e.text).unwrap().is_ok()); + // Same source: nothing to do. Bad source: refused, nothing changes. + let depth = s.doc().unwrap().undo.len(); + s.execute("equation.edit", json!({"id": id, "latex": "x + y + z"})).unwrap(); + assert_eq!(s.doc().unwrap().undo.len(), depth); + assert!(s.execute("equation.edit", json!({"id": id, "latex": "\\frac{"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": id, "latex": ""})).is_err()); + assert_eq!(equation(&s, id).text, "x + y + z"); +} + +#[test] +fn the_source_excerpt_is_at_most_the_cap_and_whole_chars() { + use crate::cmd::equation::source_excerpt; + use gridcraft_math::MAX_SOURCE_BYTES as CAP; + assert_eq!(source_excerpt(""), ""); + assert_eq!(source_excerpt("x+y"), "x+y"); + let at = "x".repeat(CAP); + assert_eq!(source_excerpt(&at), at, "a source at the cap is whole"); + assert_eq!(source_excerpt(&format!("{at}tail")), at); + // A three-byte character straddling the cap is left out rather than cut in two. + let s = format!("{}\u{20AC}", "x".repeat(CAP - 1)); + assert_eq!(source_excerpt(&s), "x".repeat(CAP - 1)); + let s = format!("{}\u{20AC}\u{20AC}", "x".repeat(CAP - 2)); + assert_eq!(source_excerpt(&s).len(), CAP - 2); + assert_eq!(source_excerpt(&"\u{1F600}".repeat(2000)).len(), CAP); +} + +#[test] +fn edit_refuses_what_is_not_an_equation() { + let mut s = s(); + let tb = s.execute("insert.textBox", json!({"text": "hi"})).unwrap()["shape"].as_u64().unwrap(); + assert!(s.execute("equation.edit", json!({"id": tb, "latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": 999, "latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"latex": "x"})).is_err()); + assert!(s.execute("equation.edit", json!({"id": -1, "latex": "x"})).is_err()); +} + +#[test] +fn layouts_are_rebuilt_on_load_and_not_saved() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "e^{i\\pi} + 1 = 0"})); + let wb = s.doc().unwrap().wb.clone(); + let bytes = serde_json::to_vec(&*wb).unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("\"math\""), "the cache is not saved"); + let (opened, _) = crate::io::open_bytes("book.json", &bytes).unwrap(); + let raw = opened.active().unwrap().shapes.iter().find(|x| x.id == id).cloned().unwrap(); + assert!(raw.math.get(&raw.text).is_none(), "a freshly read shape has no layout"); + let mut t = Session::new(); + t.add_document(crate::DocState::new(opened, None, "Book".into(), crate::Trust::FromFile)); + let e = equation(&t, id); + assert!(e.math.get(&e.text).unwrap().is_ok(), "opening lays it out"); +} + +#[test] +fn a_bad_source_from_a_file_keeps_its_error() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + sh.shapes.iter_mut().for_each(|x| x.text = "\\frac{".into()); + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let e = equation(&t, id); + assert!(e.math.get(&e.text).unwrap().is_err()); +} + +#[test] +fn equations_on_a_protected_sheet_are_locked() { + let mut s = s(); + let id = insert(&mut s, json!({"latex": "x"})); + s.execute("review.protectSheet", json!({})).unwrap(); + assert!(s.execute("equation.edit", json!({"id": id, "latex": "y"})).is_err()); + assert!(s.execute("insert.equation", json!({"latex": "y"})).is_err()); +} + +#[test] +fn a_file_with_too_many_equations_lays_out_a_bounded_amount() { + // About 1 KB each: past the budget, equations are refused without running the layout engine, + // so opening the file takes bounded time. + let source = format!("x{}", "+x".repeat(500)); + let count = gridcraft_model::MAX_EQUATION_LAYOUT_BYTES / source.len() + 40; + let mut s = s(); + let first = insert(&mut s, json!({"latex": "x", "cell": "A1"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + let template = sh.shapes.iter().find(|x| x.id == first).cloned().unwrap(); + sh.shapes.clear(); + for i in 0..count { + let mut e = template.clone(); + e.id = 100 + i as u32; + e.text = source.clone(); + e.math = Default::default(); + sh.shapes.push(e); + } + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let shapes = t.doc().unwrap().wb.active().unwrap().shapes.clone(); + let laid = shapes.iter().filter(|x| matches!(x.math.get(&x.text), Some(Ok(_)))).count(); + let refused: Vec<&Shape> = + shapes.iter().filter(|x| matches!(x.math.get(&x.text), Some(Err(e)) if e.message == gridcraft_model::EQUATION_BUDGET_MESSAGE)).collect(); + assert_eq!(laid + refused.len(), count, "every equation has a layout or the budget's error"); + assert!(laid * source.len() <= gridcraft_model::MAX_EQUATION_LAYOUT_BYTES, "{laid} laid out"); + assert!(refused.len() >= 40, "{} refused", refused.len()); + // A later edit does not retry them all, and OK on one, unchanged, lays it out. + let id = refused[0].id; + t.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + assert!(matches!(equation(&t, id).math.get(&source), Some(Err(_)))); + t.execute("equation.edit", json!({"id": id, "latex": source})).unwrap(); + assert!(matches!(equation(&t, id).math.get(&source), Some(Ok(_))), "editing lays it out"); +} + +#[test] +fn ids_stay_unique_when_a_file_used_the_largest_id() { + // A workbook (from a JSON file, say) whose shape has id u32::MAX: new equations and the + // objects of a copied sheet still get ids no other object has. + let mut s = s(); + let first = insert(&mut s, json!({"latex": "x", "cell": "A1"})); + let mut wb = (*s.doc().unwrap().wb).clone(); + if let Some(sh) = wb.sheet_mut(0) { + sh.shapes.iter_mut().filter(|x| x.id == first).for_each(|x| x.id = u32::MAX); + } + let mut t = Session::new(); + t.add_document(crate::DocState::new(wb, None, "Book".into(), crate::Trust::FromFile)); + let a = insert(&mut t, json!({"latex": "y", "cell": "C1"})); + let b = insert(&mut t, json!({"latex": "z", "cell": "E1"})); + t.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &t.doc().unwrap().wb; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| sh.shapes.iter().map(|x| x.id)).collect(); + assert_eq!(ids.len(), 6, "three equations on each sheet"); + assert!(a != u32::MAX && b != u32::MAX && a != b, "{a} {b}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 6, "every id is distinct: {ids:?}"); +} diff --git a/crates/engine/src/tests/objects.rs b/crates/engine/src/tests/objects.rs new file mode 100644 index 0000000000..2274f04131 --- /dev/null +++ b/crates/engine/src/tests/objects.rs @@ -0,0 +1,476 @@ +//! Floating objects of every kind: found, moved, listed, stacked and deleted by `{kind, id}`. + +use gridcraft_core::CellRef; +use gridcraft_model::{Anchor, AnchorMode, ObjKind, ObjRef, Sheet}; +use serde_json::json; + +use super::s; +use crate::Session; + +fn at(a: &str) -> CellRef { + CellRef::parse(a).unwrap() +} + +fn sheet(s: &Session, i: usize) -> &Sheet { + s.doc().unwrap().wb.sheet(i).unwrap() +} + +fn id_of(v: &serde_json::Value, key: &str) -> u32 { + v[key].as_u64().unwrap() as u32 +} + +/// A table with one object of each kind on the first sheet: a chart, a picture, a shape, a +/// slicer and an equation, in `ObjKind::ALL` order. +fn every_kind(s: &mut Session) -> [ObjRef; 5] { + s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Qty"], ["East", 3], ["West", 5], ["East", 2], ["North", 8]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:B5", "name": "Sales"})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "B1:B5", "type": "column", "at": "D2"})).unwrap(), "chart"); + let image = super::add_image(s, "D18", AnchorMode::MoveAndSize); + let shape = id_of(&s.execute("insert.shape", json!({"kind": "ellipse", "at": "H18"})).unwrap(), "shape"); + s.execute("selection.set", json!({"cell": "A2"})).unwrap(); + let slicer = id_of(&s.execute("insert.slicer", json!({"column": "Region", "at": "L2"})).unwrap(), "slicer"); + let equation = id_of(&s.execute("insert.equation", json!({"latex": "x^2", "cell": "L18"})).unwrap(), "equation"); + [ + ObjRef::new(ObjKind::Chart, chart), + ObjRef::new(ObjKind::Image, image), + ObjRef::new(ObjKind::Shape, shape), + ObjRef::new(ObjKind::Slicer, slicer), + ObjRef::new(ObjKind::Equation, equation), + ] +} + +#[test] +fn every_kind_is_found_moved_and_deleted_by_kind_and_id() { + let mut s = s(); + let objs = every_kind(&mut s); + for o in objs { + assert_eq!(sheet(&s, 0).object_ref(o.id), Some(o), "the id finds its kind"); + assert_eq!(ObjKind::parse(o.kind.name()), Some(o.kind)); + s.execute("object.move", json!({"kind": o.kind.name(), "id": o.id, "at": "M20", "width": 50, "height": 30})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert_eq!((a.cell, a.width, a.height), (at("M20"), 50.0, 30.0)); + s.execute("object.setAnchorMode", json!({"kind": o.kind.name(), "id": o.id, "mode": "absolute"})).unwrap(); + assert_eq!(sheet(&s, 0).object_anchor(o).unwrap().mode, AnchorMode::Absolute); + } + // An equation is a shape too; a plain shape is not an equation. + assert!(sheet(&s, 0).has_object(ObjRef::new(ObjKind::Shape, objs[4].id))); + assert!(s.execute("object.delete", json!({"kind": "equation", "id": objs[2].id})).is_err()); + // A kind that does not match the id, an unknown id or kind, and a missing kind are refused. + assert!(s.execute("object.delete", json!({"kind": "slicer", "id": objs[0].id})).is_err()); + assert!(s.execute("object.delete", json!({"kind": "chart", "id": 9999})).is_err()); + assert!(s.execute("object.delete", json!({"kind": "widget", "id": objs[0].id})).is_err()); + assert!(s.execute("object.delete", json!({"id": objs[0].id})).is_err(), "kind is required"); + for (n, o) in objs.into_iter().enumerate() { + let out = s.execute("object.delete", json!({"kind": o.kind.name(), "id": o.id})).unwrap(); + assert_eq!(out["deleted"], json!({"kind": o.kind.name(), "id": o.id})); + assert!(!sheet(&s, 0).has_object(o)); + for later in &objs[n + 1..] { + assert!(sheet(&s, 0).has_object(*later), "deleting {o:?} leaves {later:?}"); + } + } + // One undo step per delete brings the equation back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(sheet(&s, 0).has_object(objs[4])); +} + +#[test] +fn selection_pane_lists_and_stacks_slicers() { + let mut s = s(); + let objs = every_kind(&mut s); + let second = id_of(&s.execute("insert.slicer", json!({"column": "Qty", "at": "P2"})).unwrap(), "slicer"); + let list = s.execute("arrange.selectionPane", json!({})).unwrap(); + let items = list.as_array().unwrap(); + let kinds: Vec<&str> = items.iter().map(|o| o["kind"].as_str().unwrap()).collect(); + for k in ObjKind::ALL { + assert!(kinds.contains(&k.name()), "{k:?} listed in {kinds:?}"); + } + assert_eq!(kinds.last(), Some(&"slicer"), "slicers stack on top"); + let names: Vec<&str> = items.iter().map(|o| o["name"].as_str().unwrap()).collect(); + assert!(names.contains(&"Region") && names.contains(&"Qty"), "{names:?}"); + assert_eq!(sheet(&s, 0).slicers.first().map(|c| c.id), Some(objs[3].id)); + s.execute("arrange.sendBackward", json!({"kind": "slicer", "id": second, "toBack": true})).unwrap(); + assert_eq!(sheet(&s, 0).slicers.first().map(|c| c.id), Some(second)); +} + +#[test] +fn hostile_object_params_are_refused() { + let mut s = s(); + let objs = every_kind(&mut s); + for p in [ + json!({}), + json!({"kind": "chart"}), + json!({"kind": "chart", "id": -1}), + json!({"kind": "chart", "id": u64::MAX}), + json!({"kind": 7, "id": objs[0].id}), + json!({"kind": null, "id": objs[0].id}), + ] { + for cmd in ["object.delete", "object.move", "object.setAnchorMode"] { + assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p}"); + } + } + let o = objs[3]; + s.execute("object.move", json!({"kind": o.kind.name(), "id": o.id, "dx": 1e300, "dy": -1e300, "width": 1e300, "height": -5})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert!(a.dx.is_finite() && a.dy.is_finite() && a.width <= 10000.0 && a.height >= 0.0, "{a:?}"); +} + +fn cell_of(s: &Session, o: ObjRef) -> String { + sheet(s, 0).object_anchor(o).unwrap().cell.a1() +} + +#[test] +fn every_kind_follows_row_and_column_edits_and_sorts() { + let mut s = s(); + let objs = every_kind(&mut s); + // Anchors: chart D2, picture D18, shape H18, slicer L2, equation L18. + s.execute("object.setAnchorMode", json!({"kind": "shape", "id": objs[2].id, "mode": "absolute"})).unwrap(); + let cells = |s: &Session| objs.map(|o| cell_of(s, o)); + assert_eq!(cells(&s), ["D2", "D18", "H18", "L2", "L18"]); + s.execute("home.insertRows", json!({"rows": "10:11"})).unwrap(); + assert_eq!(cells(&s), ["D2", "D20", "H18", "L2", "L20"], "rows inserted above move the objects below them; an absolute shape stays"); + s.execute("home.insertColumns", json!({"cols": "C:C"})).unwrap(); + assert_eq!(cells(&s), ["E2", "E20", "H18", "M2", "M20"]); + s.execute("home.deleteColumns", json!({"cols": "C:C"})).unwrap(); + s.execute("home.deleteRows", json!({"rows": "10:11"})).unwrap(); + assert_eq!(cells(&s), ["D2", "D18", "H18", "L2", "L18"]); + // Sorting moves a picture anchored inside the sorted block with its row. + s.execute("range.setValues", json!({"range": "T1", "values": [["k"], [3], [1], [2]]})).unwrap(); + let pic = ObjRef::new(ObjKind::Image, super::add_image(&mut s, "T2", AnchorMode::MoveAndSize)); + s.execute("selection.set", json!({"range": "T1:T4"})).unwrap(); + s.execute("data.sortAscending", json!({"header": true, "column": "T"})).unwrap(); + assert_eq!(cell_of(&s, pic), "T4", "the row holding 3 sorts last"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(cell_of(&s, pic), "T2"); +} + +/// A picture at `cell` with anchor `mode`, offset `(dx, dy)` and size `(width, height)`, added +/// straight to the model like `add_image`, so a sort that follows is the only step to undo. +fn picture(s: &mut Session, cell: &str, mode: AnchorMode, dx: f32, dy: f32, width: f32, height: f32) -> ObjRef { + let id = super::add_image(s, cell, mode); + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + if let Some(img) = wb.sheet_mut(0).unwrap().images.iter_mut().find(|i| i.id == id) { + img.anchor = Anchor { dx, dy, width, height, ..img.anchor }; + } + ObjRef::new(ObjKind::Image, id) +} + +/// The anchor of `o` as (cell, dx, dy, width, height). +fn anchor_of(s: &Session, o: ObjRef) -> (String, f32, f32, f32, f32) { + let a = sheet(s, 0).object_anchor(o).unwrap(); + (a.cell.a1(), a.dx, a.dy, a.width, a.height) +} + +/// Sorting rows under a picture follows its anchor mode, as Excel's "Move and size with cells", +/// "Move but don't size with cells" and "Don't move or size with cells" do. +#[test] +fn sorting_rows_under_a_picture_follows_its_anchor_mode() { + let mut s = s(); + // Rows 2..5 hold 3, 1, 4, 2; sorted ascending they read 1, 2, 3, 4, so row 2 moves to row 4, + // row 3 to row 2, row 4 to row 5 and row 5 to row 3. Default rows are 20 pt tall. + s.execute("range.setValues", json!({"range": "A1", "values": [["k"], [3], [1], [4], [2]]})).unwrap(); + // Three pictures inside one row each (3 pt down, 12 pt tall), one per anchor mode. + let sized = picture(&mut s, "A2", AnchorMode::MoveAndSize, 5.0, 3.0, 30.0, 12.0); + let moved = picture(&mut s, "A3", AnchorMode::MoveOnly, 5.0, 3.0, 30.0, 12.0); + let pinned = picture(&mut s, "A4", AnchorMode::Absolute, 5.0, 3.0, 30.0, 12.0); + // A "move and size" picture spanning rows 2 and 3: its top is 10 pt into row 2 (y 30) and + // its bottom 15 pt into row 3 (y 55). The sort puts row 3 above row 2. + let tall = picture(&mut s, "A2", AnchorMode::MoveAndSize, 5.0, 10.0, 30.0, 25.0); + let before: Vec<_> = [sized, moved, pinned, tall].iter().map(|&o| anchor_of(&s, o)).collect(); + s.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + s.execute("data.sortAscending", json!({"header": true, "column": "A"})).unwrap(); + assert_eq!( + anchor_of(&s, sized), + ("A4".into(), 5.0, 3.0, 30.0, 12.0), + "move and size: travels with row 2 to row 4, re-fitted to the same 20 pt row" + ); + assert_eq!(anchor_of(&s, moved), ("A2".into(), 5.0, 3.0, 30.0, 12.0), "move only: travels with row 3 to row 2 at its own size"); + assert_eq!(anchor_of(&s, pinned), ("A4".into(), 5.0, 3.0, 30.0, 12.0), "absolute: stays while the cells move under it"); + // The tall picture's bottom row now sorts above its top row, so there is nothing to stretch + // it between: it travels with its top-left row and keeps its size instead of collapsing. + assert_eq!(anchor_of(&s, tall), ("A4".into(), 5.0, 10.0, 30.0, 25.0), "two rows swapped: moves with its top row at its old size"); + s.execute("edit.undo", json!({})).unwrap(); + let after: Vec<_> = [sized, moved, pinned, tall].iter().map(|&o| anchor_of(&s, o)).collect(); + assert_eq!(after, before, "undo restores every anchor"); +} + +/// A sort by columns follows the anchor mode the same way. +#[test] +fn sorting_columns_under_a_picture_follows_its_anchor_mode() { + let mut s = s(); + // Row 10 holds a header in A and 3, 1, 2 in B..D; sorted ascending, column B moves to D, + // C to B and D to C. Default columns are 64 pt wide. + s.execute("range.setValues", json!({"range": "A10", "values": [["k", 3, 1, 2]]})).unwrap(); + let sized = picture(&mut s, "B10", AnchorMode::MoveAndSize, 5.0, 3.0, 30.0, 12.0); + let moved = picture(&mut s, "C10", AnchorMode::MoveOnly, 5.0, 3.0, 30.0, 12.0); + let pinned = picture(&mut s, "D10", AnchorMode::Absolute, 5.0, 3.0, 30.0, 12.0); + // A "move and size" picture spanning columns B and C: from x 104 (40 pt into B) to x 154 + // (26 pt into C). The sort puts column C before column B. + let wide = picture(&mut s, "B10", AnchorMode::MoveAndSize, 40.0, 3.0, 50.0, 12.0); + let before: Vec<_> = [sized, moved, pinned, wide].iter().map(|&o| anchor_of(&s, o)).collect(); + s.execute("data.sort", json!({"range": "A10:D10", "header": true, "orientation": "columns", "keys": [{"row": 10}]})).unwrap(); + assert_eq!(anchor_of(&s, sized), ("D10".into(), 5.0, 3.0, 30.0, 12.0), "move and size: travels with column B to D at the same width"); + assert_eq!(anchor_of(&s, moved), ("B10".into(), 5.0, 3.0, 30.0, 12.0), "move only: travels with column C to B at its own size"); + assert_eq!(anchor_of(&s, pinned), ("D10".into(), 5.0, 3.0, 30.0, 12.0), "absolute: stays"); + assert_eq!(anchor_of(&s, wide), ("D10".into(), 40.0, 3.0, 50.0, 12.0), "two columns swapped: moves with its left column at its old size"); + s.execute("edit.undo", json!({})).unwrap(); + let after: Vec<_> = [sized, moved, pinned, wide].iter().map(|&o| anchor_of(&s, o)).collect(); + assert_eq!(after, before, "undo restores every anchor"); +} + +#[test] +fn slicers_follow_inserted_rows_like_other_objects() { + let mut s = s(); + let objs = every_kind(&mut s); + s.execute("home.insertRows", json!({"rows": "1:2"})).unwrap(); + assert_eq!(cell_of(&s, objs[3]), "L4"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(cell_of(&s, objs[3]), "L2"); +} + +#[test] +fn chart_series_follow_cut_moves_renames_and_sheet_deletes() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[3], [5], [2], [8]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:A4", "type": "column"})).unwrap(), "chart"); + let values = |s: &Session| sheet(s, 0).charts.iter().find(|c| c.id == chart).map(|c| c.series[0].values.clone()).unwrap_or_default(); + s.execute("edit.cut", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert!(values(&s).contains("$F$2:$F$5"), "a cut-move takes the series with the cells: {}", values(&s)); + s.execute("home.insertSheet", json!({"name": "Other"})).unwrap(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts[0].series[0].values = "Other!$A$1:$A$3".into(); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Inputs"})).unwrap(); + assert_eq!(values(&s), "Inputs!$A$1:$A$3"); + s.execute("home.deleteSheet", json!({"sheet": 1})).unwrap(); + assert!(values(&s).contains("#REF!"), "a series into a deleted sheet becomes #REF!: {}", values(&s)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(values(&s), "Inputs!$A$1:$A$3"); +} + +#[test] +fn a_copied_sheet_gives_its_objects_fresh_ids() { + let mut s = s(); + let objs = every_kind(&mut s); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let ids_of = |sh: &Sheet| -> Vec { + sh.charts + .iter() + .map(|c| c.id) + .chain(sh.images.iter().map(|c| c.id)) + .chain(sh.shapes.iter().map(|c| c.id)) + .chain(sh.slicers.iter().map(|c| c.id)) + .collect() + }; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| ids_of(sh)).collect(); + assert_eq!(ids.len(), 2 * objs.len()); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 2 * objs.len(), "every object id stays unique across the workbook"); + let copy = sheet(&s, 1); + let mut kinds: Vec<&str> = ids_of(copy).into_iter().filter_map(|id| copy.object_ref(id)).map(|o| o.kind.name()).collect(); + let mut want: Vec<&str> = objs.iter().map(|o| o.kind.name()).collect(); + kinds.sort_unstable(); + want.sort_unstable(); + assert_eq!(kinds, want, "the copies keep their kinds"); + assert!(s.doc().unwrap().wb.next_object_id() > *ids.last().unwrap_or(&0)); +} + +#[test] +fn bubble_sizes_follow_edits_like_the_other_series_references() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 3, 10], [2, 5, 20], [3, 2, 30]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:B3", "type": "bubble"})).unwrap(), "chart"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap().series[0] + .bubble_sizes = Some("Sheet1!$C$1:$C$3".into()); + let sizes = |s: &Session| sheet(s, 0).charts.iter().find(|c| c.id == chart).and_then(|c| c.series[0].bubble_sizes.clone()).unwrap_or_default(); + s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap(); + assert_eq!(sizes(&s), "Sheet1!$C$2:$C$4", "an inserted row moves the bubble sizes with their cells"); + s.execute("edit.cut", json!({"range": "C2:C4"})).unwrap(); + s.execute("edit.paste", json!({"at": "F2"})).unwrap(); + assert_eq!(sizes(&s), "Sheet1!$F$2:$F$4", "a cut-move takes the bubble sizes with the cells"); + s.execute("sheet.rename", json!({"sheet": 0, "name": "Data"})).unwrap(); + assert_eq!(sizes(&s), "Data!$F$2:$F$4", "a renamed sheet is renamed in the bubble sizes"); +} + +/// A file can carry an object with the largest id. New objects and a copied sheet's objects then +/// take free ids instead of the largest one again, so `{kind, id}` still names one object. +#[test] +fn object_ids_stay_unique_when_a_file_used_the_largest_id() { + let mut s = s(); + let first = id_of(&s.execute("insert.shape", json!({"kind": "rectangle", "at": "B2"})).unwrap(), "shape"); + // The file's shape carries the largest id (set on the model, as a loaded file would). + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().shapes.iter_mut().find(|o| o.id == first).unwrap().id = u32::MAX; + let second = id_of(&s.execute("insert.shape", json!({"kind": "ellipse", "at": "D2"})).unwrap(), "shape"); + let third = id_of(&s.execute("insert.shape", json!({"kind": "triangle", "at": "F2"})).unwrap(), "shape"); + assert!(second != u32::MAX && third != u32::MAX && second != third, "new shapes take free ids, not the largest again: {second}, {third}"); + s.execute("sheet.move", json!({"sheet": 0, "to": 1, "copy": true})).unwrap(); + let wb = &s.doc().unwrap().wb; + let mut ids: Vec = wb.sheets.iter().flat_map(|sh| sh.shapes.iter().map(|o| o.id)).collect(); + assert_eq!(ids.len(), 6); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 6, "every shape id is distinct across both sheets"); +} + +/// A file's anchors are not held to the 10,000 points `object.move` gives a new size. A picture +/// a file made 12,000 wide keeps that width when it is moved, shrinks by what a resize asks +/// (11,990 stays 11,990, no jump to 10,000) and never grows further; a dimension the file kept +/// within the limit is still capped there. +#[test] +fn an_oversized_imported_object_keeps_its_size_when_moved_and_shrinks_only_by_a_resize() { + let mut s = s(); + let image = super::add_image(&mut s, "B2", AnchorMode::MoveOnly); + // The file's picture is 12,000 by 300: set on the model, then written and read back as a file. + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let a = wb.sheet_mut(0).unwrap().object_anchor_mut(ObjRef::new(ObjKind::Image, image)).unwrap(); + a.width = 12_000.0; + a.height = 300.0; + } + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + s.execute("file.open", json!({"name": "wide.xlsx", "base64": saved["base64"]})).unwrap(); + let o = ObjRef::new(ObjKind::Image, sheet(&s, 0).images[0].id); + let size = |s: &Session| { + let a = sheet(s, 0).object_anchor(o).unwrap(); + (a.width.round(), a.height.round()) + }; + assert_eq!(size(&s), (12_000.0, 300.0), "the reader keeps the file's size"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "at": "D5", "dx": 3, "dy": 4})).unwrap(); + let a = sheet(&s, 0).object_anchor(o).unwrap(); + assert_eq!((a.cell, a.dx, a.dy), (at("D5"), 3.0, 4.0)); + assert_eq!(size(&s), (12_000.0, 300.0), "a move without a size keeps the file's size"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 12_010})).unwrap(); + assert_eq!(size(&s), (12_000.0, 300.0), "the object does not grow past what the file gave"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 11_990})).unwrap(); + assert_eq!(size(&s), (11_990.0, 300.0), "a resize shrinks by what it asks, with no jump to 10,000"); + s.execute("object.move", json!({"kind": "image", "id": o.id, "width": 50_000, "height": 50_000})).unwrap(); + assert_eq!(size(&s), (11_990.0, 10_000.0), "hostile sizes are capped: at the current width, and at 10,000 for a height the file kept within it"); +} + +/// `chart.set` follows the same rule: the Format Chart pane's Size fields send the unchanged +/// dimension back with the edited one, so a chart a file made 12,000 wide keeps that width when +/// its height is edited, shrinks by what is asked and never grows further. +#[test] +fn chart_set_keeps_a_chart_size_a_file_made_larger_than_the_limit() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap(); + let chart = id_of(&s.execute("insert.chart", json!({"range": "A1:A3", "type": "column", "at": "C2"})).unwrap(), "chart"); + // The file's chart is 12,000 wide (set on the model, as a loaded file would). + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + wb.sheet_mut(0).unwrap().charts.iter_mut().find(|c| c.id == chart).unwrap().anchor.width = 12_000.0; + let size = |s: &Session| { + let c = sheet(s, 0).charts.iter().find(|c| c.id == chart).unwrap(); + (c.anchor.width, c.anchor.height) + }; + s.execute("chart.set", json!({"chart": chart, "width": 12_000, "height": 250})).unwrap(); + assert_eq!(size(&s), (12_000.0, 250.0), "the unchanged width sent back with a new height stays"); + s.execute("chart.set", json!({"chart": chart, "width": 11_990})).unwrap(); + assert_eq!(size(&s), (11_990.0, 250.0), "a resize shrinks by what it asks"); + s.execute("chart.set", json!({"chart": chart, "width": 50_000, "height": 50_000})).unwrap(); + assert_eq!(size(&s), (11_990.0, 10_000.0), "hostile sizes are capped at the current width and at 10,000"); +} + +#[test] +fn arrange_and_align_match_a_shape_id_to_its_kind() { + // `arrange.*` and `arrange.align` under `kind: "equation"` act on equations only: an + // ordinary shape's id given as an equation is refused by `arrange` and left in place by + // `align`, as `object.delete` refuses it. An equation is a shape too, so its id works under + // `shape`, as for the other object commands; an unknown kind, and an id of no object of the + // kind, are refused instead of acting on whatever shape has the id. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let order = |s: &Session| -> Vec { sheet(s, 0).shapes.iter().map(|c| c.id).collect() }; + assert_eq!(order(&s), vec![shape.id, equation.id]); + assert!(s.execute("arrange.bringForward", json!({"kind": "equation", "id": shape.id, "toFront": true})).is_err()); + assert_eq!(order(&s), vec![shape.id, equation.id], "the shape is not reordered as an equation"); + s.execute("arrange.sendBackward", json!({"kind": "equation", "id": equation.id, "toBack": true})).unwrap(); + assert_eq!(order(&s), vec![equation.id, shape.id]); + s.execute("arrange.bringForward", json!({"kind": "shape", "id": equation.id, "toFront": true})).unwrap(); + assert_eq!(order(&s), vec![shape.id, equation.id], "an equation is a shape too"); + assert!(s.execute("arrange.bringForward", json!({"kind": "widget", "id": shape.id})).is_err()); + assert!(s.execute("arrange.bringForward", json!({"kind": "chart", "id": 9999})).is_err()); + assert!(s.execute("arrange.bringForward", json!({"kind": "shape", "id": objs[0].id})).is_err(), "a chart's id is not a shape"); + // Align: the shape's id given as an equation is refused and nothing moves; the two equations + // line up on their own. + let second = ObjRef::new(ObjKind::Equation, id_of(&s.execute("insert.equation", json!({"latex": "y", "cell": "B30"})).unwrap(), "equation")); + let before = (anchor_of(&s, shape), anchor_of(&s, equation)); + assert!(s.execute("arrange.align", json!({"kind": "equation", "ids": [shape.id, equation.id, second.id], "align": "left"})).is_err()); + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation)), before, "nothing is aligned with a refused id"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id, second.id], "align": "left"})).unwrap(); + let (a, b) = (sheet(&s, 0).object_anchor(equation).unwrap(), sheet(&s, 0).object_anchor(second).unwrap()); + assert_eq!((a.cell.col, a.dx), (b.cell.col, b.dx), "the equations line up"); + assert!(s.execute("arrange.align", json!({"kind": "widget", "ids": [shape.id, equation.id], "align": "left"})).is_err()); +} + +#[test] +fn arrange_refuses_a_kind_that_is_present_but_not_a_name() { + // `kind` is `shape` only when the parameter is absent: `null`, a number or another non-name + // is refused, so a shape's id is not reordered or aligned under it. The `object.*` commands + // refuse the same values, their kind being required. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let order = |s: &Session| -> Vec { sheet(s, 0).shapes.iter().map(|c| c.id).collect() }; + let before = (order(&s), anchor_of(&s, shape)); + for kind in [json!(null), json!(7), json!(["shape"]), json!({"kind": "shape"}), json!(true)] { + assert!(s.execute("arrange.bringForward", json!({"kind": kind, "id": shape.id, "toFront": true})).is_err(), "{kind}"); + assert!(s.execute("arrange.align", json!({"kind": kind, "ids": [shape.id, equation.id], "align": "left"})).is_err(), "{kind}"); + assert!(s.execute("object.move", json!({"kind": kind, "id": shape.id, "at": "A1"})).is_err(), "{kind}"); + } + assert_eq!((order(&s), anchor_of(&s, shape)), before, "nothing moved"); + // Absent, the kind is `shape`, as before. + s.execute("arrange.bringForward", json!({"id": shape.id, "toFront": true})).unwrap(); + assert_eq!(order(&s).last(), Some(&shape.id)); +} + +#[test] +fn align_refuses_an_id_that_is_not_an_object_of_the_kind() { + // `arrange.align` and `arrange.group` refuse an id in `ids` that is not an object of the + // kind, or not a number, as `arrange` and the `object.*` commands refuse it, instead of + // aligning the rest and reporting success; nothing moves. With fewer than two ids they + // change nothing and succeed. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let second = ObjRef::new(ObjKind::Equation, id_of(&s.execute("insert.equation", json!({"latex": "y", "cell": "B30"})).unwrap(), "equation")); + let before = (anchor_of(&s, shape), anchor_of(&s, equation), anchor_of(&s, second)); + for ids in [ + json!([shape.id, equation.id, second.id]), + json!([equation.id, second.id, 9999]), + json!([equation.id, second.id, -1]), + json!([equation.id, second.id, "x"]), + json!([equation.id, second.id, 1e12]), + json!([equation.id, second.id, null]), + ] { + assert!(s.execute("arrange.align", json!({"kind": "equation", "ids": ids, "align": "left"})).is_err(), "{ids}"); + assert!(s.execute("arrange.group", json!({"kind": "equation", "ids": ids})).is_err(), "{ids}"); + } + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation), anchor_of(&s, second)), before, "nothing moved"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id], "align": "left"})).unwrap(); + s.execute("arrange.align", json!({"kind": "equation", "align": "left"})).unwrap(); + assert_eq!(anchor_of(&s, equation), before.1, "fewer than two ids change nothing"); + s.execute("arrange.align", json!({"kind": "equation", "ids": [equation.id, second.id], "align": "left"})).unwrap(); + let (a, b) = (sheet(&s, 0).object_anchor(equation).unwrap(), sheet(&s, 0).object_anchor(second).unwrap()); + assert_eq!((a.cell.col, a.dx), (b.cell.col, b.dx), "the equations line up"); +} + +#[test] +fn align_refuses_ids_that_are_not_an_array() { + // `ids` may be absent (nothing to align) but, present, must be an array of object ids: `null`, + // a number, a string or an object is refused by `arrange.align` and `arrange.group`, and + // nothing moves. + let mut s = s(); + let objs = every_kind(&mut s); + let (shape, equation) = (objs[2], objs[4]); + let before = (anchor_of(&s, shape), anchor_of(&s, equation)); + for ids in [json!(null), json!(7), json!("x"), json!({"ids": [1]})] { + assert!(s.execute("arrange.align", json!({"kind": "shape", "ids": ids, "align": "left"})).is_err(), "{ids}"); + assert!(s.execute("arrange.group", json!({"kind": "shape", "ids": ids})).is_err(), "{ids}"); + } + s.execute("arrange.align", json!({"kind": "shape", "align": "left"})).unwrap(); + s.execute("arrange.group", json!({"kind": "shape"})).unwrap(); + assert_eq!((anchor_of(&s, shape), anchor_of(&s, equation)), before, "nothing moved"); +} diff --git a/crates/engine/src/tests/python_cells.rs b/crates/engine/src/tests/python_cells.rs new file mode 100644 index 0000000000..63cf1d92b8 --- /dev/null +++ b/crates/engine/src/tests/python_cells.rs @@ -0,0 +1,532 @@ +//! Python cells under edits: what keeps, moves, rewrites or removes their code. + +use std::sync::Arc; + +use gridcraft_core::{CellRef, Value}; +use gridcraft_model::{Cell, PyCode}; +use serde_json::json; + +use super::s; +use crate::Session; + +/// Makes `cell` on sheet `sheet` a Python cell with `code` and a cached value. +fn plant(s: &mut Session, sheet: usize, cell: &str, code: &str) { + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + let sh = wb.sheet_mut(sheet).unwrap(); + let at = CellRef::parse(cell).unwrap(); + let style = sh.style_id(at); + sh.set_cell(at, Cell { value: Value::Number(1.0), formula: None, style, py: Some(Arc::new(PyCode::new(code))) }); + d.wb = Arc::new(wb); +} + +fn code(s: &Session, sheet: usize, cell: &str) -> Option { + let d = s.doc().unwrap(); + d.wb.sheet(sheet).unwrap().cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_ref()).map(|p| p.code.clone()) +} + +#[test] +fn typing_py_formulas_points_to_python_set() { + let mut s = s(); + let e = s.execute("cell.set", json!({"cell": "A1", "input": "=PY(\"1+1\",0)"})).unwrap_err(); + assert!(e.to_string().contains("python.set"), "{e}"); + assert!(s.execute("cell.set", json!({"cell": "A1", "input": "=py"})).is_err()); + // Other functions starting with PY are not affected. + s.execute("cell.set", json!({"cell": "A2", "input": "=PI()"})).unwrap(); +} + +#[test] +fn entering_or_clearing_a_python_cell_removes_its_code() { + let mut s = s(); + plant(&mut s, 0, "A1", "1 + 1"); + plant(&mut s, 0, "A2", "2 + 2"); + plant(&mut s, 0, "A3", "3 + 3"); + let got = s.execute("cell.get", json!({"cell": "A1"})).unwrap(); + assert_eq!(got["input"], "1 + 1"); + assert_eq!(got["python"]["code"], "1 + 1"); + assert_eq!(got["python"]["output"], "value"); + s.execute("cell.set", json!({"cell": "A1", "input": "hello"})).unwrap(); + assert_eq!(code(&s, 0, "A1"), None); + s.execute("edit.clearFormats", json!({"range": "A2"})).unwrap(); + assert_eq!(code(&s, 0, "A2").as_deref(), Some("2 + 2"), "clearing formats keeps the code"); + s.execute("edit.clearContents", json!({"range": "A2"})).unwrap(); + assert_eq!(code(&s, 0, "A2"), None); + s.execute("edit.clearAll", json!({"range": "A3"})).unwrap(); + assert_eq!(code(&s, 0, "A3"), None); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(code(&s, 0, "A3").as_deref(), Some("3 + 3"), "undo brings the code back"); +} + +#[test] +fn copy_fill_and_sort_carry_the_code_and_paste_values_drops_it() { + let mut s = s(); + plant(&mut s, 0, "A1", "xl('B1') * 2"); + s.execute("edit.copy", json!({"range": "A1"})).unwrap(); + s.execute("edit.paste", json!({"at": "C1"})).unwrap(); + assert_eq!(code(&s, 0, "C1").as_deref(), Some("xl('B1') * 2"), "the code is copied as it is"); + s.execute("edit.pasteSpecial", json!({"at": "D1", "what": "values"})).unwrap(); + assert_eq!(code(&s, 0, "D1"), None); + assert_eq!(super::v(&s, "D1"), Value::Number(1.0), "the cached value is pasted"); + s.execute("edit.fillDown", json!({"range": "A1:A3"})).unwrap(); + assert_eq!(code(&s, 0, "A3").as_deref(), Some("xl('B1') * 2")); + // Sorting moves Python cells with their rows. + s.execute("range.setValues", json!({"range": "E1", "values": [[3], [1], [2]]})).unwrap(); + plant(&mut s, 0, "F1", "'three'"); + plant(&mut s, 0, "F2", "'one'"); + s.execute("data.sort", json!({"range": "E1:F3", "keys": [{"column": "E"}]})).unwrap(); + assert_eq!(code(&s, 0, "F1").as_deref(), Some("'one'")); + assert_eq!(code(&s, 0, "F3").as_deref(), Some("'three'")); +} + +#[test] +fn xl_references_follow_inserts_moves_and_renames() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + plant(&mut s, 0, "C5", &format!("a = xl(\"A1:A3\")\nb = xl('{other}!B2', headers=True)\nc = xl(dynamic)\n# xl(\"A1\") stays in comments")); + s.execute("home.insertRows", json!({"rows": "2:2"})).unwrap(); + let c = code(&s, 0, "C6").unwrap(); + assert!(c.starts_with("a = xl(\"A1:A4\")\n"), "{c}"); + assert!(c.contains(&format!("xl('{other}!B2', headers=True)")), "{c}"); + assert!(c.contains("# xl(\"A1\") stays"), "{c}"); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Data"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().contains("xl('Data!B2', headers=True)")); + // Cutting the cells a reference names moves the reference with them. + s.execute("edit.cut", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.paste", json!({"at": "H1"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().starts_with("a = xl(\"H1:H4\")"), "{:?}", code(&s, 0, "C6")); + // Deleting the referenced cells leaves #REF!, which fails when the code runs. + // The selection is elsewhere, so only the named column goes. + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("home.deleteColumns", json!({"cols": "H:H"})).unwrap(); + assert!(code(&s, 0, "C6").unwrap().starts_with("a = xl(\"#REF!\")"), "{:?}", code(&s, 0, "C6")); +} + +#[test] +fn a_rename_to_a_name_that_needs_quotes_rewrites_single_quoted_references() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + plant(&mut s, 0, "A1", &format!("a = xl('{other}!B2')\nb = xl(\"{other}!C3\")")); + s.execute("sheet.rename", json!({"sheet": 1, "name": "Q4 2026"})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), "a = xl(\"'Q4 2026'!B2\")\nb = xl(\"'Q4 2026'!C3\")"); + // A name with both quotes in it: the literal's own quote is escaped. + s.execute("sheet.rename", json!({"sheet": 1, "name": "Bob's \"Q4\""})).unwrap(); + let c = code(&s, 0, "A1").unwrap(); + assert_eq!(c, "a = xl(\"'Bob''s \\\"Q4\\\"'!B2\")\nb = xl(\"'Bob''s \\\"Q4\\\"'!C3\")"); + let refs: Vec> = gridcraft_model::python::xl_calls(&c).into_iter().map(|x| x.reference).collect(); + assert_eq!(refs, [Some("'Bob''s \"Q4\"'!B2".to_string()), Some("'Bob''s \"Q4\"'!C3".to_string())]); + // And back to a plain name. + s.execute("sheet.rename", json!({"sheet": 1, "name": "Data"})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), "a = xl(\"Data!B2\")\nb = xl(\"Data!C3\")"); +} + +#[test] +fn a_cut_to_another_sheet_keeps_references_on_the_source_sheet() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let (src, dest) = { + let wb = &s.doc().unwrap().wb; + (wb.sheet(0).unwrap().name.clone(), wb.sheet(1).unwrap().name.clone()) + }; + plant(&mut s, 0, "A1", "a = xl(\"B5\")\nb = xl('A2')"); + plant(&mut s, 0, "A2", "1"); + s.execute("edit.cut", json!({"range": "A1:A2"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + s.execute("edit.paste", json!({"at": "C1"})).unwrap(); + // B5 stays on the source sheet; A2 moved with the cut, so it follows to the destination. + assert_eq!(code(&s, 1, "C1").unwrap(), format!("a = xl(\"{src}!B5\")\nb = xl('{dest}!C2')")); + assert_eq!(code(&s, 0, "A1"), None); + // Within one sheet nothing is qualified. + s.execute("edit.cut", json!({"range": "C1"})).unwrap(); + s.execute("edit.paste", json!({"at": "E1"})).unwrap(); + assert_eq!(code(&s, 1, "E1").unwrap(), format!("a = xl(\"{src}!B5\")\nb = xl('{dest}!C2')")); + // A copy to another sheet still carries the code as it is. + plant(&mut s, 0, "A9", "xl(\"B5\")"); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + s.execute("edit.copy", json!({"range": "A9"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + s.execute("edit.paste", json!({"at": "A9"})).unwrap(); + assert_eq!(code(&s, 1, "A9").as_deref(), Some("xl(\"B5\")")); +} + +#[test] +fn goal_seek_and_solver_refuse_to_change_a_python_cell() { + let mut s = s(); + plant(&mut s, 0, "A1", "2"); + s.execute("cell.set", json!({"cell": "B1", "input": "=A1*2"})).unwrap(); + let e = s.execute("data.goalSeek", json!({"set": "B1", "to": 10, "changing": "A1"})).unwrap_err(); + assert!(e.to_string().contains("must contain a value"), "{e}"); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("2"), "the code is kept"); + // The set cell must be a formula: a Python cell isn't one this build can recalculate. + s.execute("cell.set", json!({"cell": "C1", "input": "3"})).unwrap(); + assert!(s.execute("data.goalSeek", json!({"set": "A1", "to": 10, "changing": "C1"})).is_err()); + let e = s.execute("data.solver", json!({"objective": "B1", "goal": "max", "variables": "A1"})).unwrap_err(); + assert!(e.to_string().contains("constants"), "{e}"); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("2")); +} + +#[test] +fn text_to_columns_keeps_a_py_piece_as_text() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "'=PY(\"x\");7"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::text("=PY(\"x\");7")); + s.execute("data.textToColumns", json!({"range": "A1", "delimiters": [";"]})).unwrap(); + // The default text qualifier takes the quotes away, as in Excel. + assert_eq!(super::v(&s, "A1"), Value::text("=PY(x)"), "the piece is kept, not cleared"); + assert_eq!(code(&s, 0, "A1"), None, "and it is not a Python cell"); + assert_eq!(super::v(&s, "B1"), Value::Number(7.0)); +} + +#[test] +fn python_cells_survive_native_json() { + let mut s = s(); + plant(&mut s, 0, "B2", "x = 1\nx"); + let wb = s.doc().unwrap().wb.clone(); + let json = serde_json::to_string(&*wb).unwrap(); + let back: gridcraft_model::Workbook = serde_json::from_str(&json).unwrap(); + let cell = back.sheet(0).unwrap().cell(CellRef::parse("B2").unwrap()).unwrap(); + assert_eq!(cell.py.as_ref().unwrap().code, "x = 1\nx"); + // Cells written before Python existed have no `py` field. + let plain: Cell = serde_json::from_value(json!({"value": {"t": "Number", "v": 2.0}, "formula": null, "style": 0})).unwrap(); + assert!(plain.py.is_none()); + assert!(!serde_json::to_string(&plain).unwrap().contains("py"), "no field is written for ordinary cells"); +} + +#[test] +fn new_errors_parse_and_have_error_type_numbers() { + use gridcraft_core::CellError; + for (text, e) in + [("#PYTHON!", CellError::Python), ("#BUSY!", CellError::Busy), ("#TIMEOUT!", CellError::Timeout), ("#BLOCKED!", CellError::Blocked)] + { + assert_eq!(CellError::parse(text), Some(e)); + assert_eq!(e.as_str(), text); + } + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "=ERROR.TYPE(#BLOCKED!)"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Number(11.0)); + s.execute("cell.set", json!({"cell": "A2", "input": "=ISERROR(#PYTHON!)"})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Bool(true)); +} + +#[test] +fn go_to_special_counts_a_python_cell_as_a_formula_not_a_constant() { + let mut s = s(); + plant(&mut s, 0, "A1", "1 + 1"); + s.execute("cell.set", json!({"cell": "A2", "input": "=1+1"})).unwrap(); + s.execute("cell.set", json!({"cell": "A3", "input": "7"})).unwrap(); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + let r = s.execute("edit.goToSpecial", json!({"kind": "formulas"})).unwrap(); + assert_eq!(r["count"], 2, "{r}"); + assert_eq!(r["selection"], "A1:A2", "{r}"); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + let r = s.execute("edit.goToSpecial", json!({"kind": "constants"})).unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["selection"], "A3", "{r}"); +} + +#[test] +fn a_macro_counts_python_code_as_data_and_a_blocked_spill_as_no_write() { + let mut s = s(); + // F2 shows 1, its cached value: a step that enters 1 there still replaces the code. + plant(&mut s, 0, "F2", "1"); + // H2's code shows #BLOCKED!, as any other new code there would. + s.execute("python.set", json!({"cell": "H2", "code": "'a'"})).unwrap(); + // J2's result spills over J2:J3. A step that writes J3 blocks it, which doesn't write J2. + s.execute("python.set", json!({"cell": "J2", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("J2").unwrap()).unwrap(); + let data = vec![Value::Number(5.0), Value::Number(6.0)]; + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, data).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(super::v(&s, "J3"), Value::Number(6.0)); + super::macros::put( + &mut s, + json!({"name": "Py", "steps": [ + {"command": "cell.set", "params": {"cell": "F2", "input": "1"}}, + {"command": "python.set", "params": {"cell": "H2", "code": "'b'"}}, + {"command": "cell.set", "params": {"cell": "J3", "input": "x"}} + ]}), + ); + let c = s.execute("macro.check", json!({"name": "Py"})).unwrap(); + assert_eq!(c["footprint"]["sheets"][0]["cells"], json!(["F2", "H2", "J3"]), "{c}"); + assert_eq!(c["footprint"]["sheets"][0]["conflicts"], json!(["F2", "H2"]), "{c}"); + let e = s.execute("macro.run", json!({"name": "Py", "onConflict": "fail"})).unwrap_err().to_string(); + assert!(e.contains("F2") && e.contains("H2") && !e.contains("J2"), "{e}"); + assert_eq!(code(&s, 0, "F2").as_deref(), Some("1"), "nothing was changed"); +} + +#[test] +fn replace_edits_a_python_cells_code_and_keeps_it_a_python_cell() { + let mut s = s(); + plant(&mut s, 0, "A1", "x = 1\nx"); + { + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + Arc::make_mut(cell.py.as_mut().unwrap()).object = true; + d.wb = Arc::new(wb); + } + let r = s.execute("edit.replace", json!({"what": "x", "with": "y"})).unwrap(); + assert_eq!(r["replaced"], 1); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("y = 1\ny")); + let d = s.doc().unwrap(); + let cell = d.wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap(); + assert!(cell.py.as_ref().unwrap().object, "the return type is kept"); + assert_eq!(cell.value, Value::Error(gridcraft_core::CellError::Blocked)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("x = 1\nx")); +} + +#[test] +fn replace_leaves_python_code_that_would_no_longer_fit() { + let mut s = s(); + let long = "a".repeat(gridcraft_model::python::MAX_FORMULA_CHARS / 2); + plant(&mut s, 0, "A1", &long); + let r = s.execute("edit.replace", json!({"what": "a", "with": "bb"})).unwrap(); + assert_eq!(r["replaced"], 0); + assert_eq!(r["skipped"], 1); + assert_eq!(code(&s, 0, "A1").as_deref(), Some(long.as_str())); +} + +#[test] +fn a_hidden_python_cell_on_a_protected_sheet_hides_its_code() { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "secret = 1\nsecret"})).unwrap(); + s.execute("python.set", json!({"cell": "B1", "code": "'shown'"})).unwrap(); + s.execute("home.formatCells", json!({"range": "A1", "style": {"protection": {"locked": true, "hidden": true}}})).unwrap(); + let hidden = |s: &Session, a: &str| { + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + crate::display::formula_hidden(&d.wb, sh, CellRef::parse(a).unwrap()) + }; + assert!(!hidden(&s, "A1"), "an unprotected sheet hides nothing"); + s.execute("review.protectSheet", json!({})).unwrap(); + assert!(hidden(&s, "A1"), "Hidden on a protected sheet hides the code, as it hides a formula"); + assert!(!hidden(&s, "B1")); + // Editing it is refused where a formula's would be: the cell is locked. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "2"})).is_err()); + assert_eq!(code(&s, 0, "A1").as_deref(), Some("secret = 1\nsecret")); +} + +#[test] +fn every_merge_keeps_only_the_upper_left_cells_python_code() { + let mut s = s(); + for (cmd, row) in [("home.mergeAcross", 1), ("home.mergeCells", 2), ("home.mergeCenter", 3)] { + plant(&mut s, 0, &format!("A{row}"), "'kept'"); + plant(&mut s, 0, &format!("B{row}"), "'merged away'"); + s.execute(cmd, json!({"range": format!("A{row}:B{row}")})).unwrap(); + assert_eq!(code(&s, 0, &format!("A{row}")).as_deref(), Some("'kept'"), "{cmd}"); + assert_eq!(code(&s, 0, &format!("B{row}")), None, "{cmd}: the hidden cell is no Python cell"); + assert_eq!(super::v(&s, &format!("B{row}")), Value::Empty, "{cmd}"); + } +} + +#[test] +fn unmerging_lets_a_blocked_python_result_spill_again() { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, vec![Value::Number(5.0), Value::Number(6.0)]).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Number(6.0)); + s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Error(gridcraft_core::CellError::Spill), "a merged cell blocks the spill"); + s.execute("home.unmergeCells", json!({"range": "A2:B2"})).unwrap(); + assert_eq!((super::v(&s, "A1"), super::v(&s, "A2")), (Value::Number(5.0), Value::Number(6.0)), "it spills again"); +} + +#[test] +fn save_model_asks_before_it_writes_over_a_python_cell_that_shows_nothing() { + let mut s = s(); + for (cell, input) in [("B1", "=5*A1+4*A2"), ("B2", "=6*A1+4*A2")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + // H2 is a Python cell whose cached value is empty: its code is still content. + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + sh.set_cell( + CellRef::parse("H2").unwrap(), + Cell { value: Value::Empty, formula: None, style: Default::default(), py: Some(Arc::new(PyCode::new("None"))) }, + ); + } + let model = json!({"objective": "B1", "variables": "A1:A2", "constraints": ["B2 <= 24"]}); + let e = s.execute("data.solverSaveModel", json!({"to": "H1", "model": model})).unwrap_err().to_string(); + assert!(e.contains(crate::cmd::analysis::OVERWRITE_ERROR) && e.contains("H2"), "{e}"); + assert_eq!(code(&s, 0, "H2").as_deref(), Some("None"), "nothing was written"); +} + +/// A1 is a Python cell whose kept result `[5, 6]` spills over A1:A2, and B1 reads A2. +pub(super) fn spill_with_a_reader() -> crate::Session { + let mut s = s(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse("A1").unwrap()).unwrap(); + let value = Value::Array(Arc::new(gridcraft_core::Array::new(2, 1, vec![Value::Number(5.0), Value::Number(6.0)]).unwrap())); + Arc::make_mut(cell.py.as_mut().unwrap()).output = + Some(gridcraft_model::PyOutput { value, type_name: "list".into(), preview: String::new(), convertible: true }); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "=SUM(A2)"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(6.0)); + s +} + +#[test] +fn new_python_code_recalculates_the_readers_of_its_old_spill() { + let mut s = spill_with_a_reader(); + s.execute("python.set", json!({"cell": "A1", "code": "[7, 8]"})).unwrap(); + assert_eq!(super::v(&s, "A2"), Value::Empty, "new code has no result yet"); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "B1 read the old spill"); + // The same code again keeps its result, and its spill. + let mut s = spill_with_a_reader(); + s.execute("python.set", json!({"cell": "A1", "code": "[5, 6]"})).unwrap(); + assert_eq!((super::v(&s, "A2"), super::v(&s, "B1")), (Value::Number(6.0), Value::Number(6.0))); +} + +#[test] +fn replace_in_python_code_recalculates_the_readers_of_its_old_spill() { + let mut s = spill_with_a_reader(); + let r = s.execute("edit.replace", json!({"what": "[5,", "with": "[7,"})).unwrap(); + assert_eq!(r["replaced"], 1); + assert_eq!(super::v(&s, "A2"), Value::Empty); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "B1 read the old spill"); +} + +#[test] +fn clearing_pasting_over_or_blocking_a_python_spill_recalculates_its_readers() { + let mut s = spill_with_a_reader(); + s.execute("edit.clearContents", json!({"range": "A1"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "clear"); + let mut s = spill_with_a_reader(); + s.execute("cell.set", json!({"cell": "D1", "input": "9"})).unwrap(); + s.execute("edit.copy", json!({"range": "D1"})).unwrap(); + s.execute("edit.paste", json!({"at": "A1"})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "paste"); + let mut s = spill_with_a_reader(); + s.execute("home.mergeCells", json!({"range": "A2:A3"})).unwrap(); + assert_eq!(super::v(&s, "A1"), Value::Error(gridcraft_core::CellError::Spill)); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "merge"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(6.0), "undo"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(super::v(&s, "B1"), Value::Number(0.0), "redo"); +} + +/// `prefix` and a comment padded to the longest code that still fits in one cell. +fn at_the_limit(prefix: &str) -> String { + let with = |n: usize| format!("{prefix}\n#{}", "x".repeat(n)); + let (mut lo, mut hi) = (0, gridcraft_model::python::MAX_FORMULA_CHARS); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if PyCode::new(&with(mid)).fits() { lo = mid } else { hi = mid - 1 } + } + with(lo) +} + +#[test] +fn an_edit_that_would_make_python_code_too_long_is_refused() { + let mut s = s(); + s.execute("home.insertSheet", json!({})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 0})).unwrap(); + let other = s.doc().unwrap().wb.sheet(1).unwrap().name.clone(); + let refused = |e: crate::EngineError, cell: &str| { + let e = e.to_string(); + assert!(e.contains(&format!("!{cell} longer than Excel's 8192-character")) && e.contains("nothing was changed"), "{e}"); + }; + // A sheet rename that lengthens a reference. + let a1 = at_the_limit(&format!("a = xl(\"{other}!B2\")")); + plant(&mut s, 0, "A1", &a1); + refused(s.execute("sheet.rename", json!({"sheet": 1, "name": "A much longer sheet name"})).unwrap_err(), "A1"); + assert_eq!(code(&s, 0, "A1").unwrap(), a1); + assert_eq!(s.doc().unwrap().wb.sheet(1).unwrap().name, other); + // One of the same length is made. + let same = "Z".repeat(other.chars().count()); + s.execute("sheet.rename", json!({"sheet": 1, "name": same})).unwrap(); + assert_eq!(code(&s, 0, "A1").unwrap(), a1.replace(&other, &same)); + // Code short of the limit still follows each edit. + plant(&mut s, 0, "A7", "d = xl(\"Z1\")"); + s.execute("selection.set", json!({"range": "B10"})).unwrap(); + s.execute("home.insertColumns", json!({"cols": "Y:Y"})).unwrap(); + assert_eq!(code(&s, 0, "A7").unwrap(), "d = xl(\"AA1\")"); + // An inserted column that turns Z1 into AA1. + let a3 = at_the_limit("b = xl(\"Z1\")"); + plant(&mut s, 0, "A3", &a3); + s.execute("cell.set", json!({"cell": "D1", "input": "kept"})).unwrap(); + s.execute("selection.set", json!({"range": "C1"})).unwrap(); + refused(s.execute("home.insertColumns", json!({"cols": "C:C"})).unwrap_err(), "A3"); + assert_eq!(code(&s, 0, "A3").unwrap(), a3); + assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().value(CellRef::parse("D1").unwrap()), Value::text("kept")); + // A cut to another sheet, which qualifies B9 with the source sheet. + let a5 = at_the_limit("c = xl(\"B9\")"); + plant(&mut s, 0, "A5", &a5); + s.execute("edit.cut", json!({"range": "A5"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": 1})).unwrap(); + refused(s.execute("edit.paste", json!({"at": "C1"})).unwrap_err(), "C1"); + assert_eq!(code(&s, 0, "A5").unwrap(), a5); + assert_eq!(code(&s, 1, "C1"), None); +} + +/// Makes `cell` a Python cell whose cached value is empty, as a file's `PY` formula with no cached +/// value reads. +fn plant_empty(s: &mut Session, cell: &str) { + plant(s, 0, cell, "x = 1"); + let d = s.doc_mut().unwrap(); + let mut wb = (*d.wb).clone(); + if let Some(c) = wb.sheet_mut(0).unwrap().cells.get_mut(CellRef::parse(cell).unwrap()) { + c.value = Value::Empty; + } + d.wb = Arc::new(wb); +} + +#[test] +fn python_code_with_an_empty_value_counts_as_content() { + // A report or a PivotTable asks before replacing it. + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Sales"], ["East", 1], ["West", 2], ["East", 3]]})).unwrap(); + plant_empty(&mut s, "D2"); + let report = json!({"tool": "Descriptive Statistics", "range": "B1:B4", "labels": true, "output": "D1"}); + assert!(s.execute("data.analysisToolPak", report).is_err(), "the report asks for overwrite"); + plant_empty(&mut s, "H4"); + let pivot = s.execute("insert.pivotTable", json!({"destination": "Sheet1!H3", "rows": ["Region"], "values": ["Sales"]})); + assert!(pivot.is_err_and(|e| e.to_string().contains("already data"))); + assert_eq!((code(&s, 0, "D2"), code(&s, 0, "H4")), (Some("x = 1".into()), Some("x = 1".into())), "the code is kept"); + // Cells aren't pushed off the sheet over it. + plant_empty(&mut s, "K1048576"); + assert!(s.execute("home.insertCells", json!({"range": "K1", "shift": "down"})).is_err()); + assert_eq!(code(&s, 0, "K1048576"), Some("x = 1".into())); + // A table without a header row doesn't push it off the sheet either. + s.execute("range.setValues", json!({"range": "X1", "values": [[1], [2]]})).unwrap(); + plant_empty(&mut s, "X1048576"); + assert!(s.execute("insert.table", json!({"range": "X1:X2", "header": false})).is_err()); + assert_eq!(code(&s, 0, "X1048576"), Some("x = 1".into())); + // It is part of the data region. + s.execute("range.setValues", json!({"range": "P1", "values": [[1], [""], [3]]})).unwrap(); + plant_empty(&mut s, "P2"); + let sh = s.doc().unwrap().wb.sheet(0).unwrap().clone(); + assert_eq!(crate::selection::current_region(&sh, CellRef::parse("P1").unwrap()).a1(), "P1:P3"); + // Pasted into part of a legacy array, it is refused like any content. + s.execute("selection.set", json!({"range": "R1:R3"})).unwrap(); + s.execute("cell.set", json!({"input": "=5", "array": true})).unwrap(); + plant_empty(&mut s, "T1"); + s.execute("edit.copy", json!({"range": "T1"})).unwrap(); + assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array"))); +} diff --git a/crates/engine/src/tests/python_commands.rs b/crates/engine/src/tests/python_commands.rs new file mode 100644 index 0000000000..eb794c609c --- /dev/null +++ b/crates/engine/src/tests/python_commands.rs @@ -0,0 +1,245 @@ +//! The python.* commands. + +use gridcraft_core::{CellError, Value}; +use serde_json::json; + +use super::{s, v}; + +fn set(s: &mut crate::Session, cell: &str, code: &str) -> serde_json::Value { + s.execute("python.set", json!({"cell": cell, "code": code})).unwrap() +} + +#[test] +fn set_stores_the_code_and_blocks_the_cell_until_it_can_run() { + let mut s = s(); + let r = set(&mut s, "B1", "xl('A1') + 1"); + assert_eq!(r["cell"], "B1"); + assert_eq!(v(&s, "B1"), Value::Error(CellError::Blocked)); + let got = s.execute("cell.get", json!({"cell": "B1"})).unwrap(); + assert_eq!(got["python"]["code"], "xl('A1') + 1"); + assert_eq!(got["python"]["output"], "value"); + assert_eq!(got["input"], "xl('A1') + 1"); + // The active cell by default. + s.execute("selection.set", json!({"cell": "D4"})).unwrap(); + s.execute("python.set", json!({"code": "2"})).unwrap(); + assert_eq!(s.execute("cell.get", json!({"cell": "D4"})).unwrap()["python"]["code"], "2"); + // One undo step takes the cell back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.execute("cell.get", json!({"cell": "D4"})).unwrap()["python"].is_null()); +} + +#[test] +fn unchanged_code_keeps_its_cached_result() { + let mut s = s(); + set(&mut s, "A1", "21 * 2"); + // As a file would have cached it. + { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let cell = sh.cells.get_mut(gridcraft_core::CellRef::new(0, 0)).unwrap(); + let py = std::sync::Arc::make_mut(cell.py.as_mut().unwrap()); + py.output = Some(gridcraft_model::PyOutput { value: Value::Number(42.0), type_name: "int".into(), preview: "42".into(), convertible: true }); + cell.value = Value::Number(42.0); + } + set(&mut s, "A1", "21 * 2"); + assert_eq!(v(&s, "A1"), Value::Number(42.0), "same code, same result"); + s.execute("python.set", json!({"cell": "A1", "code": "21 * 2", "output": "object"})).unwrap(); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "object"); + set(&mut s, "A1", "21 * 3"); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked), "new code has no result yet"); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "object", "the return type stays"); +} + +#[test] +fn set_refuses_bad_params_long_code_headers_and_protected_cells() { + let mut s = s(); + for p in [ + json!({"cell": "A1"}), + json!({"cell": "A1", "code": 5}), + json!({"cell": "not a cell", "code": "1"}), + json!({"cell": "A1", "code": "1", "output": "sideways"}), + ] { + assert!(s.execute("python.set", p.clone()).is_err(), "{p}"); + } + // The limit is the stored PY(…) formula's 8,192 characters. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "y".repeat(8_080)})).is_err()); + s.execute("python.set", json!({"cell": "A1", "code": "y".repeat(8_079)})).unwrap(); + let quoted = format!("{}{}", "\"".repeat(1_200), "y".repeat(5_800)); + let e = s.execute("python.set", json!({"cell": "A2", "code": quoted})).unwrap_err(); + assert!(e.to_string().contains("8192") || e.to_string().contains("8,192"), "{e}"); + // A table header is the column's name. + s.execute("range.setValues", json!({"range": "C1", "values": [["Name", "Score"], ["a", 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "C1:D2", "headers": true})).unwrap(); + assert!(s.execute("python.set", json!({"cell": "D1", "code": "1"})).is_err()); + assert_eq!(v(&s, "D1"), Value::text("Score")); + set(&mut s, "D2", "1"); + // A locked cell on a protected sheet refuses it. + s.execute("review.protectSheet", json!({})).unwrap(); + let e = s.execute("python.set", json!({"cell": "F1", "code": "1"})).unwrap_err(); + assert!(e.to_string().contains("protected"), "{e}"); +} + +#[test] +fn set_over_a_spilling_formula_takes_the_spill_away() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(3)"})).unwrap(); + assert_eq!(v(&s, "A3"), Value::Number(3.0)); + set(&mut s, "A1", "[1, 2, 3]"); + assert_eq!(v(&s, "A3"), Value::Empty); + assert!(s.doc().unwrap().wb.sheet(0).unwrap().spill_ranges.is_empty()); +} + +/// A cached result as a file would have kept it on the cell: `[[1], [2], [3]]`, a list. +fn cache_list(s: &mut crate::Session, cell: &str) { + let at = gridcraft_core::CellRef::parse(cell).unwrap(); + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let py = std::sync::Arc::make_mut(sh.cells.get_mut(at).unwrap().py.as_mut().unwrap()); + let arr = gridcraft_core::Array::new(3, 1, vec![1.0.into(), 2.0.into(), 3.0.into()]).map(Value::from).unwrap(); + py.output = Some(gridcraft_model::PyOutput { value: arr, type_name: "list".into(), preview: "[1, 2, 3]".into(), convertible: true }); +} + +/// A1 holds `[1, 2, 3]` with its cached list spilled over A1:A3 as Excel values; B1 reads A3. +fn cached_spill_with_a_reader() -> crate::Session { + let mut s = s(); + set(&mut s, "A1", "[1, 2, 3]"); + cache_list(&mut s, "A1"); + s.execute("formulas.calculateNow", json!({})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "=SUM(A3)"})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(1.0)); + assert_eq!(v(&s, "B1"), Value::Number(3.0)); + s +} + +fn output_of(s: &mut crate::Session, cell: &str) -> serde_json::Value { + s.execute("cell.get", json!({"cell": cell})).unwrap()["python"]["output"].clone() +} + +fn undo_depth(s: &mut crate::Session) -> Option { + s.execute("history.list", json!({})).unwrap()["undo"].as_array().map(Vec::len) +} + +#[test] +fn output_switches_the_return_type_and_drops_a_result_of_the_other_type() { + let mut s = cached_spill_with_a_reader(); + // The mode it already has changes nothing and adds no undo step. + let undo = undo_depth(&mut s); + let r = s.execute("python.output", json!({"cell": "A1", "mode": "value"})).unwrap(); + assert_eq!(r["output"], "value"); + assert_eq!(undo_depth(&mut s), undo); + assert_eq!(v(&s, "A3"), Value::Number(3.0), "the kept result still spills"); + // Without `mode` it switches. The cached list is an Excel value's result: as with python.set + // and a new return type, the cell has no result until it runs, and its old spill goes with + // its readers recalculated. + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + let r = s.execute("python.output", json!({})).unwrap(); + assert_eq!(r["output"], "object"); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked)); + assert_eq!(v(&s, "A3"), Value::Empty, "the old spill goes"); + assert_eq!(v(&s, "B1"), Value::Number(0.0), "and what read it is recalculated"); + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["code"], "[1, 2, 3]", "the code stays"); + // The same as python.set with the same code and the other return type. + let mut by_set = cached_spill_with_a_reader(); + by_set.execute("python.set", json!({"cell": "A1", "code": "[1, 2, 3]", "output": "object"})).unwrap(); + for c in ["A1", "A3", "B1"] { + assert_eq!(v(&s, c), v(&by_set, c), "{c}"); + } + assert_eq!(output_of(&mut s, "A1"), output_of(&mut by_set, "A1")); + // Switching back brings no result back: the dropped one belonged to the old type. + s.execute("python.output", json!({"cell": "A1", "mode": "value"})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Error(CellError::Blocked)); + assert_eq!(v(&s, "A3"), Value::Empty); + // Each switch is one undo step, and undoing the first brings the result and its spill back. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + assert_eq!(v(&s, "A1"), Value::Number(1.0)); + assert_eq!(v(&s, "A3"), Value::Number(3.0)); + assert_eq!(v(&s, "B1"), Value::Number(3.0)); + // A cell with no result keeps showing #BLOCKED!. + set(&mut s, "C1", "x = 1"); + s.execute("python.output", json!({"cell": "C1"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Error(CellError::Blocked)); + assert_eq!(output_of(&mut s, "C1"), "object"); +} + +#[test] +fn output_refuses_table_headers_and_locked_cells_as_set_does() { + let mut s = s(); + // A Python cell in a table's header row (as a file could hold one): python.set refuses to + // put code there, and python.output refuses to change it. + s.execute("range.setValues", json!({"range": "C1", "values": [["Name", "Score"], ["a", 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "C1:D2", "headers": true})).unwrap(); + { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let cell = wb.sheet_mut(0).unwrap().cells.get_mut(gridcraft_core::CellRef::parse("D1").unwrap()).unwrap(); + cell.py = Some(std::sync::Arc::new(gridcraft_model::PyCode::new("'Score'"))); + } + let e = s.execute("python.output", json!({"cell": "D1"})).unwrap_err(); + assert!(e.to_string().contains("table header"), "{e}"); + assert_eq!(output_of(&mut s, "D1"), "value"); + // A locked cell on a protected sheet refuses it; an unlocked one formatted Hidden takes it, + // as it takes python.set. + set(&mut s, "F1", "1"); + set(&mut s, "G1", "2"); + s.execute("home.formatCells", json!({"range": "G1", "style": {"protection": {"locked": false, "hidden": true}}})).unwrap(); + s.execute("review.protectSheet", json!({})).unwrap(); + let e = s.execute("python.output", json!({"cell": "F1"})).unwrap_err(); + assert!(e.to_string().contains("protected"), "{e}"); + assert_eq!(output_of(&mut s, "F1"), "value"); + s.execute("python.set", json!({"cell": "G1", "code": "2"})).unwrap(); + s.execute("python.output", json!({"cell": "G1"})).unwrap(); + assert_eq!(output_of(&mut s, "G1"), "object"); +} + +#[test] +fn output_refuses_cells_without_python_and_bad_modes() { + let mut s = s(); + // Empty params: the active cell, which holds no Python code. + let e = s.execute("python.output", json!({})).unwrap_err(); + assert!(e.to_string().contains("isn't a Python cell"), "{e}"); + s.execute("cell.set", json!({"cell": "B1", "input": "=1+1"})).unwrap(); + assert!(s.execute("python.output", json!({"cell": "B1"})).is_err()); + set(&mut s, "A1", "1"); + for p in [json!({"cell": "A1", "mode": "sideways"}), json!({"cell": "A1", "mode": 1}), json!({"cell": "nowhere"})] { + assert!(s.execute("python.output", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["python"]["output"], "value"); + // python.set refuses a return type that isn't text too, rather than ignoring it. + assert!(s.execute("python.set", json!({"cell": "A1", "code": "1", "output": true})).is_err()); +} + +#[test] +fn a_recorded_switch_keeps_the_return_type_it_set() { + // python.output without `mode` switches, so a recording keeps the return type the switch set + // (as Bold records `on`): played back on a cell that already has it, nothing switches back. + let mut s = s(); + set(&mut s, "A1", "1"); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("python.output", json!({"cell": "A1"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + let m = s.execute("macro.get", json!({"name": "Rec"})).unwrap(); + let m = crate::macros::parse_macro(&m).unwrap(); + let steps = crate::macros::command_steps(&m.steps); + let step = steps.iter().find(|(_, id, _)| *id == "python.output").map(|(_, _, p)| (*p).clone()); + assert_eq!(step.and_then(|p| p.get("mode").cloned()), Some(json!("object"))); + for _ in 0..2 { + s.execute("macro.run", json!({"name": "Rec", "onConflict": "overwrite"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "object"); + } + // A run inside a script is recorded the same way. + s.execute("automate.newScript", json!({"name": "Switch", "commands": [{"command": "python.output", "params": {"cell": "A1"}}]})).unwrap(); + s.execute("macro.record", json!({"relative": false})).unwrap(); + s.execute("automate.runScript", json!({"name": "Switch"})).unwrap(); + s.execute("macro.record", json!({"stop": true, "name": "Rec2"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + for _ in 0..2 { + s.execute("macro.run", json!({"name": "Rec2", "onConflict": "overwrite"})).unwrap(); + assert_eq!(output_of(&mut s, "A1"), "value"); + } +} diff --git a/crates/engine/src/tests/python_files.rs b/crates/engine/src/tests/python_files.rs new file mode 100644 index 0000000000..cad3f87456 --- /dev/null +++ b/crates/engine/src/tests/python_files.rs @@ -0,0 +1,744 @@ +//! Python cells in files: native JSON, and xlsx as `_xlfn._xlws.PY(index,0|1)` with the code in +//! the Python part ([MS-XLSX] 2.1.23, 2.3.10) and cached values. Nothing here runs Python: results +//! are cached ones, as a file would hold them. + +use std::io::{Read, Write}; +use std::sync::Arc; + +use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value}; +use gridcraft_model::{Cell, PyCode, PyOutput, Workbook}; +use serde_json::json; + +use super::{s, v}; +use crate::{Session, Trust}; + +fn py(s: &mut Session, cell: &str, code: &str) { + s.execute("python.set", json!({"cell": cell, "code": code})).unwrap(); +} + +/// Gives a Python cell a result, as running it (or a file's cache) would. +fn cache(s: &mut Session, cell: &str, value: Value, type_name: &str) { + let d = s.doc_mut().unwrap(); + let wb = Arc::make_mut(&mut d.wb); + let sh = wb.sheet_mut(0).unwrap(); + let c = sh.cells.get_mut(CellRef::parse(cell).unwrap()).unwrap(); + let p = Arc::make_mut(c.py.as_mut().unwrap()); + p.output = Some(PyOutput { value, type_name: type_name.into(), preview: String::new(), convertible: true }); +} + +fn array(rows: usize, cols: usize, data: Vec) -> Value { + Value::Array(Arc::new(Array::new(rows, cols, data).unwrap())) +} + +fn save(s: &mut Session, format: &str) -> Vec { + let r = s.execute("file.saveBytes", json!({"format": format})).unwrap(); + crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap() +} + +fn open(s: &mut Session, name: &str, bytes: &[u8]) { + s.execute("file.open", json!({"name": name, "base64": crate::io::base64_encode(bytes)})).unwrap(); +} + +fn part(bytes: &[u8], name: &str) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + z.by_name(name).unwrap().read_to_string(&mut xml).unwrap(); + xml +} + +fn sheet_xml(bytes: &[u8]) -> String { + part(bytes, "xl/worksheets/sheet1.xml") +} + +/// The package with `edit` applied to each XML part (by name), and `add` added. +fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &str)]) -> Vec { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let name = f.name().to_string(); + let mut data = Vec::new(); + f.read_to_end(&mut data).unwrap(); + if let Ok(text) = std::str::from_utf8(&data) { + data = edit(&name, text).into_bytes(); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(&data).unwrap(); + } + for (name, text) in add { + out.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(text.as_bytes()).unwrap(); + } + out.finish().unwrap().into_inner() +} + +/// The package with `edit` applied to the first sheet's XML. +fn with_sheet_xml(bytes: &[u8], edit: impl Fn(&str) -> String) -> Vec { + with_parts(bytes, |name, text| if name == "xl/worksheets/sheet1.xml" { edit(text) } else { text.to_string() }, &[]) +} + +/// `xml` with its `` replaced by `data`. +fn replace_sheet_data(xml: &str, data: &str) -> String { + match (xml.find(""), xml.find("")) { + (Some(a), Some(b), _) => format!("{}{data}{}", &xml[..a], &xml[b + "".len()..]), + (_, _, Some(a)) => format!("{}{data}{}", &xml[..a], &xml[a + "".len()..]), + _ => panic!("no sheetData in {xml}"), + } +} + +/// An empty workbook's package with `data` as its first sheet's cells and, when `scripts` is +/// given, a Python part holding them (the relationship and the content type included), as +/// [MS-XLSX] 2.1.23 describes it. +fn excel_shaped(data: &str, scripts: Option<&[&str]>) -> Vec { + let mut s = s(); + let plain = save(&mut s, "xlsx"); + let Some(scripts) = scripts else { return with_sheet_xml(&plain, |xml| replace_sheet_data(xml, data)) }; + let codes: String = scripts.iter().map(|c| format!("{c}")).collect(); + let python = format!( + "\n{codes}" + ); + const REL: &str = + ""; + const TYPE: &str = ""; + let edit = |name: &str, text: &str| match name { + "xl/worksheets/sheet1.xml" => replace_sheet_data(text, data), + "xl/_rels/workbook.xml.rels" => text.replace("", &format!("{REL}")), + "[Content_Types].xml" => text.replace("", &format!("{TYPE}")), + _ => text.to_string(), + }; + with_parts(&plain, edit, &[("xl/python/python1.xml", &python)]) +} + +fn code(s: &Session, cell: &str) -> Option { + s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(cell).unwrap()).and_then(|c| c.py.as_deref()).cloned() +} + +/// A workbook with a value, a formula over a Python cell, a spilling table, an object, long code +/// with quotes and line breaks, and an error. +fn build() -> (Session, String) { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "21"})).unwrap(); + py(&mut s, "B1", "xl('A1') * 2"); + cache(&mut s, "B1", Value::Number(42.0), "int"); + s.execute("cell.set", json!({"cell": "A5", "input": "=B1+1"})).unwrap(); + py(&mut s, "C1", "[[1, 'two'], [3, \"four\"]]"); + cache(&mut s, "C1", array(2, 2, vec![1.0.into(), Value::text("two"), 3.0.into(), Value::text("four")]), "list"); + s.execute("python.set", json!({"cell": "E1", "code": "[1, 2]", "output": "object"})).unwrap(); + cache(&mut s, "E1", array(2, 1, vec![1.0.into(), 2.0.into()]), "list"); + let long = format!("# {}\ntext = \"say \\\"hi\\\"\"\nlen(text)", "x".repeat(7_900)); + assert!(PyCode::new(&long).fits()); + py(&mut s, "F1", &long); + cache(&mut s, "F1", Value::Number(8.0), "int"); + py(&mut s, "G1", "1/0"); + { + let d = s.doc_mut().unwrap(); + let sh = Arc::make_mut(&mut d.wb).sheet_mut(0).unwrap(); + sh.cells.get_mut(CellRef::parse("G1").unwrap()).unwrap().value = Value::Error(CellError::Python); + } + s.execute("formulas.calculateNow", json!({})).unwrap(); + assert_eq!(v(&s, "B1"), Value::Number(42.0)); + assert_eq!(v(&s, "A5"), Value::Number(43.0)); + assert_eq!(v(&s, "D2"), Value::text("four")); + assert_eq!(v(&s, "E1"), Value::text("list"), "a Python object shows its type"); + assert_eq!(v(&s, "E2"), Value::Empty, "and doesn't spill"); + (s, long) +} + +#[test] +fn xlsx_stores_the_code_in_the_python_part_with_cached_values() { + let (mut s, long) = build(); + let bytes = save(&mut s, "xlsx"); + let xml = sheet_xml(&bytes); + // The formula names the cell's script by index, in the order the cells are written: B1, C1, + // E1, F1, G1. + assert!(xml.contains("_xlfn._xlws.PY(0,0)42"), "{xml}"); + assert!(xml.contains(">_xlfn._xlws.PY(2,1)"), "the Python object cell has return type 1: {xml}"); + assert!(!xml.contains("xl('A1')"), "the code is not in the sheet"); + let python = part(&bytes, "xl/python.xml"); + assert!( + python.contains("xl('A1') * 2"), + "{python}" + ); + assert_eq!(python.matches("").count(), 5); + assert!( + part(&bytes, "[Content_Types].xml").contains("") + ); + assert!( + part(&bytes, "xl/_rels/workbook.xml.rels") + .contains("Type=\"http://schemas.microsoft.com/office/2023/09/relationships/Python\" Target=\"python.xml\"") + ); + assert!(xml.contains("t=\"array\" ref=\"C1:D2\""), "the spill is saved like a dynamic array's: {xml}"); + assert!(xml.contains("#VALUE!") && !xml.contains("#PYTHON!"), "Python errors are cached as #VALUE!"); + + open(&mut s, "book.xlsx", &bytes); + assert_eq!(s.doc().unwrap().trust, Trust::FromFile); + // Cached values show, spills included, and the code is back. + assert_eq!(v(&s, "B1"), Value::Number(42.0)); + assert_eq!(v(&s, "A5"), Value::Number(43.0)); + assert_eq!( + (v(&s, "C1"), v(&s, "D1"), v(&s, "C2"), v(&s, "D2")), + (Value::Number(1.0), Value::text("two"), Value::Number(3.0), Value::text("four")) + ); + assert_eq!(code(&s, "B1").unwrap().code, "xl('A1') * 2"); + assert!(code(&s, "E1").unwrap().object); + assert_eq!(code(&s, "F1").unwrap().code, long, "long code with quotes and line breaks survives"); + assert_eq!(v(&s, "G1"), Value::Error(CellError::Value)); + // A blocker typed into the spill area gives #SPILL!; clearing it spills again, without + // running anything. + s.execute("cell.set", json!({"cell": "D2", "input": "x"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Error(CellError::Spill)); + s.execute("edit.clearContents", json!({"range": "D2"})).unwrap(); + assert_eq!(v(&s, "D2"), Value::text("four")); + // Saved again, the file holds the same formulas and scripts. + let again = save(&mut s, "xlsx"); + assert!(sheet_xml(&again).contains("_xlfn._xlws.PY(0,0)")); + assert_eq!(part(&again, "xl/python.xml"), python); + // A workbook without Python cells has no Python part. + let mut plain = super::s(); + assert!(!save(&mut plain, "xlsx").windows(10).any(|w| w == b"python.xml")); +} + +#[test] +fn excel_authored_python_cells_are_read_as_python() { + // A workbook as [MS-XLSX] 2.3.10 describes it: `_xlfn._xlws.PY(index,0|1,params…)` naming a + // script of the Python part, whose code names the parameters as `%Px%`, with a spilled result + // cached. + let data = "_xlfn._xlws.PY(0,0)1\ + _xlfn._xlws.PY(1,1,C1:C3)DataFrame\ + 2"; + let bytes = excel_shaped(data, Some(&["[1, 2]", "df = xl(\"%P2%\", headers=True)\ndf.describe()"])); + let mut s = s(); + open(&mut s, "excel.xlsx", &bytes); + let a1 = code(&s, "A1").expect("an Excel Python cell is a Python cell"); + assert_eq!(a1.code, "[1, 2]"); + assert!(!a1.object); + assert_eq!((v(&s, "A1"), v(&s, "A2")), (Value::Number(1.0), Value::Number(2.0)), "its spilled values are kept"); + let cell = s.doc().unwrap().wb.active().unwrap().cell(CellRef::new(0, 0)).unwrap().clone(); + assert!(cell.formula.is_none()); + let b1 = code(&s, "B1").unwrap(); + assert_eq!(b1.code, "df = xl(\"C1:C3\", headers=True)\ndf.describe()", "a parameter is put back as its reference"); + assert!(b1.object); + assert_eq!(v(&s, "B1"), Value::text("DataFrame")); + // Saved by GridCraft, the code goes back into a Python part, the reference as text. + let again = save(&mut s, "xlsx"); + assert!(part(&again, "xl/python.xml").contains("df = xl(\"C1:C3\", headers=True)\ndf.describe()")); + // The string-literal form (other applications, files GridCraft wrote before) still reads. + let literal = "_xlfn._xlws.PY(\"1 + 1\",1)2"; + open(&mut s, "literal.xlsx", &excel_shaped(literal, None)); + assert_eq!(code(&s, "A1").map(|p| (p.code, p.object)), Some(("1 + 1".to_string(), true))); +} + +#[test] +fn a_py_formula_naming_a_missing_script_keeps_only_its_value() { + let data = "_xlfn._xlws.PY(0,0)5_xlfn._xlws.PY(3,0)6"; + for (name, bytes) in [("one.xlsx", excel_shaped(data, Some(&["5"]))), ("none.xlsx", excel_shaped(data, None))] { + let (wb, warnings) = crate::io::open_bytes(name, &bytes).unwrap(); + let sh = wb.sheet(0).unwrap(); + let b1 = sh.cell(CellRef::parse("B1").unwrap()).unwrap(); + assert!(b1.py.is_none() && b1.formula.is_none(), "{name}: no code to keep, and no formula #NAME? would replace"); + assert_eq!(b1.value, Value::Number(6.0), "{name}"); + assert!(warnings.iter().any(|w| w.contains("Python")), "{name}: {warnings:?}"); + } + let (wb, _) = crate::io::open_bytes("one.xlsx", &excel_shaped(data, Some(&["5"]))).unwrap(); + assert_eq!(wb.sheet(0).unwrap().cell(CellRef::parse("A1").unwrap()).unwrap().py.as_ref().map(|p| p.code.as_str()), Some("5")); +} + +/// `bytes` with the part `name` stored uncompressed and one byte of its data changed, so the +/// archive is intact but reading the part fails its checksum. +fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let entry = f.name().to_string(); + let mut data = Vec::new(); + f.read_to_end(&mut data).unwrap(); + let options = zip::write::SimpleFileOptions::default(); + let options = if entry == name { options.compression_method(zip::CompressionMethod::Stored) } else { options }; + out.start_file(entry, options).unwrap(); + out.write_all(&data).unwrap(); + } + let mut zipped = out.finish().unwrap().into_inner(); + let at = zipped.windows(marker.len()).position(|w| w == marker.as_bytes()).expect("the marker is stored as it is"); + zipped[at + 1] ^= 0x20; + zipped +} + +#[test] +fn a_damaged_python_part_is_a_warning_and_the_workbook_opens_with_its_values() { + let data = "_xlfn._xlws.PY(0,0)59"; + let good = excel_shaped(data, Some(&["5"])); + // The part's data fails its checksum (a damaged archive entry). + let damaged = with_damaged_part(&good, "xl/python/python1.xml", ""); + // The part is not well-formed XML, before its first script. + let broken = |at: &'static str, with: &'static str| { + with_parts(&good, move |name, text| if name == "xl/python/python1.xml" { text.replace(at, with) } else { text.to_string() }, &[]) + }; + let malformed = broken("", "", Color::Auto)]); + let mut sh = (*wb.sheets[0]).clone(); + sh.shapes.push(Shape { + id: 3, + kind: ShapeKind::TextBox, + anchor: Anchor { cell: CellRef::parse("D2").unwrap(), width: 80.0, height: 30.0, ..Default::default() }, + fill: Color::Auto, + line: Color::Auto, + text: "plain".into(), + format: Default::default(), + math: Default::default(), + }); + wb.sheets[0] = Arc::new(sh); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 3); + assert_eq!(s[0].text, "{".repeat(40)); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[1].text, "\u{1F600} & ]]> ", "XML-illegal characters are dropped, the rest kept"); + assert_eq!(s[2].kind, ShapeKind::TextBox); + assert_eq!(s[2].text, "plain"); +} + +#[test] +fn office_math_edited_elsewhere_reads_back_as_edited() { + // GridCraft writes the source in the description and Office Math in the body. Another + // application that edits the Office Math (Excel) leaves the description alone; the marker in + // the description no longer matches the body, so the Office Math is converted and the stale + // source dropped, and the next save writes the edited equation. + let wb = book(vec![equation(1, "B2", "x^2", Color::Rgb(0x1F4E79))]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + assert!(described(&d, "x^2")); + // Excel's edit: the base `x` becomes `y`, in the Office Math only. + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + let edited = d[m0..m1].replacen("x", "y", 1); + assert_ne!(edited, d[m0..m1]); + d.replace_range(m0..m1, &edited); + parts.insert(name, d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[0].text, "{y}^{2}", "the edited Office Math, converted"); + assert_eq!(s[0].line, Color::Rgb(0x1F4E79)); + // Saving writes the edited equation; the old source is gone. + let again = drawing(&unzip(&write_xlsx(&back).unwrap())); + assert!(described(&again, "{y}^{2}") && !again.contains("x^2"), "{again}"); +} + +#[test] +fn a_marker_over_garbage_office_math_falls_back_without_panicking() { + // Office Math that is not the marker's and not in the subset either: the Choice is left + // alone and the fallback text box, which carries the description, is read as the equation. + let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + d.replace_range(m0..m1 + "".len(), "junk"); + parts.insert(name.clone(), d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::Equation); + assert_eq!(s[0].text, "x^2"); + // A description whose marker is malformed is not GridCraft's source: with Office Math the + // maths is converted; without it the box is text. + let d2 = drawing(&unzip(&write_xlsx(&wb).unwrap())).replace("descr=\"gridcraft:latex:", "descr=\"gridcraft:latex:zz:"); + parts.insert(name, d2.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!((s[0].kind, s[0].text.as_str()), (ShapeKind::Equation, "{x}^{2}")); +} + +#[test] +fn office_math_outside_the_subset_reads_the_fallback() { + let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let mut d = drawing(&parts); + // Another writer: no GridCraft source, Office Math the reader does not convert (a + // pre-subscript), and a fallback text box with its own text. + while let Some(a) = d.find(" descr=\"gridcraft:latex:") { + let b = d[a + 8..].find('"').unwrap() + a + 9; + d.replace_range(a..b, ""); + } + let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); + d.replace_range( + m0..m1 + "".len(), + "12y", + ); + let fb = d.find("").unwrap(); + let t = d[fb..].find("x^2").unwrap() + fb; + d.replace_range(t..t + "x^2".len(), "the writer's fallback"); + parts.insert(name, d.into_bytes()); + let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); + let s = shapes(&back); + assert_eq!(s.len(), 1); + assert_eq!(s[0].kind, ShapeKind::TextBox, "not an equation"); + assert_eq!(s[0].text, "the writer's fallback", "the fallback is read, not the empty Office Math box"); +} + +#[test] +fn hostile_sources_round_trip_exactly() { + // Sources built from the characters XML and LaTeX treat specially: each is saved (as Office + // Math with a fallback, or as text) and read back as the same equation source. + const PARTS: &[&str] = &[ + "x", + "\\frac{a}{b}", + "\"", + "'", + "<", + ">", + "&", + "&", + "]]>", + "