@datagrok/curves 1.10.15 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Curves changelog
2
2
 
3
+ ## 1.11.0 (2026-03-13)
4
+
5
+ ## 1.10.15 (2025-12-02)
6
+
7
+ * Png Renderer: Fix flickering and moved to PowerGrid
8
+
3
9
  ## 1.10.12 (2025-09-16)
4
10
 
5
11
  * GROK-18808: Provided consistent names for Data top menu
@@ -58,7 +64,7 @@
58
64
  * Data-to-curves: fully covered script with history, datasync and 2 tier support
59
65
  * Raw PNG renderer
60
66
 
61
- ## 1.6.0 - 1.8.0 (2025-03-31)
67
+ ## 1.8.0 (2025-03-31)
62
68
 
63
69
  ### Features
64
70
 
@@ -90,6 +96,10 @@
90
96
  * Fit panel: Fixed namings and inputs
91
97
  * GROK-17492: Fixed error when adding statistics column if the series has no name
92
98
 
99
+ ## 1.6.0 (2024-09-09)
100
+
101
+ * Fixed tests
102
+
93
103
  ## 1.5.0 (2024-08-23)
94
104
 
95
105
  ### Features
package/CLAUDE.md ADDED
@@ -0,0 +1,265 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Overview
6
+
7
+ **Curves** (`@datagrok/curves`) is a Datagrok plugin for **fitted curves** — dose-response curves, sigmoid fits, and general curve fitting. It provides in-grid cell rendering of charts stored in various formats in cells, interactive editing (outlier toggling, property panels), automatic curve fitting, a "Data to Curves" pipeline that converts well-level assay data into fitted curve summaries, a multi-curve overlay viewer, and statistics extraction (IC50, AUC, R², etc.).
8
+
9
+ Category: **Visualizations**. Top menu: `Data | Curves | ...`.
10
+
11
+ ## Build Commands
12
+
13
+ ```bash
14
+ npm install
15
+ npm run build # grok api && grok check --soft && webpack
16
+ npm run test # grok test
17
+ npm run build-all # Builds js-api → utils → statistics → this package
18
+ npm run link-all # Links datagrok-api, @datagrok-libraries/utils, @datagrok-libraries/statistics
19
+ ```
20
+
21
+ ## Key Dependencies
22
+
23
+ - `@datagrok-libraries/statistics` — **core fitting engine**: defines `IFitChartData`, `IFitSeries`, `IFitChartOptions`, `IFitPoint`, `FitStatistics`, `FitCurve`, `FitFunction` classes, Nelder-Mead optimizer, sigmoid/linear/log-linear/exponential/4PL fit functions, confidence intervals, box-plot statistics, and `FitConstants` (tags, sizing, thresholds)
24
+ - `@datagrok-libraries/utils` — `Viewport` (world↔screen coordinate transform), `StringUtils`
25
+ - `@datagrok-libraries/test` — test framework (`category`, `test`, `expect`)
26
+ - `jstat` — statistical distributions
27
+ - `wu` — lazy iteration
28
+ - `exceljs` — Excel file support
29
+ - `dayjs` — date manipulation
30
+ - `rxjs` — reactive subscriptions (debounce, merge)
31
+
32
+ ### Data Model (from `@datagrok-libraries/statistics`)
33
+
34
+ The **native format** for curve data in cells is JSON conforming to `IFitChartData`:
35
+ ```
36
+ IFitChartData {
37
+ chartOptions?: IFitChartOptions // axes bounds, log scale, title, axis names, showStatistics
38
+ seriesOptions?: IFitSeriesOptions // default series options (fit function, colors, markers)
39
+ series?: IFitSeries[] // array of data series
40
+ }
41
+ ```
42
+ Each `IFitSeries` has `points: IFitPoint[]` (x, y, outlier, color, marker, stdev) plus fit configuration (fitFunction, parameters, colors, showFitLine, clickToToggle, droplines, etc.).
43
+
44
+ Options cascade: **DataFrame tags → Column tags → Cell JSON → Series defaults**, merged at render time.
45
+
46
+ ## Curve Converter Architecture
47
+
48
+ The Curves package supports **multiple curve data formats** through a dynamic converter system. The central format is the native IFitChartData JSON. Other formats (XML 3DX, compact dose-response, PZFX, etc.) are converted to native format on-the-fly via registered converters.
49
+
50
+ ### How It Works
51
+
52
+ 1. **Detection**: Semantic type detectors in `detectors.js` identify curve data in columns. Each detector:
53
+ - Sets `col.semType = 'fit'`
54
+ - For non-native formats, sets column tag `.%curve-format` to a friendly format name (e.g. `3dx`, `compact-dr`, `pzfx`)
55
+ - If no format tag is set, the data is assumed to be in native IFitChartData JSON format
56
+
57
+ 2. **Conversion**: When a cell value needs to be parsed, `parseCellValue()` in `curve-converter.ts`:
58
+ - Checks the column's `.%curve-format` tag for the format name
59
+ - If present, looks up the converter function by format name in the registry and applies it
60
+ - If absent, parses the value directly as JSON
61
+ - Results are cached in a value-based `DG.LruCache` keyed by `formatName||cellValue`
62
+
63
+ 3. **Registration**: Converters are registered in `_initCurves()` via `registerCurveConverter(formatName, fn)`:
64
+ - Local converters (in this package) are registered directly by format name to avoid circular dependencies
65
+ - External converters (from other packages) are discovered via `initExternalConverters()` which finds DG functions tagged with `meta.role: curveConverter` and `meta.curveFormat: '<name>'`
66
+
67
+ ### Key Constants
68
+
69
+ - `FitConstants.TAG_CURVE_FORMAT` = `'.%curve-format'` — column tag storing format name (e.g. `'3dx'`, `'compact-dr'`, `'pzfx'`)
70
+ - `FitConstants.FIT_SEM_TYPE` = `'fit'` — semantic type for fit curves
71
+ - `FitConstants.TAG_FIT_CHART_FORMAT` = `'.fitChartFormat'` — legacy tag for format identification
72
+
73
+ ### Supported Formats
74
+
75
+ | Format | Detector | Format Name | File |
76
+ |--------|----------|-------------|------|
77
+ | **Native JSON** (IFitChartData) | `detectFit` — looks for `series` + `points` | None (native) | — |
78
+ | **XML 3DX** (`<chart>...</chart>`) | `detectXMLCurveChart` | `3dx` | `fit/converters/xml-converter.ts` |
79
+ | **Compact Dose-Response** (`{"p":..., "poi":...}`) | `detectCompactDoseResponse` | `compact-dr` | `fit/converters/compact-dr-converter.ts` |
80
+ | **PZFX** (GraphPad Prism XY) | `detectPzfxCurveChart` | `pzfx` | `fit/converters/pzfx-converter.ts` |
81
+
82
+ ### Adding a New Format
83
+
84
+ To add support for a new curve format, use the `/add-curve-format` skill. In summary:
85
+ 1. Create a converter function in `src/fit/converters/` that converts the format to native JSON
86
+ 2. Add a detector in `detectors.js` that identifies the format and sets the converter tag
87
+ 3. Register the converter in `_initCurves()` in `package.ts`
88
+ 4. Add tests in `src/tests/converter-tests.ts`
89
+
90
+ ## Architecture
91
+
92
+ ### Entry Point — `src/package.ts`
93
+
94
+ `PackageFunctions` class registers all platform-visible functions via `@grok.decorators`:
95
+
96
+ **Initialization:**
97
+ - `_initCurves` — `@init`: registers `FitGridCellHandler`, registers all local curve converters, discovers external converters
98
+
99
+ **Registered Functions:**
100
+
101
+ | Function | Decorator / Meta | Purpose |
102
+ |---|---|---|
103
+ | `curveFitDemo` | `@demo`, `demoPath: Curves \| Curve Fitting` | Loads demo CSV and opens table view |
104
+ | `dataToCurves` | `@func` | Programmatic API: converts well-level data into a DataFrame with fitted curve JSON column |
105
+ | `dataToCurvesTopMenu` | `@func`, `top-menu: Data \| Curves \| Data to Curves` | Opens the Data to Curves dialog UI |
106
+ | `addStatisticsColumn` | `@func`, `vectorFunc`, `role: transform` | Extracts a fit statistic from a specific series into a new float column |
107
+ | `addAggrStatisticsColumn` | `@func`, `vectorFunc`, `role: transform` | Aggregates statistics across all series |
108
+ | `convertXmlCurveToJsonFunc` | `@func`, `role: curveConverter` | Returns XML 3DX converter function |
109
+ | `convertCompactDrToJsonFunc` | `@func`, `role: curveConverter` | Returns compact dose-response converter function |
110
+ | `convertPzfxToJsonFunc` | `@func`, `role: curveConverter` | Returns PZFX converter function |
111
+
112
+ ### Converter Infrastructure — `src/fit/curve-converter.ts`
113
+
114
+ Central module for the converter system:
115
+ - `registerCurveConverter(nqName, fn)` — registers a converter function
116
+ - `initExternalConverters()` — discovers converters from external packages via `DG.Func.find({meta: {role: 'curveConverter'}})`
117
+ - `parseCellValue(cellValue, column)` — **the single entry point** for parsing any cell value; applies converter if needed
118
+ - `convertCellValue(cellValue, column)` — converts using registered converter, with value-based LRU caching
119
+ - `isNativeFormat(column)` / `hasConverter(column)` — check whether a column uses native or converted format
120
+
121
+ ### Semantic Type Detectors — `detectors.js`
122
+
123
+ `CurvesPackageDetectors` detects columns with semantic type `fit`:
124
+ 1. `detectXMLCurveChart` — matches `<chart>...</chart>`, sets converter tag
125
+ 2. `detectFit` — matches native JSON with `series` + `points`
126
+ 3. `detectPzfxCurveChart` — matches PZFX XY table XML
127
+ 4. `detectCompactDoseResponse` — matches compact DR JSON with `p` + `poi` fields
128
+
129
+ ### Cell Renderer — `src/fit/fit-renderer.ts`
130
+
131
+ `FitChartCellRenderer` (extends `DG.GridCellRenderer`) — the main grid cell renderer for `fit` cells:
132
+ - **Caching**: three `DG.LruCache` instances: `parsedCurves` (parsed IFitChartData), `fittedCurves` (fitted curve results), `curvesDataPoints` (extracted data points)
133
+ - **render()**: parses cell via `parseCellValue()` → renders axes, fit lines, points, confidence intervals, droplines, statistics, title, legend
134
+ - **onClick()**: toggles outlier status on points (native format only), updates dependent statistics columns
135
+ - **onDoubleClick()**: opens `inspectCurve` dialog (resizable chart editor)
136
+ - **onMouseMove()**: shows tooltip with x/y values on point hover
137
+ - Outlier toggling is only available for native format columns (`isNativeFormat()`)
138
+
139
+ Key helper functions:
140
+ - `getOrCreateParsedChartData(cell)` — cached parse with options merge (DF → Column → Cell cascade)
141
+ - `getOrCreateCachedFitCurve(series, ...)` — cached Nelder-Mead fit
142
+ - `substituteZeroes(data)` — replaces x=0 with calculated substitute when logX is enabled
143
+ - `setOutlier(gridCell, point, ...)` — toggles outlier, updates cell JSON, fires custom event
144
+ - `layoutChart(rect, ...)` — computes viewport, xAxis, yAxis rectangles with margins
145
+
146
+ ### Property Panel — `src/fit/fit-grid-cell-handler.ts`
147
+
148
+ `FitGridCellHandler` (extends `DG.ObjectHandler`) — renders the context panel when a fit cell is selected:
149
+ - **Options pane**: switch level (Dataframe/Column/Cell), series and chart options
150
+ - **Chart pane**: enlarged `GridCellWidget` rendering
151
+ - **Fit pane**: per-series or aggregated statistics with "+" buttons to extract stats as columns
152
+ - Uses `parseCellValue()` for format-agnostic cell parsing
153
+
154
+ ### Rendering Utilities — `src/fit/render-utils.ts`
155
+
156
+ Low-level canvas drawing functions using `CanvasRenderingContext2D`:
157
+
158
+ | Function | What it renders |
159
+ |---|---|
160
+ | `renderPoints` | Data points (circles, markers) and error bars |
161
+ | `renderFitLine` | Fitted curve line (solid/dotted/dashed/dashdotted) |
162
+ | `renderConfidenceIntervals` | Shaded confidence bands |
163
+ | `renderConnectDots` | Direct point-to-point line connections |
164
+ | `renderDroplines` | IC50 droplines |
165
+ | `renderStatistics` | In-chart text labels for selected statistics |
166
+ | `renderTitle` | Chart title |
167
+ | `renderAxesLabels` | X and Y axis name labels |
168
+ | `renderLegend` | Color-coded legend |
169
+
170
+ ### Converters — `src/fit/converters/`
171
+
172
+ Each converter is a pure function: `(value: string) => string` (raw cell value → native JSON string).
173
+
174
+ | File | Function | Source Format |
175
+ |------|----------|---------------|
176
+ | `xml-converter.ts` | `convertXmlCurveToJson` | XML 3DX `<chart>` documents |
177
+ | `compact-dr-converter.ts` | `convertCompactDrToJson` | Compact dose-response JSON (`{p, poi, mxr, mnr, hs, ...}`) |
178
+ | `pzfx-converter.ts` | `convertPzfxToJson` | GraphPad Prism PZFX XY tables |
179
+
180
+ ### XML Parser — `src/fit/fit-parser.ts`
181
+
182
+ `convertXMLToIFitChartData(xmlText)` — parses legacy 3DX XML format `<chart>` documents into `IFitChartData`. Used by the XML converter. Reorders parameters from `[IC50, tan, max, min]` to `[max, tan, IC50, min]`.
183
+
184
+ ### Data to Curves — `src/fit/data-to-curves.ts`
185
+
186
+ The main data transformation pipeline. `convertDataToCurves()` groups well-level assay data by compound|assay|target|run and builds fitted curve JSON.
187
+
188
+ ### Multi-Curve Viewer — `src/fit/multi-curve-viewer.ts`
189
+
190
+ `MultiCurveViewer` (extends `DG.JsViewer`) — superimposes curves from multiple rows/columns on one chart. Supports trellis mode, selection/current/mouseover tracking, and legend columns.
191
+
192
+ ### PZFX Parser — `src/formats/pzfx/pzfx-parser.ts`
193
+
194
+ Parses GraphPad Prism `.pzfx` files. Also used by the PZFX converter and the file viewer/handler.
195
+
196
+ ## Tests — `src/tests/`
197
+
198
+ Test entry point: `src/package-test.ts` — imports all test files.
199
+
200
+ | File | What it tests |
201
+ |---|---|
202
+ | `detector-tests.ts` | Semantic type detection for all formats (JSON, XML, compact DR, PZFX) |
203
+ | `converter-tests.ts` | All converters (XML, compact DR, PZFX), caching, format detection, rendering integration |
204
+ | `fit-tests.ts` | Core fitting algorithms (sigmoid, linear, log-linear, exponential, polynomial) |
205
+ | `curves-cell-renderer-tests.ts` | Cell renderer creation and rendering performance |
206
+ | `transform-tests.ts` | Viewport coordinate transformations |
207
+ | `pzfx-tests.ts` | PZFX file parser |
208
+
209
+ ## Source Structure
210
+
211
+ ```
212
+ src/
213
+ package.ts — Entry point, PackageFunctions, converter registration
214
+ package.g.ts — Auto-generated function wrappers (DO NOT EDIT)
215
+ package-api.ts — Auto-generated API namespace (DO NOT EDIT)
216
+ package-test.ts — Test entry point
217
+ fit/
218
+ curve-converter.ts — Converter registry, LRU cache, parseCellValue() entry point
219
+ fit-renderer.ts — FitChartCellRenderer, caching, chart layout, merging
220
+ fit-grid-cell-handler.ts — FitGridCellHandler (property panel), stats calculation
221
+ render-utils.ts — Canvas drawing functions (points, lines, CIs, droplines, legend)
222
+ fit-parser.ts — XML 3DX → IFitChartData parser (used by xml-converter)
223
+ data-to-curves.ts — Data to Curves pipeline (UI dialog + conversion logic)
224
+ multi-curve-viewer.ts — MultiCurveViewer (overlay viewer)
225
+ fit-inspection.ts — inspectSeries helper
226
+ fit-demo.ts — Demo data generation and demo entry point
227
+ converters/
228
+ xml-converter.ts — XML 3DX format converter
229
+ compact-dr-converter.ts — Compact dose-response JSON converter
230
+ pzfx-converter.ts — PZFX (GraphPad Prism) format converter
231
+ formats/
232
+ pzfx/
233
+ pzfx-parser.ts — PZFX file parser
234
+ tests/
235
+ detector-tests.ts — Semantic type detector tests (all formats)
236
+ converter-tests.ts — Converter tests (all formats, caching, integration)
237
+ fit-tests.ts — Fitting algorithm tests
238
+ curves-cell-renderer-tests.ts — Renderer benchmarks
239
+ transform-tests.ts — Viewport transform tests
240
+ pzfx-tests.ts — PZFX parser tests
241
+ scripts/
242
+ calculateMSR.py — MSR calculation (Python, statsmodels)
243
+ files/
244
+ curves-demo.csv — Demo data
245
+ detectors.js — Semantic type detectors (all curve formats)
246
+ ```
247
+
248
+ ## Quick Lookups
249
+
250
+ | Looking for... | Check first |
251
+ |---|---|
252
+ | Adding a new curve format | Use `/add-curve-format` skill |
253
+ | Converter infrastructure | `src/fit/curve-converter.ts` |
254
+ | Existing converters | `src/fit/converters/` |
255
+ | Function/demo/init registration | `src/package.ts` |
256
+ | Cell renderer (render, click, tooltip) | `src/fit/fit-renderer.ts` |
257
+ | Property panel (options, stats, chart) | `src/fit/fit-grid-cell-handler.ts` |
258
+ | Canvas drawing (points, lines, axes) | `src/fit/render-utils.ts` |
259
+ | Data to Curves dialog & conversion | `src/fit/data-to-curves.ts` |
260
+ | Multi-curve overlay viewer | `src/fit/multi-curve-viewer.ts` |
261
+ | XML 3DX format parsing | `src/fit/fit-parser.ts` |
262
+ | Fit data types (IFitChartData, etc.) | `@datagrok-libraries/statistics/src/fit/fit-curve.ts` |
263
+ | Constants (tags, sizes, thresholds) | `@datagrok-libraries/statistics/src/fit/const.ts` |
264
+ | Semantic type detection | `detectors.js` |
265
+ | Test entry point | `src/package-test.ts` |
package/detectors.js CHANGED
@@ -8,22 +8,24 @@
8
8
  const FIT_SEM_TYPE = 'fit';
