Skip to content

Latest commit

 

History

History
785 lines (538 loc) · 85.3 KB

numpy-domains.md

File metadata and controls

785 lines (538 loc) · 85.3 KB

NumPy Domains — Trusted Scientific Helpers

Back to Enabling NumPy & Python in LibreOffice (core venv bridge, =PYTHON(), architecture, sandbox).

WriterAgent builds domain-specific trusted helpers on top of the warm venv subprocess: fixed host stubs call reviewed modules under plugin/scripting/ (and related packages) with the full scientific stack — no AST sandbox inside those modules. This document covers Analysis, Visualization, Symbolic Math, Units, Text Analytics, Forecasting, Optimization, Quant, and planned domains (Geospatial, Audio).

Related: Analysis Sub-Agent · Image Recognition (Vision) · Embeddings · DuckDB Calc · SageMath (deferred) · Venv IPC & serialization


Table of contents

  1. Venv packages by domain
  2. Scientific domain roadmap (trusted helpers)
  3. Future Refinements & Polish for Existing Domains

Venv packages by domain {#venv-packages-by-domain}

Trusted helpers require packages in the user venv (scripting.python_venv_path). Settings → Python Test reports Present/Missing per group, and after Test finishes, when anything is still Missing, appends copy-paste uv pip install … then pip install … lines at the bottom for those packages.

Required venv packages (trusted analysis helpers)

The 14 Calc Analysis Helpers in plugin/scripting/analysis.py require a fixed scientific stack in the user venv. Settings → Python Test reports these under Data Analysis / EDA Libraries and includes them in the bottom uv/pip install footer when any are missing.

uv pip install numpy pandas scipy scikit-learn statsmodels fg-data-profiling pandas-montecarlo

The helpers work on pandas 2.3 and 3.x. fg-data-profiling declares pandas<3, so this line installs pandas 2.3; without it uv installs pandas 3. The dev lock and the compute image run pandas 3.1.

Package Used by
numpy, pandas All helpers (coercion, tables, aggregates)
scipy detect_outliers z-score
scikit-learn detect_outliers (isolation_forest), cluster_numeric
fg-data-profiling (data_profiling) describe_data
statsmodels run_regression, forecast_time_series / decompose_time_series
pandas-montecarlo monte_carlo

Helpers that need a missing package return MISSING_PACKAGE with the install line above — there is no in-code fallback to alternate libraries. See Analysis Sub-Agent. IQR uses pandas quantiles and does not import scipy. monte_carlo permutes series order and does not draw with replacement; its metrics are final_value, bust_prob, goal_prob, and worst_trough.

compare_periods parses date_col with parse_date_column (Calc epoch 1899-12-30; whole numbers from 1900 through 2200 are 1 January of that year). pd.to_datetime on a serial is nanoseconds since 1970 and used to collapse several years into one 1970 period. detect_outliers method isolation_forest is row-level: metrics.per_column is empty and flags is a single N outlier rows (isolation_forest) line. IQR and z-score still count outliers per column. Missing scikit-learn returns MISSING_PACKAGE from isolation_forest and from cluster_numeric, including the scaler import. pivot_aggregate and group_summary accept aggfunc as a string, a list of strings, or a dict of column to string, using only sum, mean, median, min, max, count, std, var, first, last, nunique, prod, sem, skew, and quantile. Names are stripped and lowercased. Anything else is INVALID_PARAM. Pivot writes 0 for a missing group only when every aggregation is sum, count, prod, or nunique; otherwise the cell is empty. MultiIndex headers flatten in level order with _ (Sales_Q1, Sales_sum), then the usual _1 suffix if two labels collide. correlation_matrix rejects min_abs below 0. A value above 1 returns no pairs. run_regression drops non-finite rows before the fit. clean_and_prepare treats extension dtypes such as Float64 and UInt64 as numeric. Complex columns stay categorical. Duplicate column labels (only reachable when a pandas DataFrame is passed in; grid headers are deduplicated) return INVALID_PARAM from describe_data and quick_stats. describe_data computes IQR outlier counts in one pass over the numeric columns. An empty compare_periods period stays empty (sum uses min_count=1) and its change is empty rather than inf. run_regression rejects a target that also appears in features, and duplicate feature names, with INVALID_PARAM. cluster_numeric drops all-empty numeric columns and lists them in flags. kpi_summary validates agg against the shared aggregation set; clean_and_prepare rejects unknown fill_numeric / fill_categorical values.

Demo workbook (all NumPy domains)

  • Showcase Demo (Pretty Dashboard & Executive Layout): tests/fixtures/python_showcase_demo.ods / python_showcase_demo.xlsx (docs/python-in-calc-showcase.md). Modern styled executive dashboard with KPI cards, formatted tables, live =PY() / =PYTHON() formulas across Sales, Marketing ML, Time Series Forecasting, Portfolio Optimization, Engineering Units, Plot Gallery, and SQL/DuckDB (SQL only in cells; RESULTS are a short =PY() that reads an explicit SQL cell/range as data[1] plus named-range identity as data[0]; sheet-only uses session_duckdb(); sibling ACS zip_income.csv join is live run_sql + scoped_dir). XLSX named ranges are absolute (Sales_Analytics!$A$4:$J$39) so =PY() does not pack a calling-cell-shifted data[0]. Both formats share the same standard-sheet chrome (title 📊 {Sheet} — {sub}, blank row 2, section banner row 3, data header / named-range anchors at row 4 — A4:J39 / A4:G24). ODS formulas use single-pass OpenFormula conversion ([$Sheet.A4:.I39]) plus TableColumn / TableRow sizes and table:covered-table-cell after each number-columns-spanned so headed Calc keeps Overview KPI cards and the capability matrix (odfpy spans alone collapse later cells into column A). Spacer rows are a string-typed empty cell with use-optimal-row-height=false so headed Calc keeps blank R2 (a void <table:table-cell/> was still dropped: section landed on R2, Order_ID on R3, named A4 started on ORD-1001). Regenerate via python scripts/generate_pretty_demo_spreadsheet.py --format all (also copies zip_income.csv).
  • Manual QA Test Fixture: tests/fixtures/numpy_domains_demo.ods (numpy_domains_demo.README.md). Native ODS preserving uppercase =PYTHON() add-in tokens for automated test validation. Regenerate via python scripts/generate_numpy_domains_demo_spreadsheet.py.

Case definitions: scripts/numpy_domains_demo_cases.py.

Planned domain package groups {#planned-domain-package-groups}

Future trusted-helper domains (Geospatial, Audio, optional prophet) will each declare required venv packages and a Settings → Python Test group when implemented. Shipped today:

Domain Settings → Python Test group Entry doc
Vision Vision Libraries — OCR required: Docling (docling, rapidocr, onnxruntime, css_inline) or Paddle (paddleocr, paddle, css_inline) when Docling is not installed; optional: paddleocr/paddle fallback, easyocr/openvino/nemotron_ocr/ocrmac/tesseract (listed when present), ultralytics, skimage ../images/recognition.md
Embeddings Embeddings Libraries (envwrap, sentence_transformers, sqlite_vec, langgraph, langchain_core, langchain_text_splitters) ../embeddings.md
Visualization Visualization Libraries (matplotlib, seaborn) Visualization § Phase A–C
Symbolic Math (SymPy) Computer Algebra (sympy) Symbolic Math §3
Units (Pint) Data Engineering Libraries (pint, duckdb) Data Engineering / Units §3b
Forecasting Data Analysis / EDA Libraries (statsmodels — shared with analysis) Forecasting §2
Text Analytics Text / NLP Libraries (spacy, textdescriptives, transformers, …) Text Analytics §4
Quantitative Finance Quantitative Finance Libraries (yfinance, pandas_ta, …) Run Python Script Quant Helpers (Calc only)

SageMath remains a future optional extension — sagemath-integration-dev-plan.md.


Scientific domain roadmap (trusted helpers) {#scientific-domain-roadmap-trusted-helpers}

The sections below are roadmaps and reference for scientific capabilities. Shipped domains: Analysis (../calc/analysis-sub-agent.md), Vision (../images/recognition.md), Visualization (§1), Symbolic Math (SymPy) (§3), Units (Pint) (§3b), Forecasting (§2), Text Analytics (§4), Optimization (partial — §5), and Quant (Run Python Script). DuckDB SQL helpers (through Phase D: multi-table catalog plus shared-kernel session_duckdb(), plus honesty polish: 200-row cap with visible truncated/warning, run_sql firewall) are implemented under the same trusted + Run Python Script + analysis-domain pattern; see ../calc/duckdb-dev-plan.md. Remaining domains (Geospatial, Audio) follow the same pattern: trusted modules under plugin/scripting/, fixed venv stubs, host extract → IPC → compact results → document egress, plus optional Run Python Script templates and specialized sub-agent exposure.

Domain helper pattern (Analysis + Vision canonical)

Shipped domains prove the stack. New domains should mirror them—not invent parallel plumbing.

Register host glue once: add an RPS entry (and optional script-picker entry) in plugin/scripting/domain_registry.py, use shared header/template helpers from helper_domain.py, and keep compute/egress in the domain modules. Do not copy another if *_meta is not None block into python_runner.execute_and_insert_result.

Layer Analysis Vision Viz Symbolic (SymPy) Units (Pint) Forecast Planned
Trusted module analysis.py vision.py viz.py symbolic.py units.py forecast.py text_analytics.py, …
Templates run_analysis(...) script run_vision(...) script run_viz(...) script run_symbolic(...) script run_units(...) script run_forecast(...) script …
Host client client.py run_analysis client.py run_vision client.py run_viz client.py run_symbolic units.py run_units client.py run_forecast Same RPC shape
Runner / egress helper_domain.py (run_domain), analysis_egress.py vision_runner.py, vision_egress.py egress in viz.py egress in symbolic.py egress in units.py egress in forecast.py Per domain
Run Python Script register in domain_registry.py PICKER / RPS same same same same same Host glue: helper_domain.py + registry; picker via document_scripts.py
Run Python Script execution venv + post-venv venv + post-venv venv + post-venv venv + post-venv venv + post-venv venv + post-venv All built-in helper samples execute visible run_*() Python. Calc helpers bind selected cells as data; Writer text injects text + document_context; Vision injects selected graphic bytes as image. Results route via post-venv insert in python_runner.py using specs from domain_registry.py. Calc sheet inserters are (doc, ctx, result); Writer/Draw inserters are (ctx, doc, result).
Settings Test Data Analysis / EDA Vision Libraries Visualization Libraries Computer Algebra Data Engineering Libraries Data Analysis / EDA (statsmodels) Per domain when shipped
LLM surface Hidden. Calc chat: =PY() only analyze_image deferred Calc chat: matplotlib via =PY() Writer/Calc domain="python" — math_run_symbolic Run Python Script Units Helpers only Chat hidden; RPS Forecast Helpers Calc analysis/python domains hidden
flowchart TD
  user[User_or_LLM] --> picker[RunPythonScript_or_delegate]
  picker --> host[Host_UNO_extract]
  host --> stub[Fixed_venv_stub]
  stub --> trusted[Trusted_module_full_stack]
  trusted --> result[Compact_JSON_or_image]
  result --> egress[Calc_Writer_egress]
Loading

Dual access model: Prefer high-level run_*({helper, params}, data, context) (or domain-specific inputs like vision's image). Keep python_run_script / =PYTHON() as the escape hatch for novel work. Return MISSING_PACKAGE when required venv packages are absent; optional pure-Python or ASCII fallbacks per domain.

Data handoff: Reuse calc_addin_data.py and payload_codec split-grid. For LLM/sub-agent paths, pass data_range (late binding) rather than full grids in chat context — see Analysis Sub-Agent — Data Handoff.

Sheet layout flags: headers and header_row sit on the spec next to helper, not inside params. The host client copies them onto the trusted-action packet, and the worker puts them back on the spec before parse_trusted_spec. Dropping them defaulted headers to true, so headers=false from forecast_data / optimize_data read the first data row as column names. The host copies headers and header_row onto the packet without bool() or int(), and the worker returns INVALID_SPEC when header_row is not an integer or headers is not a boolean coerce_bool accepts. The string "false" is false.

Helper errors: Coercers in venv/coerce.py and helper-local validators raise HelperError(code, message) from venv/results.py. Each result-dict helper in analysis, forecast, optimize, and viz carries @catch_helper_error under @helper(...), which turns HelperError into error_result(code, message, helper=<name>). symbolic's _symbolic_helper wrapper catches the same class. Any other exception propagates (run_domain maps it to <DOMAIN>_FAILED, and a direct =PY or Python call raises).

Visualization note: Phase A uses the venv worker and __wa_payload__: "image" envelope for raw matplotlib (no trusted module required). Phases B–C shipped: Run Python Script image egress and trusted Viz helpers (viz.py, [Viz] templates, plot_data, analysis auto-plot).

New Domain Proposals

We are actively expanding the set of supported scientific libraries. These packages are not part of the standard LLM sandbox and must be accessed via trusted extension modules.

Domain Packages Implementation
Data Engineering pint, pyarrow Trusted module plugin/scripting/units.py or io.py
NLP langdetect (grammar Local + embeddings plain-text locale), spacy (shipped via text_analytics.py) Venv langdetect via langdetect_rpc.py; Writer dialog + Run Python Script direct imports
Bayesian Opt scikit-optimize Trusted module plugin/scripting/optimization.py

The implementation should follow the Domain helper pattern using the established RPC stub architecture.

Prioritization

Priority Domain Status today First target
0 Analysis (numeric EDA, regression, clustering, …) Shipped — ../calc/analysis-sub-agent.md; Viz auto-plot via viz_auto_plot.py Maintenance
1 Visualization & Plotting Shipped (Phase A–C) plot_data, [Viz] quick_plot
2 Time Series & Forecasting Shipped (Phase 1) — anomalies, viz bands, auto_plot; Prophet deferred Optional prophet model (Phase 2)
3 Symbolic Mathematics Shipped (SymPy only; Sage deferred) math_run_symbolic, [Math] solve_equation
4 Text / Document Analytics Shipped — spaCy + topics + sentiment; Writer dialog; no LLM tool yet LLM tool surface
5 Optimization & OR Partial — optimize_data + scipy helpers shipped; pulp/ortools deferred pulp / ortools
6 Geospatial Not started [Geo] map_data
7 Audio / Signal Processing Recording shipped; no librosa analysis Spectrogram via Viz egress
8 Data Engineering Shipped (Pint) — units.py, [Units] templates; pyarrow IO deferred convert_quantity, parse_quantity
9 NLP Partial — langdetect in embeddings venv; spaCy in text analytics LLM tool for text analytics
10 Bayesian Opt Not started skopt

1. Visualization & Plotting {#visualization}

Status: Phase A–C shipped (raw matplotlib pipeline, Run Python Script image egress, trusted Viz helpers).

Goal: Turn analysis results into publication-quality charts inside LibreOffice—Calc sheet graphics or Writer inline images—without requiring the LLM to write matplotlib every time. Highest immediate ROI for demos and shareable workflows.

Why: Users respond to visuals. "I generated a professional chart from my spreadsheet in two clicks" is a strong adoption story. Pairs naturally with the analysis sub-agent (auto-plot regression, clusters, Monte Carlo distributions).

Phase A — Raw matplotlib pipeline (shipped)

No viz.py yet. Matplotlib figures from user/LLM code are captured in the venv and inserted via the existing image envelope.

Component Module Behavior
Figure → bytes venv/to_wire.py, venv/venv_sandbox.py figure_to_image_payload() (SVG default); plot_image_payload() (SVG, or 150-dpi PNG above 1 MiB); _capture_open_figures_payload() gives one image per open figure, skipping blank ones; _returned_figures() for a returned Figure, seaborn grid or list of them; serialize_result() for nested Figure; Agg backend; figure cleanup
Wire format payload_codec.py PAYLOAD_IMAGE, pack_image_envelope(), is_image_payload(); shared temp-file helper
Calc =PYTHON() function.py, python_image_egress.py insert_image_result_on_sheet() → GraphicObjectShape anchored to formula cell on its owning sheet
Chat / LLM venv.py Calc: auto-insert on the tool document (ctx.doc), not the front window, plus image_path. Writer/Draw: image_path → image_insert
Writer notebook writer_importer.py Shared inline image insertion (insert_run_image, _insert_image_in_flow); cell run orchestration in notebook_runner.py
LLM prompts import_policy.py App-specific format_matplotlib_plot_hint() (Calc / Writer / Draw); not in global import policy
LLM sandbox sandbox.py matplotlib, seaborn allowed (not on the sandbox blocklist)
Settings Test venv_worker.py matplotlib under Scientific Libraries; Visualization Libraries group (matplotlib, seaborn) when Viz helpers are used
Tests test_matplotlib_output.py, test_python_function.py, test_venv_python_image.py, test_python_runner_domains.py, test_viz.py, test_plot_data.py Codec, sandbox e2e, multi-figure capture, Calc chat insert, RPS venv path, trusted helpers

Works today:

# =PYTHON() — plt is auto-imported; explicit import still fine
plt.plot([1, 2, 3])
# Calc chat — one step (plot inserts on the tool document, not whichever window is in front; image_path still returned)
python_run_script(code="… plt.plot(…) …")

# Writer / Draw chat — two steps
1. python_run_script(code="… plt.plot(…) …")
2. image_insert(image_path=<returned path>)

Which figures become pictures:

  • Every open figure becomes its own image (SVG; a 150-dpi PNG when the SVG is over 1 MiB).
  • Use plt.subplots for one picture with several plots. The cell may end on any pyplot call, such as fig, axs = plt.subplots(1, 2) or plt.hist(...).
  • End the cell on a figure, a seaborn grid (e.g. pairplot = sns.pairplot(df)) or a list of figures to show exactly those, in that order; the others are discarded.
  • A blank figure is skipped when another has a drawing.
  • A non-plot last value is replaced by any open figure, so call plt.close() first to return a value.
  • Desktop places one floating picture per image; Collabora draws them stacked in the cell.

Native LO charts (charts.py — chart_upsert, chart_list, …) are a separate UNO chart path, not matplotlib. The LLM can already create native Calc/Writer charts from structured data; Viz helpers complement that with statistical plotting (seaborn, heatmaps, distribution plots).

Known limitations: No UNO e2e test for full =PYTHON() plot insertion (geometry unit-tested with mocks). Each open figure becomes its own image. Optional polish (anchor/z-order, replace-existing-chart, UNO e2e): Monaco Phase 3.

Calc plot replacement reuses only a GraphicObjectShape named WriterAgentPlot (or WriterAgentPlot_N for an integer N ≥ 2 with no sign, whitespace, or leading zero, optionally followed by a space and a wa-plot tag; any other suffix is not a slot) that belongs to the target cell (see the owner tag below). Shapes preserve the graphic's intrinsic aspect ratio instead of stretching to a fixed size. A new slot 0 stands beside the cell (0.1 mm inside the far edge of the cell or, for a multi-column spill, the last spilled column of the formula's row, so its anchor stays on that row) unless it fills a large merged placeholder block (both dimensions at least 40 mm by 30 mm); later slots stand beside it at their intrinsic aspect ratio. Existing plots keep their box, so one may cover a wider new spill. A plot placed past a multi-column spill is anchored to the last spilled cell, so cutting only the formula cell leaves the plot behind (cutting the spilled row moves both). A list or grid result with images and scalars spills with the image cells empty; image-only results, dicts, header-only DataFrames, and lists holding a dict or DataFrame show "Image inserted" / "Images inserted". When created, successive slots chain horizontally from the live outer edge of preceding slots without gaps or overlaps (resizing an earlier slot on recalculation may cause overlap if its aspect changes). In right-to-left sheets (TableLayout == 1), slots chain from right to left. An existing slot is not reloaded when its image bytes are unchanged, tracked via the SHA-256 digest in its owner tag; matplotlib SVG output is written without a date and with a fixed id salt so an unchanged figure gives identical bytes. When image bytes differ, the graphic is swapped and the box the user arranged is kept. Only when the new image's aspect ratio differs by more than 1% from the old graphic's does a non-fill slot take the new aspect, keeping its long side and its top-left corner (top-right in right-to-left sheets). When an image fails to load, the failure is logged and the remaining slots still update: a new slot stays as a 10 cm × 6 cm empty-graphic placeholder, an existing slot keeps its previous picture, and the cell value is unchanged. If the formula cell's row or column is hidden, newly created plot shapes are set to hidden (Visible=False), while existing shapes preserve their visibility state across recalculations. Stock Calc moves a cell-anchored shape's anchor to the cell under its top-left corner whenever the shape is positioned, so slots after the first end up anchored to other cells, and LibrePy cannot write maStart back. Each plot therefore records both its owner formula cell and its anchor cell at the time of writing in a wa-plot:<oc>,<or>[@<ac>,<ar>][:<sha>] tag stored in UserDefinedAttributes (saved in ODF; the shape's alt text is left alone; 0.9.1 tags without @<ac>,<ar> gain the anchor on their next recalc), and also stores the tag without the digest at the end of the shape's Name so it survives XLSX round-trips. When a tagged shape's anchor moves, the owner is shifted by the same delta: if the shifted owner equals the target cell, the formula and plot moved together (row/column insertion or deletion above or left of them) and the plot is reused; otherwise the recorded owner keeps the plot (user drag, or columns inserted between the formula and slot k) unless the shifted owner cell now holds another =PY() formula. On a right-to-left sheet, a tag read only from Name (reloaded from XLSX) ignores column shifts so it keeps its recorded owner's column while still following row moves. A plot without a tag is matched by its anchor. Stale WriterAgentPlot_N shapes for higher slots on the cell, and duplicate shapes for one slot (e.g. a plot pasted from another workbook whose name did not collide under SdrObject::MakeNameUnique, or an XLSX file with two pictures of one name; in-document pasted copies are renamed by Calc to WriterAgentPlot wa-plot:1,2@1, 1 or WriterAgentPlot 1 and are never slots), are removed only when image_count is passed (on the index-0 insert); callers that omit image_count do not remove them. User images and other shapes at that cell are left alone; a plot from before the name prefix gets a new sibling instead of being guessed. =PY() plot placement, refresh, and sweep add no undo entries of their own. Undoing the entry that created the =PY() formula removes its plots and WriterAgent image: note, while deleting or overwriting the formula manually leaves them. WriterAgent image: notes written or cleared by =PY() add no undo entry and keep any pending redo. A new plot from a tool or Run Python Script records one "WriterAgent: Insert plot" entry per new plot so undo removes it and redo restores it unchanged. A missing document, sheet, draw page, or formula cell raises ImageEgressError. Chat tools set image_inserted false. On the main thread, =PY() processes every slot and then returns the first such error instead of "Image inserted"; off-main, the WriterAgent image: note is written only when the cell's note is empty or already starts with that prefix. Any other note text is left in place, because a Calc cell has one note and insertNew replaces it, while the cell text can still say "Image inserted". The temp PNG/SVG is removed after GraphicURL returns.

Phase B — Run Python Script + Writer image egress (shipped)

python_runner.py execute_and_insert_result() iterates get_post_venv_domains() before the raw-image plot fallback and inserts plots via viz.py egress helpers (Calc → insert_image_result_on_sheet; Writer → insert_image_at_locator). Writer and Draw plot inserts unlink the temp file after GraphicURL returns, including when insert raises. The path is under the temp directory, so it is embedded rather than linked. Viz templates execute the visible run_viz(...) call in the venv; results route via post-venv insert. Tests: test_python_runner_domains.py.

Phase C — Trusted Viz helpers (shipped)

viz.py (templates, trusted runner, Calc/Writer egress), client.py run_viz, _viz_script_section in document_scripts.py, post-venv routing in python_runner.py, plot_data analysis-domain tool, and analyze_data auto-plot via viz_auto_plot.py.

Helper Purpose Notes
plot_data Auto chart from numeric grid + spec chart_type is line, bar, scatter, or histogram after strip and lowercase. Missing or blank is line. Any other value is INVALID_PARAM (chart_type must be line, scatter, histogram, or bar) and is not drawn as a line. x and y match a column exactly, or by str(label) when the requested name is not itself a column. An unknown y is UNKNOWN_COLUMN (Unknown columns: <name>); omitting y uses the first numeric column. A scatter with no x uses the first other numeric column, or NOT_ENOUGH_NUMERIC (Need at least two numeric columns.) when there is none. A y that names a non-numeric column, or a scatter x that does, is NON_NUMERIC_COLUMN.
correlation_heatmap Heatmap method is pearson, kendall, or spearman (strip and lowercase). Anything else is INVALID_PARAM. If seaborn cannot draw, the helper uses matplotlib imshow.
time_series_plot Date-indexed line plot Shared with Forecast. historical_value_col, when set, must name a column (UNKNOWN_COLUMN). It does not fall back to value_col. A non-numeric value column is NON_NUMERIC_COLUMN. Rows are plotted in ascending parsed-date order. Missing forecast_col, lower_col, and upper_col are skipped. History, forecast, and the confidence band with no plotted row is INSUFFICIENT_DATA (No rows to plot.). A forecast column that is present and entirely null does not count as data.
quick_plot Default Run Python Script template It plots one series, y_col or else the first numeric column. y_cols is INVALID_PARAM (quick_plot takes y_col, not y_cols). A list y_col is INVALID_PARAM (y_col must be one column name). The same exact-or-str(label) match applies, so integer column 0 matches "0". x_col, when it names a column, is the bar tick labels and the line x values. Bar when the frame has 12 or fewer rows, otherwise line. The y column that is plotted, if it is not numeric, is NON_NUMERIC_COLUMN.

Run Python Script templates: Viz Helpers → [Viz] quick_plot, [Viz] correlation_heatmap, [Viz] time_series.

Result contract (draft): The host reads {status, helper, title, image} (one envelope, possibly nested; code/message on error). chart_type and writer_cleanup_hints are informational with no host consumer. Image bytes use the same __wa_payload__: "image" envelope as Phase A. SVG payloads over 8 MiB are re-rendered as PNG so the image fits the 16 MiB IPC frame cap. Viz helpers close the matplotlib figure on every exit, including when savefig fails, so a trusted-action error does not leave the figure open on the warm worker.

Analysis sub-agent: After run_regression, cluster_numeric, monte_carlo, or correlation_matrix, analyze_data can auto-call a matching viz helper when auto_plot=true or the task hint mentions charts (see viz_auto_plot.py).

Chat tool results: plot_data returns what python_run_script returns (insert_plots_and_report in python/venv.py): the viz result under result with image bytes shown as "<image>"; in Calc image_inserted, plot_error and message, with status error only when no plot landed and failed plots' temp files in image_path(s); outside Calc image_path(s). A viz result with no image is VIZ_ERROR. analyze_data / forecast_data auto-plot record on their own result instead (plot, image_inserted, plot_error): a failed plot never fails the analysis, and a closed document propagates. Forecast auto-plot failures are VIZ_ERROR dicts.

Packages: matplotlib (required); seaborn (recommended). Settings → Python Visualization Libraries group lists both.

Fallback: ASCII mini-charts or compact text tables when matplotlib is missing (MISSING_PACKAGE).

Phase 2+ (deferred): create_interactive_chart — static multi-view export or embedded HTML/JS if LibreOffice egress supports it.


2. Time Series & Forecasting {#forecasting}

Status: Shipped (Phase 1). Trusted helpers via forecast.py, Run Python Script Forecast Helpers, and forecast_data chat tool (domain="analysis"). Phase 1 adds anomaly_detection_time_series, confidence-band time_series_plot, and forecast_data auto_plot. Optional prophet deferred to Phase 2.

Goal: Forecast, decompose, and flag anomalies on date-indexed Calc data—natural fit for spreadsheets (finance, ops, sales).

Why: Strong Calc synergy; pairs with Visualization for confidence-band plots (Phase 1).

Already in codebase:

Piece Location
Period-over-period change compare_periods in analysis helpers (uses the same parse_date_column rules as forecast: Calc serials and 1900–2200 years)
Outlier detection detect_outliers — cross-sectional; use anomaly_detection_time_series for temporal anomalies
OLS / statsmodels run_regression; statsmodels in analysis venv install line
Range → pandas calc_addin_data.py, venv/analysis.py coerce_to_dataframe

Shipped helpers:

Helper Purpose Key params
forecast_time_series Forward predictions + intervals when available periods=12, model="auto" (Holt-Winters / ARIMA / moving-average fallback)
decompose_time_series Trend / seasonal / residual date_col, value_col, period, model
anomaly_detection_time_series Series-aware outliers (STL residuals + robust z-score) date_col, value_col, period, threshold=3.0 (number greater than 0), method="stl_residual"

Seasonality: The period is inferred from the date frequency (daily 7, business-day 5, weekly 52, monthly 12, quarterly 4), and only when the series covers at least two full cycles. Otherwise model="auto" stays trend-only and adds a flag. An explicit seasonal_periods (or period on decompose / anomaly) still wins. Row count alone used to pick 12 whenever there were 24 or more rows, so a daily sheet was fit as a 12-day season. Duplicate timestamps are averaged before the fit. Weekday-only series forecast on business days. Calc date serials and integer years are parsed in the venv. A numeric date column whose values all lie in 1900–2200 and are whole numbers is a year column (1 January). Any other positive serial uses the Calc epoch 1899-12-30. The host range read still returns raw serials. A gap that breaks frequency inference does not fall back to a flat moving average: the model is fit on row order, and when the typical gap is a month, quarter, or year, future dates use an anchored offset only when every timestamp is on that anchor. Otherwise each future date is the last observation plus N times that DateOffset, so a 28th or 30th that is not the period end stays on that day of month. Day >= 28 used to select MonthEnd, and 2023-12-28 rolled to 2023-12-31. An irregular series adds a flag because the model still assumes equal spacing. An explicit seasonal_periods with fewer than two full cycles does not run Holt-Winters; auto stays trend-only and says so. Explicit model arima or moving_average ignores seasonal_periods and adds a flag. auto and holt_winters still use it. The forecast table contains the whole horizon up to the 10000-period cap. Decomposition edge NaNs are empty cells, not NaN tokens. A decomposition longer than 200 rows adds "decomposition table shows the first 200 of N rows". periods below 1 is INVALID_PARAM; a non-positive value used to be raised to one row and was not flagged. period below 2 on decompose and anomaly is INVALID_PARAM, the same rule as seasonal_periods. anomaly threshold <= 0 is INVALID_PARAM ("threshold must be a number greater than 0"). Zero and negative values used to flag every row. date_col and value_col must be different columns. A frequency with no mapped cycle (yearly, minutes) names that frequency in the trend-only flag. Only a series with no inferred frequency keeps the "could not infer a seasonal period" flag. A horizon that would run past pandas' timestamp range (for example a yearly series at the 10000-period cap) is INVALID_PARAM, not an OutOfBoundsDatetime escape.

Holt-Winters intervals: 95% bands are the 2.5 and 97.5 percentiles of HoltWintersResults.simulate paths. That results object has forecast / predict / simulate and no get_prediction (get_prediction is on ETS and statespace results). Calling get_prediction used to raise, get swallowed, and the sheet said intervals were unavailable with no lower/upper. If simulation cannot build a band, the result keeps the point forecast and sets metrics.interval_note (available: false) instead of inventing bounds. The flag is Holt-Winters prediction intervals are omitted; the forecast column is the point forecast. and interval_note.message is HoltWintersResults has no analytic get_prediction; simulate() did not return a 95% band. and is not copied into flags.

Phase 2 (deferred):

Helper Purpose
forecast_time_series with model="prophet" Facebook Prophet (heavy optional dep)

Module layout: plugin/scripting/forecast.py + plugin/scripting/venv/forecast.py.

Packages: statsmodels (required for decomposition and most forecasts; already in analysis stack); optional prophet (heavy — future Test group, MISSING_PACKAGE if absent).

Run Python Script: Forecast Helpers → [Forecast] forecast_time_series, [Forecast] decompose_time_series, [Forecast] anomaly_detection_time_series.

Output: Predictions / decomposition / anomaly tables (analysis egress pattern). forecast_data output_range uses the same sheet-qualified anchor as analyze_data (Report.B2, 'Q1.Sales'!B2, 'O''Brien'.A1): the report is written on that sheet. forecast_data with auto_plot=true (or chart keywords in task_hint) inserts a confidence-band chart via extended time_series_plot. A sheet-write failure leaves status ok and sets sheet_write_error. The forecast table is still returned, and auto-plot still runs.

Sub-agent: forecast_data in domain="analysis" — same delegation as EDA/regression (optimize_data precedent); supports auto_plot for band charts (forecast_auto_plot.py).

Threading: forecast_data and optimize_data are async. Sheet reads and result or chart writes run on the LibreOffice main thread. Venv forecast, optimize, and auto-plot viz IPC stay on the worker. Auto-plot history is a calc_range envelope from resolve_python_data; merge_forecast_plot_data materializes that envelope before building the band table. Sheet data resolution passes doc directly to resolve_python_data.

Fallback: Simple moving-average projection in pandas when statsmodels forecasting APIs unavailable (forecast_time_series with model="auto" or "moving_average"). model="auto" tries Holt-Winters (when a season passes the two-cycle check), then ARIMA(1,1,1), then the moving average; the fallback flag names the first model's exception ("primary model failed (…); used arima" / "statsmodels forecast failed (…); used moving_average"), and if every model fails the result is FORECAST_FAILED with the last exception.

Tests: test_forecast.py, test_forecast_templates.py, test_python_runner_domains.py, test_forecast_data.py, test_forecast_auto_plot.py.

Forecasting Phase 1 {#forecasting-phase-1}

Status: Shipped (items 1–3). Prophet remains Phase 2.

Goal: Temporal anomaly detection, forecast confidence-band charts on Calc, and optional Facebook Prophet — without bloating Phase 0’s tabular-only surface.

Prerequisite: Phase 0 is shipped (plugin/scripting/forecast.py, plugin/scripting/venv/forecast.py, plugin/calc/forecast.py, RPS Forecast Helpers, forecast_data in domain="analysis"). Mirror Optimize/Analysis patterns; do not add forecast helpers to analyze_data HELPER_NAMES.

Locked decisions
Decision Choice Why
Anomaly helper anomaly_detection_time_series in existing forecast.py / venv/forecast.py Same module + RPC; reuses _prepare_time_series
Anomaly method STL / seasonal-decompose residuals + robust z-score Cross-sectional detect_outliers is wrong for seasonality; decompose already shipped
Viz bands Extend time_series_plot in venv/viz.py Doc already says “shared with Forecast”; avoid a third plot helper unless extension is too messy
Auto-plot New plugin/calc/forecast_auto_plot.py + hook in ForecastDataTool Copy viz_auto_plot.py + AnalyzeDataTool (the auto-plot block after write_anchor_result)
Prophet Optional model="prophet" on forecast_time_series only Heavy dep; separate Settings group; MISSING_PACKAGE when absent
LLM tool Still forecast_data only; add auto_plot param Same as analyze_data; no new chat tool
Writer Still Calc-only RPS Phase 0 scope unchanged
flowchart TD
  forecast_data[forecast_data_tool] --> compute[venv_forecast_helper]
  compute --> table[metrics_and_tables]
  compute --> auto_plot{auto_plot_or_chart_hint}
  auto_plot --> viz[time_series_plot_with_bands]
  viz --> sheet[Calc_chart_image_egress]
  anomalies[anomaly_detection_time_series] --> table
Loading
Work item 1 — anomaly_detection_time_series

Purpose: Flag dates where the value is an outlier relative to trend and seasonality, not column-wise IQR.

Params (defaults):

Param Default Notes
date_col "Date" Same as Phase 0
value_col "Value" Same as Phase 0
period auto (12 if n≥24) Passed to STL/decompose
method "stl_residual" Phase 1 ships one method only
threshold 3.0 Finite number greater than 0, default 3. Zero and below are INVALID_PARAM. Flag when the absolute robust z-score is greater than threshold.

Algorithm (recommended):

  1. Reuse _prepare_time_series from venv/forecast.py.
  2. Run statsmodels.tsa.seasonal.STL (preferred over seasonal_decompose for robust residuals) with period=season.
  3. Compute robust z-scores on resid (the MAD branch multiplies by _NORMAL_MAD_SCALE, 0.6745, about Φ^{-1}(0.75)); mark rows where |z| > threshold.
  4. Return tabular egress:
{
  "status": "ok",
  "helper": "anomaly_detection_time_series",
  "metrics": {"n_anomalies": 2, "period": 12, "threshold": 3.0},
  "tables": [
    {
      "name": "anomalies",
      "columns": ["date", "observed", "expected", "residual", "score"],
      "rows": [...]
    }
  ]
}

Optional second table all_scores (truncated) for debugging — keep behind params.include_all=false default to limit sheet size.

Errors: MISSING_PACKAGE (statsmodels), INSUFFICIENT_DATA (need ≥ 2×period points, same as decompose).

Files:

File Change
plugin/scripting/forecast.py Add to HELPER_NAMES, _DEFAULT_PARAMS, template
plugin/scripting/venv/forecast.py Implement helper + _dispatch_helper branch
tests/scripting/test_forecast.py Inject one obvious spike in FORECAST_GRID; assert flagged
scripts/numpy_domains_demo_cases.py Third forecast case + regenerate ODS

Do not document cross-sectional detect_outliers as time-series anomalies — that was the Phase 0 doc drift risk.

Work item 2 — Viz confidence-band plots

Purpose: After forecast_time_series, insert a chart: historical line + forecast line + shaded confidence band when lower/upper columns exist.

Extend time_series_plot (lines 250–291) with optional params:

Param Purpose
forecast_col Column name for forward forecast values (overlay)
lower_col / upper_col Band edges; use fill_between when both present
historical_value_col When plotting a merged history+forecast frame. Must name an existing column. A missing name is UNKNOWN_COLUMN and does not fall back to value_col.

Alternative (if extension gets messy): add viz helper forecast_band_plot that accepts the forecast result table via params.forecast_table (columns from Phase 0 forecast table) plus data_range for history — host merges in run_trusted_viz before IPC. Prefer single-helper extension first.

Matplotlib behavior:

  • Plot historical date/value_col as solid line.
  • Plot forecast segment as dashed line.
  • ax.fill_between(dates, lower, upper, alpha=0.2) when intervals exist.
  • Do not invent bands when the model omitted intervals. Holt-Winters bands are simulation percentiles; if simulate fails, the table has no lower/upper and metrics.interval_note says why.

Files:

File Change
plugin/scripting/venv/viz.py Band overlay logic
plugin/scripting/viz.py Pass new params through templates if exposed
tests/scripting/test_viz.py Unit test with synthetic history + forecast columns (mock Agg)
Demo Optional check_mode: visual case on forecast sheet
Work item 3 — forecast_data auto-plot

Purpose: Match analysis UX: forecast_data with auto_plot=true (or chart keywords in task_hint) inserts band chart on Calc after table egress.

Pattern: Copy analysis auto-plot wiring:

  1. Add plugin/calc/forecast_auto_plot.py:
    • predicate is helper == "forecast_time_series" and (auto_plot or task_hint_implies_plot(task_hint))
    • run_auto_plot_after_forecast merges history with the forecast table and calls time_series_plot, taking value_col / lower / upper from the merged header.
    • Reuse task_hint_implies_plot from viz_auto_plot.py (import, do not duplicate regex).
  2. In ForecastDataTool.execute: after successful run + optional output_range write, mirror AnalyzeDataTool (the auto-plot block after write_anchor_result; run_auto_plot_after_forecast, insert_viz_result_into_doc).
  3. Add auto_plot: bool to forecast_data parameters (default false to match conservative Phase 0; or true to match analyze_data — pick false unless product wants parity).

Tests:

File Coverage
tests/calc/test_forecast_auto_plot.py merged-header params asserted on run_trusted_viz; mock viz insert
tests/calc/test_forecast_data.py auto_plot=true calls viz path (mocked)
Work item 4 — Optional Prophet (stretch / end of Phase 1)

Only if time permits after items 1–3.

Piece Detail
Model forecast_time_series with model="prophet"
Package prophet — add Forecasting Libraries group in venv_diagnostics.py _SANDBOX_SELF_CHECK_GROUPS
Install hint uv pip install prophet (note: can be slow/heavy on some platforms)
Fallback MISSING_PACKAGE with hint; do not auto-fallback to Holt-Winters when user asked for prophet
Tests Skip if prophet not installed (pytest.importorskip)
Files checklist (Phase 1 complete)
Action Path
Edit plugin/scripting/venv/forecast.py, plugin/scripting/forecast.py
Add plugin/calc/forecast_auto_plot.py
Edit plugin/calc/forecast.py (auto_plot param + hook)
Edit plugin/scripting/venv/viz.py (+ maybe viz.py templates)
Edit plugin/scripting/writeragent_api.py
Tests test_forecast.py, test_viz.py, test_forecast_auto_plot.py, test_forecast_data.py, demo cases
Docs This section → mark Phase 1 shipped; update prioritization row; ../calc/analysis-sub-agent.md one line on auto_plot for forecasts
Diagnostics Only if Prophet shipped
Implementation order
  1. anomaly_detection_time_series (venv + host + template + tests + demo case)
  2. Extend time_series_plot for bands (+ viz tests)
  3. forecast_auto_plot.py + ForecastDataTool hook (+ tests)
  4. Prophet (optional) + Settings group
  5. Regenerate demo ODS; make test
Explicitly out of Phase 1
  • Stuffing forecast helpers into analyze_data
  • Writer RPS / Writer egress for forecast
  • create_interactive_chart (Viz Phase 2+)
  • Geospatial / Audio / Quant test debt
  • Auto-plot for decompose_time_series (optional nice-to-have; not required for Phase 1 sign-off)
Phase 1 sign-off criteria
  • anomaly_detection_time_series flags injected spike in unit test and demo sheet
  • forecast_data with auto_plot=true inserts chart on Calc when matplotlib present
  • time_series_plot draws band when lower/upper provided
  • All new tests pass; make test green
  • Prioritization table updated; Prophet noted as Phase 2

3. Symbolic Mathematics & Equation Solving {#symbolic-math}

Status: Shipped (SymPy). Trusted helpers via symbolic.py, Run Python Script Math Helpers, and math_run_symbolic chat tool (domain="python"). SageMath remains a future optional extension — see sagemath-integration-dev-plan.md.

Goal: Solve, simplify, integrate, and differentiate equations; round-trip LaTeX ↔ LibreOffice Math objects; bridge Writer, Calc =PYTHON(), and Vision OCR of handwritten equations.

Why: Appeals to students, engineers, researchers; synergizes with Docling/Vision → sympy → Writer Math OLE.

Shipped helpers:

Helper Purpose
solve_equation Symbolic solve for variables
symbolic_simplify / integrate / differentiate Core SymPy wrappers
latex_to_math_object Validate/normalize LaTeX for Writer Math insert

Integration:

Piece Location
Trusted module Host symbolic.py; compute venv/symbolic.py; RPC client.py run_symbolic
Run Python Script Direct import templates in symbolic.py, Math Helpers in document_scripts.py
Writer Math insert insert_symbolic_result_into_writer in symbolic.py → convert_latex_to_starmath
Chat tool math_run_symbolic (domain="python")

Packages: sympy (required). Settings → Python Computer Algebra group lists sympy.

Run Python Script templates: Math Helpers → [Math] solve_equation, [Math] symbolic_simplify, [Math] integrate, [Math] differentiate.

Tests: test_symbolic.py, test_domain_templates_contract.py, test_python_runner_domains.py, test_symbolic_tool.py.

Parser limits: e is Euler's number unless it is the variable being differentiated or solved. Dunder names and non-decimal dots are rejected before parsing, because parse_expr uses eval. An integral SymPy leaves as Integral(...) returns NO_CLOSED_FORM. solve_equation rejects !=, ==, and inequalities. Factorial equations need a space before = (n! = 720); SymPy may still have no algorithm for them. These helpers already use the 300s long trusted worker timeout (LONG_TRUSTED_WORKER_TIMEOUT_SEC). A parse_expr result that is not a SymPy expression (a Python string, list, tuple, or dict, or 1.0.func) is PARSE_ERROR with message Not a math expression. An unknown call such as foo(x) is PARSE_ERROR with message Undefined function in expression: foo. Function is not a parser name. solve_equation returns NO_SOLUTION (No solution.) when the solution set is empty (exp(x), 1 = 0). When solve lists no roots and the set is not empty (x = x, 0, x**x), the result stays status: ok and latex is that set (\mathbb{C}, or the condition). sin(x) stays the explicit roots 0 and pi.

Out of scope (deferred): SageMath backend, sage sandbox integration — sagemath-integration-dev-plan.md.


3b. Data Engineering / Units (Pint) {#data-engineering-units}

Status: Shipped (Pint). Trusted helpers via units.py and Run Python Script Units Helpers. pyarrow / Arrow IO remains deferred.

Goal: Convert, parse, format, and dimensionally-check physical quantities inside LibreOffice without requiring the LLM to manage UnitRegistry() singletons or serialization.

Why: Unit normalization composes with analysis and vision workflows (OCR tables, lab data, engineering spreadsheets). Pint covers compound units (m/s → km/h) beyond Calc's built-in CONVERT() symbol set.

Shipped helpers:

Helper Purpose
convert_quantity Convert a value between units
parse_quantity Parse a quantity string
format_quantity Format magnitude + units for display
check_dimensionality Test dimensional compatibility

Integration:

Piece Location
Trusted module units.py (lazy-loads venv run_units)
Run Python Script Direct import templates in units.py, Units Helpers in document_scripts.py
Writer / Calc egress insert_units_result_into_doc in units.py

Packages: pint (required). Settings → Python Data Engineering Libraries group lists pint.

Run Python Script templates: Units Helpers → [Units] convert_quantity, [Units] parse_quantity, [Units] check_dimensionality. Edit positional or keyword arguments in the direct helper function call (e.g. convert_quantity(data, "m/s", "km/h")). The host parses that direct call into dispatch keys by positional prefix: value, from, to for convert_quantity; quantity for parse_quantity; magnitude, units, format_spec for format_quantity; quantity_a, quantity_b for check_dimensionality. Keywords keep the names written in the call and override the same slot.

Calc egress: By default, convert_quantity and parse_quantity write a single formatted cell at the selection anchor (e.g. 36 km/h). Writer inserts the same formatted string as plain text. A vector result inserts the per-cell strings joined with ", " (blank cells are left out of that join). For a debug/report layout, pass output_style="detailed" in the function call — this writes a key-value grid (formatted value on the first row, then magnitude/units or compatibility fields). check_dimensionality defaults to detailed.

# formatted (default for convert/parse) — anchor cell:
36 km/h

# detailed — starting at anchor cell:
36 km/h
Magnitude | 36
Units     | kilometer / hour

Vectorized / Range Inputs in =PY(): Units helpers (convert_quantity, parse_quantity, format_quantity) accept either a scalar or a Calc cell range (data), 1D list, or 2D column vector. When a column is passed as a trailing formula argument, the converted numeric magnitudes spill directly down the spreadsheet column without requiring Python list comprehensions:

# Convert a column of values from m/s to km/h (spills down column):
=PY("convert_quantity(data, 'm/s', 'km/h')"; A1:A10)

# Single cell (1x1 CalcRange unwraps to scalar float):
=PY("convert_quantity(data, 'm/s', 'km/h')"; A1)

# Pairwise conversion with matching units column:
=PY("convert_quantity(data[0], data[1], 'km/h')"; A1:A10; B1:B10)
  • Shape preservation: $N \times 1$ column in $\to$ $N \times 1$ column out; $1 \times N$ row in $\to$ $1 \times N$ row out; 1×1 single cell $\to$ scalar float.
  • Blanks & Errors: Missing/blank cells produce empty cells; individual invalid units emit "#VALUE!" without aborting the rest of the column. An RPC blank value or magnitude is PARSE_ERROR, not a successful 0. Numeric 0 is zero. Direct NaN stays blank; a non-finite magnitude is an error.
  • Display: format_quantity and parse_quantity use the compact unit (m, km / h). A dimensionless quantity formats as the bare magnitude (42), with no trailing space. convert_quantity keeps the caller's to text (km/h). A scalar RPC units value is Pint's long name (meter, kilometer / hour). A vector RPC units value is the caller's target spelling: one string when every cell shares it, or a list aligned with magnitudes when targets differ. formatted on that result is the per-cell list. Writer and the Run Python Script status line join that list with ", " (entries empty after strip are skipped and #VALUE! stays). Calc writes the numeric values grid. Unknown unit text is PARSE_ERROR. A dimension mismatch or a range shape mismatch is UNITS_ERROR. A non-dict params is INVALID_SPEC. A format_spec Python rejects is INVALID_SPEC. A scalar unit argument that is omitted or only whitespace is MISSING_PARAM. An omitted parse_quantity value (None or "") is MISSING_PARAM with message quantity is required on both the direct call and run_units. A whitespace-only quantity is PARSE_ERROR (empty quantity) on run_units and a blank cell on the direct call. Both from and from_unit, or both to and to_unit, when non-blank and different, are INVALID_SPEC with message from and from_unit disagree or to and to_unit disagree. The from-pair is reported first. Strings match after strip. One blank alias is ignored.
  • Dual returns: Direct =PY() calls return numeric magnitudes/lists for native Calc matrix spilling; RPC calls (run_units) return a single compact vector payload.

Tests: test_units.py, test_domain_templates_contract.py, test_python_runner_domains.py, test_map_range.py.

Out of scope (deferred): calc.convert() Calc-parity wrapper, pyarrow / plugin/scripting/io.py.


4. Text / Document Analytics {#text-analytics}

Status: High-quality spaCy implementation (multilingual via textdescriptives + spaCy pipelines) plus topics (NMF) using scikit-learn. Exposed via modeless dialog (Writer), Run Python Script templates (Writer), direct imports, and Settings Python self-check. No stdlib fallback.

Goal: Readability, topic structure, key phrases, sentiment by section, and cross-document comparison for reports and long-form Writer content.

Why: Strengthens core Writer use case; overlaps with professional writers, legal, academic users.

Input sources (host): Document text (whole or selection) is extracted on the host and sent to the venv worker. spaCy paths cap input at 1,000,000 characters (nlp.max_length); longer input is analyzed up to the cap and result.truncated carries analyzed_chars / total_chars (the dialog formatter does not show it yet).

High-quality spaCy features (multilingual):

  • Readability + descriptive stats via textdescriptives
  • Entity extraction (NER)
  • Key phrases (noun chunks)
  • Linguistic profile

Sentiment by section (transformers, heading sections)

Fancier: Topics

topics helper (added in 2026) performs lightweight topic modeling with TF-IDF + NMF from scikit-learn. It is especially useful on whole documents because the host extracts logical sections (using the heading tree) and passes a list of section texts. The result includes:

  • Top terms per topic
  • (When sections are provided) dominant topic + strength per section. A section is the heading once plus the following body (tracked deletions omitted). Sections with fewer than 8 words are omitted from assignments. section_index is the index in the section list passed to the helper. meta.n_topics is how many topics were fit. meta.n_sections, when present, is the number of input sections. The fit count is lowered to min(samples, features) because NMF’s nndsvd init refuses a larger n_components.

This gives writers an at-a-glance "map" of the major themes and where they appear — exactly the "topic structure" goal.

Sentiment (by section)

sentiment helper uses transformers + a strong multilingual model (default: cardiffnlp/twitter-xlm-roberta-base-sentiment, an XLM-RoBERTa model with good cross-lingual performance). score is signed polarity in [-1, 1] (positive confidence, negative confidence, or 0 for neutral) and the same number is used for the average and for each per_section entry. LABEL_n uses the model’s num_labels and the midpoint rule. The sentiment object is always score and label. section_index is only on per_section entries. The worker keeps the last successfully loaded sentiment pipeline and does not keep a failed load. "N star" / "N stars" uses that rule with five classes. The default Cardiff NLP model already returns the words negative, neutral, and positive. When run on the whole document it uses heading-based section extraction and returns both overall sentiment and per-section results. This delivers the "sentiment by section" goal for reports and long-form Writer content across 34 locales.

The old spacytextblob implementation has been removed (it provided only limited multilingual support).

Install hint (CPU wheels recommended for broad compatibility):

uv pip install transformers torch --index-url https://download.pytorch.org/whl/cpu

Override the model via the JSON setting text_analytics_sentiment_model (see config).

Results are inserted as compact tables and usable from scripts.

Module: Host facade text_analytics.py; compute in venv/text_analytics.py (spaCy + textdescriptives; runs inside the user venv).

UI (minimal): WriterAgent → Text Analytics... opens a modeless dialog with buttons for Readability (doc/sel), Entities, Key Phrases, Topics, Check Venv, and "Insert report here". All work is done with real spaCy pipelines (or sklearn for topics) in your configured Python venv (Settings → Python). Check Venv's install command includes scikit-learn, and the report says whether scikit-learn is installed.

Insert report writes into the Writer document that is active when Insert is clicked. The dialog stores the analyzed document's RuntimeUID. When that id and the active document's id are both non-empty and different, Insert asks you to switch back or run the analysis again and does not write. When either id is missing, Insert writes into the active Writer document. A worker exception shows the missing-package hint only when the message contains No module named, ModuleNotFoundError, or ImportError. Timeouts and other worker failures show Error: plus the exception text. Insert is enabled only when text_analytics_report_html returns a table, and Insert writes that same table; cell text goes through helper_domain.escape_for_html_insert (single-escaped).

Advanced scripting: Run Python Script Text Helpers templates call run_text_analytics(...). Edit the helper and params in that call; on Run the host injects text and document_context from the Writer document, then inserts results as a compact HTML table after the caret/selection. run_text_analytics accepts only the helper names in helper_registry (full, readability, entities, key_phrases, topics, sentiment, diagnostics, check); any other name, including an empty-text call, is UNKNOWN_HELPER.

Settings → Python Test: Reports a "Text / NLP Libraries" group (spacy, textdescriptives, transformers). For topics also install scikit-learn. Install hint: uv pip install spacy textdescriptives transformers torch --index-url https://download.pytorch.org/whl/cpu && python -m spacy download xx_sent_ud_sm. Packages are probed independently from package metadata, so torch is reported even when transformers is missing.

Requirements in the venv: spacy + textdescriptives + at least one model for the spaCy features. transformers + torch (CPU) for the sentiment helper (multilingual XLM-RoBERTa default). scikit-learn for the topics helper. The document's CharLocale (if present) is passed to prefer a better model for spaCy. xx_ent_wiki_sm is only the last-resort model (NER, no parser or sentence boundaries). On that model key phrases are empty and sentence counts are 0; entities still run. Prefer xx_sent_ud_sm or a *_core_* model.

Direct use: From any python_run_script or Run Python Script you can from writeragent.scripting.text_analytics import analyze_text, run_text_analytics.

No LLM tool surface for this helper yet; access via the dialog or by writing/running scripts. The LLM can still reach it via the python domain / python_run_script or by invoking the trusted helper directly.


5. Optimization & Operations Research {#optimization}

Status: Partial. scipy optimization shipped; monte_carlo shipped. Note: pulp and ortools integration is deferred to a later phase; current helpers rely on scipy.optimize.

Goal: Linear programming, scheduling, portfolio optimization inside Calc—appeals to analysts, supply chain, finance.

Proposed helpers:

| optimize_portfolio | Long-only minimum-variance (Sharpe is report-only) | scipy.optimize, numpy | | linear_programming | LP from spec dict | scipy.optimize.linprog (pulp deferred) | | solve_scheduling_problem | Assignment / small IP | scipy.optimize.linear_sum_assignment (ortools/pulp deferred) |

Run Python Script: Optimize Helpers → [Optimize] portfolio, [Optimize] linear_program.

Sheet output: optimize_data output_range uses the same sheet-qualified anchor as analyze_data (Report.B2, 'Q1.Sales'!B2). The parsed sheet is written through the shared Calc tabular egress.

Tie-in: Stochastic optimization with existing monte_carlo helper.

Sub-agent: Extend domain="analysis".

Packages: scipy (required).

linear_programming layout: Each row is a variable (c is that variable's objective coefficient). Each a* column is one <= constraint. b is one bound per constraint column. The template default a_cols: ["a1"] is a single constraint; repeat that same bound on every variable row. If b cannot be aligned to the constraint columns, the helper returns SHAPE_MISMATCH and does not replace b with zeros.

optimize_portfolio minimizes variance of per-period returns. A target_return outside [min, max] of the asset mean returns is INFEASIBLE_TARGET with that range in details. Solution tables show up to 200 rows (ANALYSIS_DATA_TABLE_ROWS). Weights are long-only and sum to 1. The objective is the covariance scaled by the mean diagonal, because raw daily variances sit under SLSQP's default tolerance and used to return the equal-weight start as optimal. risk_free_rate does not change the weights. When returns_col or cost_cols is omitted, date-named columns and monotonic unique integer columns are left out, so a worker id or a Date serial is not an asset or a task. Each omitted column is one flags entry, either "Skipped column {name} (looks like a date); pass the column list explicitly to include it." or the same sentence with "an id". A date-like name is reported once. Passing returns_col or cost_cols includes those columns and adds no skip flag. linear_programming accepts one bounds pair for every variable or one pair per original row (a pair for a row dropped as non-numeric is ignored). An infeasible or unbounded LP returns INFEASIBLE / UNBOUNDED with details.solver_status, and an unknown param name is INVALID_PARAM instead of being ignored. A missing column is UNKNOWN_COLUMN. A repeated name among c_col, b_col, and a_cols is INVALID_PARAM with message "c_col, b_col, and a_cols must name distinct columns; repeated: ...". Scheduling reports metrics.unassigned_rows when there are more rows than columns, and metrics.unassigned_columns counts columns left over when there are more columns than rows. A non-numeric linear_programming cell drops that variable row instead of raising. A sheet-write failure on optimize_data leaves status ok and sets sheet_write_error.

Quant picker: Quant Helpers are listed only for Calc. The inserter is the sheet grid from insert_quant_result_into_calc. Writer does not show the section. The grid adds the helper's warning (synthetic daily calendar, averaged duplicate dates) as a Flags block after the metrics.

Quant returns: efficient_frontier reads the sheet as a returns grid, the same contract as portfolio_tearsheet and optimize_portfolio. PyPortfolioOpt's mean_historical_return and CovarianceShrinkage default returns_data=False (prices, then percent-change). The helper passes returns_data=True so a returns sheet does not come back status: ok with a corner portfolio. Annualization stays 252 trading days. technical_analysis and portfolio_tearsheet sort a date / datetime / timestamp column ascending before path-dependent indicators and drawdown; duplicate tearsheet dates are averaged. That column is parsed with parse_date_column (Calc epoch 1899-12-30; whole numbers from 1900 through 2200 are 1 January of that year). pd.to_datetime on a serial is nanoseconds since 1970, which is not NaT, so a tearsheet used to annualize a one-day calendar and skip the synthetic-date warning. technical_analysis still writes the original date cells. fetch_historical_data stringifies every datetime column, and a multi-ticker download labels columns Close / AAPL. A comma-separated ticker string is several symbols. weight_bounds must be a pair or omitted, and a non-finite risk_free_rate is INVALID_PARAM. Incomplete frontier rows are dropped before the optimizer, because Ledoit-Wolf turns NaN into 0. fetch_historical_data passes auto_adjust=True, so Close is split-adjusted on every yfinance version. portfolio_tearsheet and efficient_frontier drop datetime and timedelta columns other than the date / datetime / timestamp column before reading returns. pd.to_numeric on those dtypes is nanoseconds since 1970, so a second date column (Period, Unnamed: 0, a timezone column) used to enter the mean and the covariance. A numeric column such as Year stays a return column. parse_date_column parses text cells with format="mixed" (ISO next to 01/02/2024, or a date next to a datetime). Mixed time zones stay on the single-format parser. The fetch_historical_data template ticker is AAPL.


6. Geospatial {#geospatial}

Status: Not started (niche; lower priority unless demand appears).

Goal: Static map image + attribute table from location columns in Calc.

Proposed helper: map_data(data_range, …) → image envelope (same as Viz Phase A/C) + summary table.

Packages (all optional): geopandas, folium, shapely — ship only if users request; MISSING_PACKAGE otherwise.

Run Python Script: Geo Helpers → [Geo] map_data.

Egress: Viz image path + analysis-style table insert.


7. Audio / Signal Processing {#audio-signal}

Status: Partial. Voice recording runs in the user venv (../chat/audio-architecture.md); venv analysis helpers (librosa) not shipped yet.

Goal: Analyze imported audio (including recordings saved from the chat panel): spectrograms, basic features, optional transcription post-processing.

Synergy: Recording produces WAV in user workflow; capture and analysis both run in the venv (sounddevice for mic input; optional librosa for analysis helpers).

Proposed helpers:

Helper Purpose
analyze_audio Duration, RMS, tempo, key features
spectrogram_plot Image via Viz envelope

Run Python Script: Audio Helpers → [Audio] analyze, [Audio] spectrogram.

Packages: librosa (optional Test group); matplotlib for plots.

Sub-agent: Writer main or specialized; optional link to STT pipeline in ../chat/audio-architecture.md.


Implementation phasing (cross-domain)

Phase Scope Domains
0 Trusted module + 1–2 helpers + Run Python Script section + unit tests Forecast Phase 0 shipped; next: Geospatial or Text LLM tool
0b Glue without full trusted module Viz Phase B — is_image_payload in Run Python Script
1 Sub-agent / analyze_data-style tools + delegation prompts Geospatial or Text LLM tool; Forecast Phase 2 (prophet)
2 Egress polish, optional caches, Writer cleanup hints All

Keep each domain lean: reuse payload_codec, split-grid, document-attached scripts + Monaco, and Settings Test reporting—the same surfaces that make Analysis and Vision usable without an LLM.

Shared-kernel Calc semantics (reset, recalc, idempotent cells): ../enabling_numpy_in_libreoffice.md §6 — Session modes. Worker lifecycle and code hot cache: numpy-serialization.md — Warm worker. Trusted-code pattern (generic): ../enabling_numpy_in_libreoffice.md §5.


3. Future Refinements & Polish for Existing Domains {#future-refinements--polish-for-existing-domains}

Roadmap of ergonomic, output formatting, and parameter enhancements across existing scientific and helper domains (refining what is already shipped rather than inventing new domains).

Cross-cutting ergonomic improvements {#cross-cutting-ergonomic-improvements}

  1. Vectorized / Array inputs for scalar helpers ([Units], [Math]):
    • Shipped for [Units]: convert_quantity, parse_quantity, and format_quantity in plugin/scripting/venv/units.py accept scalars, 1D lists, and 2D Calc column ranges directly without list comprehensions in =PY() (see Data Engineering / Units). Vectorized inputs for [Math] remain planned.
  2. Theme-aware visualization styles:
    • Detect active LibreOffice light/dark appearance via get_monaco_theme_info() and apply theme-aware figure backgrounds and palette hints (plt.style.use('dark_background') or transparent canvas in dark mode) so charts look native in dark documents.
  3. Presentation-ready number & table styling on Calc egress:
    • When tabular analysis results write to Calc, apply light default formatting (bold header row, light fill, percentage and 2-decimal number formatting where metadata indicates it).

Domain-specific polish opportunities {#domain-specific-polish-opportunities}

  • Vision / OCR:
    • Calc direct grid target: Route extract_structure table results directly into active sheet cell ranges instead of HTML-only.
    • Initialization feedback: Display a progress indicator ("Initializing OCR engine...") on the first heavy model invocation in the status chrome.
  • Symbolic Math (SymPy):
    • =PY() multi-solution unpacking: Ensure multi-solution outputs from solve_equation (e.g. [-2, 2]) unpack seamlessly into 1D/2D Calc formula arrays.
    • Numerical evaluation toggle: Optional evaluate=True / float_precision=4 parameter on solve_equation and symbolic_simplify for engineers wanting exact formulas alongside decimal approximations.
  • Units (Pint):
    • Offset temperature guidance: Add template examples and warnings for gauge vs difference temperature conversions (degC vs delta_degC).
    • Dimensionality mismatch diagnostics: Return clear, human-readable dimension descriptions (e.g. "Incompatible: [length] vs [mass] * [length] / [time]^2") when checks fail.
  • Analysis Helpers (EDA, Regression, Outliers):
    • Target/feature column auto-detection: Default target_col to the last column and feature_cols to all preceding numeric columns when omitted.
    • Data hygiene helper (shipped as clean_and_prepare): clean_and_prepare handles type coercion, optional drop_duplicates, and fill_numeric / fill_categorical imputation before modeling.
  • Time Series & Forecasting:
    • Summary KPI banner: Add executive summary metrics (MAPE, Expected Next Value, Trend %) above the projected data table. Frequency-based seasonality (and weekday forecast dates) is shipped; see Forecasting.
  • Text / Document Analytics:
    • Writer in-document highlighting: Option to highlight detected entities or low-readability sentences directly in Writer text.
    • Topic weight breakdown: Format topics output with relative percentage weights per section for quick at-a-glance density inspection.
  • Optimization (Scipy):
    • Calc range mapping: Clarify cell-range parameter mappings in optimize_portfolio and linear_program templates for easy spreadsheet bound referencing.

Open

  • [feature M few] Optional Facebook Prophet model (model="prophet") for forecast_time_series with a Forecasting Libraries Settings group and MISSING_PACKAGE when absent. (§ Forecasting Phase 1, Work item 4)
  • [feature S few] Auto-plot for decompose_time_series, which the forecasting phase left as a nice-to-have. (§ Forecasting Phase 1, Explicitly out of Phase 1)
  • [idea L few] create_interactive_chart for static multi-view export or embedded HTML/JS if LibreOffice egress can carry it. (§ Visualization & Plotting, Phase C)
  • [eng S few] UNO end-to-end test of full =PYTHON() plot insertion, which today is covered only by mocked geometry tests. (§ Visualization & Plotting, Phase A known limitations)
  • [feature S many] LLM tool surface for text analytics, which is reachable only through the dialog, Run Python Script or python_run_script. (§ Text / Document Analytics)
  • [fidelity S few] Show the truncated (analyzed_chars / total_chars) note in the Text Analytics dialog formatter. (§ Text / Document Analytics)
  • [feature M few] Add pulp and ortools backends to the Optimization helpers beyond the shipped scipy.optimize ones. (§ Optimization & Operations Research)
  • [feature M few] Bayesian optimization helper using scikit-optimize. (§ New Domain Proposals)
  • [idea S few] pyarrow IO module (plugin/scripting/io.py) and a calc.convert() Calc-parity wrapper for units. (§ Data Engineering / Units (Pint))
  • [feature L few] Geospatial map_data helper producing a static map image plus attribute table from location columns, with a Geo Helpers script section. (§ Geospatial)
  • [feature M few] Audio analysis helpers (analyze_audio, spectrogram_plot) using librosa in the venv with Audio Helpers templates. (§ Audio / Signal Processing)
  • [fidelity S many] Theme-aware matplotlib styles that follow the LibreOffice light or dark appearance. (§ Cross-cutting ergonomic improvements)
  • [fidelity S many] Light default formatting (bold header, fill, percent and decimal formats) when tabular analysis results are written to Calc. (§ Cross-cutting ergonomic improvements)
  • [fidelity S many] Route Vision extract_structure table results straight into Calc cell ranges instead of HTML only. (§ Domain-specific polish opportunities)
  • [feature S many] Status progress message such as "Initializing OCR engine..." on the first heavy OCR model load. (§ Domain-specific polish opportunities)
  • [fidelity S few] Unpack multi-solution solve_equation results into 1D/2D Calc arrays under =PY(). (§ Domain-specific polish opportunities)
  • [feature S few] Optional evaluate / float_precision parameter on solve_equation and symbolic_simplify for decimal approximations. (§ Domain-specific polish opportunities)
  • [fidelity S few] Template examples and warnings for offset temperature conversions (degC versus delta_degC) in Units helpers. (§ Domain-specific polish opportunities)
  • [fidelity S few] Human-readable dimension descriptions when check_dimensionality finds incompatible units. (§ Domain-specific polish opportunities)
  • [feature S few] Default target_col to the last column and feature_cols to the preceding numeric columns in regression when omitted. (§ Domain-specific polish opportunities)
  • [feature S many] Summary KPI banner (MAPE, expected next value, trend percent) above the forecast table. (§ Domain-specific polish opportunities)
  • [feature M many] Writer in-document highlighting of detected entities or low-readability sentences. (§ Domain-specific polish opportunities)
  • [fidelity S few] Show relative percentage topic weights per section in topics output. (§ Domain-specific polish opportunities)
  • [fidelity S few] Clarify cell-range parameter mapping in the optimize_portfolio and linear_program templates. (§ Domain-specific polish opportunities)