9
9
  const TAG_FIT_CHART_FORMAT = '.fitChartFormat';
10
10
  const TAG_FIT_CHART_FORMAT_3DX = '3dx';
11
+ const TAG_CURVE_FORMAT = '.%curve-format';
11
12
  const likelyPNGColNames = ['image', 'png', 'thumbnail', 'img', 'glyph', 'icon', 'picture', 'photo'];
12
13
  /// <reference path="../../globals.d.ts" />
13
14
  class CurvesPackageDetectors extends DG.Package {
14
- //tags: semTypeDetector
15
+ //meta.role: semTypeDetector
15
16
  //input: column col
16
17
  //output: string semType
17
18
  detectXMLCurveChart(col) {
18
19
  if (DG.Detector.sampleCategories(col, (s) => s.startsWith('<chart>') && s.endsWith('</chart>'), 1)) {
19
20
  col.setTag(TAG_FIT_CHART_FORMAT, TAG_FIT_CHART_FORMAT_3DX);
21
+ col.setTag(TAG_CURVE_FORMAT, '3dx');
20
22
  col.semType = FIT_SEM_TYPE;
21
23
  return col.semType;
22
24
  }
23
25
  return null;
24
26
  }
25
27
 
26
- //tags: semTypeDetector
28
+ //meta.role: semTypeDetector
27
29
  //input: column col
28
30
  //output: string semType
29
31
  detectFit(col) {
@@ -35,4 +37,39 @@ class CurvesPackageDetectors extends DG.Package {
35
37
  }
36
38
  return null;
37
39
  }
40
+
41
+ //meta.role: semTypeDetector
42
+ //input: column col
43
+ //output: string semType
44
+ detectPzfxCurveChart(col) {
45
+ if (DG.Detector.sampleCategories(col, (s) => {
46
+ return s.includes('<Table') && s.includes('TableType="XY"') && s.includes('<XColumn');
47
+ }, 1)) {
48
+ col.setTag(TAG_CURVE_FORMAT, 'pzfx');
49
+ col.semType = FIT_SEM_TYPE;
50
+ return col.semType;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ //meta.role: semTypeDetector
56
+ //input: column col
57
+ //output: string semType
58
+ detectCompactDoseResponse(col) {
59
+ if (DG.Detector.sampleCategories(col, (s) => {
60
+ try {
61
+ if (!s.includes('"p"') || !s.includes('"poi"'))
62
+ return false;
63
+ const obj = JSON.parse(s);
64
+ return obj.p !== undefined && Array.isArray(obj.p) && obj.poi !== undefined;
65
+ } catch (_e) {
66
+ return false;
67
+ }
68
+ }, 1)) {
69
+ col.setTag(TAG_CURVE_FORMAT, 'compact-dr');
70
+ col.semType = FIT_SEM_TYPE;
71
+ return col.semType;
72
+ }
73
+ return null;
74
+ }
38
75
  }