@datagrok/curves 1.10.14 → 1.11.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,233 @@
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 as JSON/XML 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
+ Cell values are JSON strings 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
+ Legacy XML format (3DX `<chart>...</chart>`) is auto-detected and converted to JSON via `fit-parser.ts`.
45
+
46
+ Options cascade: **DataFrame tags → Column tags → Cell JSON → Series defaults**, merged at render time.
47
+
48
+ ## Architecture
49
+
50
+ ### Entry Point — `src/package.ts`
51
+
52
+ `PackageFunctions` class registers all platform-visible functions via `@grok.decorators`:
53
+
54
+ **Initialization:**
55
+ - `_initCurves` — `@init`: registers `FitGridCellHandler` as an `ObjectHandler` for grid cell property panels
56
+
57
+ **Registered Functions:**
58
+
59
+ | Function | Decorator / Meta | Purpose |
60
+ |---|---|---|
61
+ | `curveFitDemo` | `@demo`, `demoPath: Curves \| Curve Fitting` | Loads demo CSV and opens table view |
62
+ | `dataToCurves` | `@func` | Programmatic API: converts well-level data (concentration, readout, batch/compound/assay/run IDs) into a DataFrame with fitted curve JSON column. Supports parent-table join for pre-fit parameters, reported IC50s, etc. |
63
+ | `dataToCurvesTopMenu` | `@func`, `top-menu: Data \| Curves \| Data to Curves` | Opens the Data to Curves dialog UI |
64
+ | `addStatisticsColumn` | `@func`, `vectorFunc`, `role: transform` | Extracts a single fit statistic (e.g., IC50, AUC, R²) from a specific series into a new float column |
65
+ | `addAggrStatisticsColumn` | `@func`, `vectorFunc`, `role: transform` | Same but aggregates across all series using a DG.Stats aggregation (min, max, avg, med, etc.) |
66
+
67
+ **Exports**: `_package`, `Sync` (sequential promise runner), auto-generated wrappers from `package.g.ts`
68
+
69
+ ### Semantic Type Detector — `detectors.js`
70
+
71
+ `CurvesPackageDetectors` detects columns with semantic type `fit`:
72
+ 1. `detectXMLCurveChart` — matches strings starting with `<chart>` and ending with `</chart>`, sets tag `.fitChartFormat = '3dx'`
73
+ 2. `detectFit` — matches JSON strings containing both `series` and `points` keywords
74
+
75
+ ### Cell Renderer — `src/fit/fit-renderer.ts`
76
+
77
+ `FitChartCellRenderer` (extends `DG.GridCellRenderer`) — the main grid cell renderer for `fit` cells:
78
+ - **Caching**: three `DG.LruCache` instances: `parsedCurves` (parsed JSON), `fittedCurves` (fitted curve results), `curvesDataPoints` (extracted data points)
79
+ - **render()**: parses cell → gets chart data → renders axes, fit lines, points, confidence intervals, droplines, statistics, title, legend
80
+ - **onClick()**: toggles outlier status on points (if `clickToToggle` is enabled), updates dependent statistics columns
81
+ - **onDoubleClick()**: opens `inspectCurve` dialog (resizable chart editor)
82
+ - **onMouseMove()**: shows tooltip with x/y values on point hover; shows enlarged chart tooltip for small cells
83
+ - **Visibility thresholds**: axes, labels, title, legend, points, droplines each have minimum pixel-size thresholds from `FitConstants`
84
+
85
+ Key helper functions:
86
+ - `getOrCreateParsedChartData(cell)` — cached JSON parse with options merge (DF → Column → Cell cascade)
87
+ - `getOrCreateCachedFitCurve(series, ...)` — cached Nelder-Mead fit
88
+ - `substituteZeroes(data)` — replaces x=0 with calculated substitute when logX is enabled
89
+ - `setOutlier(gridCell, point, ...)` — toggles outlier, updates cell JSON, fires custom event, recalculates stats columns
90
+ - `inspectCurve(gridCell)` — opens a dialog with a `GridCellWidget` for interactive chart editing
91
+ - `layoutChart(rect, ...)` — computes viewport, xAxis, yAxis rectangles with margins
92
+ - `mergeChartOptions(...)` / `mergeSeries(...)` — combine options/series from multiple cells
93
+ - `mergeProperties(properties, source, target)` — cascading property merge
94
+
95
+ ### Property Panel — `src/fit/fit-grid-cell-handler.ts`
96
+
97
+ `FitGridCellHandler` (extends `DG.ObjectHandler`) — renders the context panel when a fit cell is selected:
98
+ - **Options pane**: switch level (Dataframe/Column/Cell), series options (fit function, colors, markers, line style, confidence intervals), chart options (log scale, axes bounds, zeroes handling)
99
+ - **Chart pane**: enlarged `GridCellWidget` rendering
100
+ - **Fit pane**: displays per-series or aggregated statistics (R², AUC, IC50, slope, top, bottom) with "+" buttons to extract each stat as a new column
101
+
102
+ Also contains:
103
+ - `calculateSeriesStats()` — computes `FitStatistics` for a single series (uses cached fit curve)
104
+ - `getChartDataAggrStats()` — aggregates statistics across all series using DG.Stats
105
+ - `changeCurvesOptions()` — applies property changes at Dataframe/Column/Cell level
106
+ - `detectSettings()` — scans column to detect which options are custom per-cell vs default
107
+
108
+ ### Rendering Utilities — `src/fit/render-utils.ts`
109
+
110
+ Low-level canvas drawing functions, all using `CanvasRenderingContext2D`:
111
+
112
+ | Function | What it renders |
113
+ |---|---|
114
+ | `renderPoints` | Data points (circles, markers) and error bars (stdev whiskers) |
115
+ | `renderFitLine` | Fitted curve line (with line style: solid/dotted/dashed/dashdotted) |
116
+ | `renderConfidenceIntervals` | Shaded confidence bands around fit line |
117
+ | `renderConnectDots` | Direct point-to-point line connections |
118
+ | `renderDroplines` | IC50 droplines (dashed lines from axis to curve) |
119
+ | `renderStatistics` | In-chart text labels for selected statistics |
120
+ | `renderTitle` | Chart title above the plot area |
121
+ | `renderAxesLabels` | X and Y axis name labels |
122
+ | `renderLegend` | Color-coded legend with series names, markers, and optional column labels |
123
+
124
+ Also: `getSeriesColor()`, candlestick/box-plot rendering (for replicate data visualization).
125
+
126
+ ### XML Parser — `src/fit/fit-parser.ts`
127
+
128
+ `convertXMLToIFitChartData(xmlText)` — parses legacy 3DX XML format `<chart>` documents into `IFitChartData`. Extracts grid bounds, axis labels, series parameters (reorders from `[IC50, tan, max, min]` to `[max, tan, IC50, min]`), points, and outlier masks.
129
+
130
+ ### Data to Curves — `src/fit/data-to-curves.ts`
131
+
132
+ The main data transformation pipeline:
133
+
134
+ **`dataToCurvesUI()`** — dialog with two forms:
135
+ - **Well Table Form**: table, assay, concentration, readout, batch ID, run ID, compound ID, target entity, outliers, additional columns (auto-detects columns by name heuristics)
136
+ - **Parent Table Form**: optional table with pre-fit parameters (Max/Hill/Inflection/Min), reported IC50, qualified IC50, experiment ID, qualifier, fit function selection (4PL dose-response or 4PL regression), use-prefit-params toggle
137
+ - **Join Editor**: columns to join well-level and parent-level data
138
+ - Supports dialog history for re-running with same settings
139
+
140
+ **`convertDataToCurves()`** — core logic:
141
+ 1. Groups well-level rows by compound|assay|target|run (or custom join column)
142
+ 2. Builds `IFitSeries` per curve with points sorted by x, outlier flags, per-run marker types, categorical colors
143
+ 3. Assigns pre-fit parameters from parent table if available
144
+ 4. Creates result DataFrame with: `Fitted Curve` column (JSON, semType=fit), `Compound|Assay|Target` grouping column, info columns (assay, batch, compound, target, run, reported IC50, etc.)
145
+ 5. Computes aggregated stats: max percent inhibition, geomean IC50, standard deviation, total/reported result counts
146
+ 6. Auto-adds calculated statistics columns (IC50, Max, Min, Hill, AUC) if no parent table
147
+ 7. Sets up layout: trellis plot with MultiCurveViewer, selected curves grid, overlay viewer
148
+
149
+ ### Multi-Curve Viewer — `src/fit/multi-curve-viewer.ts`
150
+
151
+ `MultiCurveViewer` (extends `DG.JsViewer`) — superimposes curves from multiple rows/columns on one chart:
152
+ - Properties: `curvesColumnNames` (column list), `legendColumnName`, `showSelectedRowsCurves`, `showCurrentRowCurve`, `showMouseOverRowCurve`, `mergeColumnSeries`, `showOutliers`, plus all `IFitChartOptions` properties
153
+ - Reacts to: current cell change, mouse-over row, selection change (debounced 50ms)
154
+ - Merges chart options from all visible cells, assigns categorical colors, adjusts opacity for large selections
155
+ - Supports trellis mode (uses filter instead of selection/current)
156
+ - `fromChartData(chartData)` — static factory for standalone use
157
+
158
+ ### Fit Inspection — `src/fit/fit-inspection.ts`
159
+
160
+ `inspectSeries(series, fitFunctionName)` — creates a temporary single-row DataFrame with the series as a fit cell, opens it in the inspect dialog with click-to-toggle and IC50 droplines. Used for programmatic curve inspection.
161
+
162
+ ### Demo — `src/fit/fit-demo.ts`
163
+
164
+ - `createSigmoidPoints(length, step, pointsPerX)` — generates random sigmoid data with noise
165
+ - `createDemoDataFrame(rowCount, chartsCount, chartsPerCell)` — builds a full demo DataFrame with multiple fit columns
166
+ - `curveDemo()` — loads `files/curves-demo.csv` and opens it
167
+
168
+ ### Python Script — `scripts/calculateMSR.py`
169
+
170
+ `Calculate MSR` — computes Minimum Significant Ratio using mixed-effects linear models (statsmodels). Groups by compound, assay, target entity; uses log10(IC50) with run dates as random effects. Falls back to simple variance calculation for small sample sizes. Top menu: `Data | Curves | Calculate MSR...`.
171
+
172
+ ## Tests — `src/tests/`
173
+
174
+ Test entry point: `src/package-test.ts` — imports all test files.
175
+
176
+ | File | What it tests |
177
+ |---|---|
178
+ | `fit-tests.ts` | Core fitting: `getSeriesFitFunction`, `getCurve`, `fitSeries` (sigmoid, linear, log-linear, exponential, polynomial), confidence intervals, statistics, benchmarks |
179
+ | `detector-tests.ts` | Semantic type detection for JSON fit data and XML 3DX format |
180
+ | `curves-cell-renderer-tests.ts` | Cell renderer creation and rendering performance benchmarks |
181
+ | `transform-tests.ts` | Viewport coordinate transformations (world↔screen) |
182
+
183
+ ## Source Structure
184
+
185
+ ```
186
+ src/
187
+ package.ts — Entry point, PackageFunctions, Sync helper
188
+ package.g.ts — Auto-generated function wrappers (DO NOT EDIT)
189
+ package-api.ts — Auto-generated API namespace (scripts, funcs)
190
+ package-test.ts — Test entry point
191
+ fit/
192
+ fit-renderer.ts — FitChartCellRenderer, caching, chart layout, merging
193
+ fit-grid-cell-handler.ts — FitGridCellHandler (property panel), stats calculation
194
+ render-utils.ts — Canvas drawing functions (points, lines, CIs, droplines, legend)
195
+ fit-parser.ts — XML 3DX → IFitChartData converter
196
+ data-to-curves.ts — Data to Curves pipeline (UI dialog + conversion logic)
197
+ multi-curve-viewer.ts — MultiCurveViewer (overlay viewer)
198
+ fit-inspection.ts — inspectSeries helper
199
+ fit-demo.ts — Demo data generation and demo entry point
200
+ tests/
201
+ fit-tests.ts — Fitting algorithm tests
202
+ detector-tests.ts — Semantic type detector tests
203
+ curves-cell-renderer-tests.ts — Renderer benchmarks
204
+ transform-tests.ts — Viewport transform tests
205
+ scripts/
206
+ calculateMSR.py — MSR calculation (Python, statsmodels)
207
+ files/
208
+ curves-demo.csv — Demo data
209
+ detectors.js — Semantic type detectors (XML and JSON fit formats)
210
+ ```
211
+
212
+ ## Quick Lookups
213
+
214
+ | Looking for... | Check first |
215
+ |---|---|
216
+ | Function/demo/init registration | `src/package.ts` |
217
+ | Cell renderer (render, click, tooltip) | `src/fit/fit-renderer.ts` (`FitChartCellRenderer`) |
218
+ | Property panel (options, stats, chart) | `src/fit/fit-grid-cell-handler.ts` (`FitGridCellHandler`) |
219
+ | Canvas drawing (points, lines, axes) | `src/fit/render-utils.ts` |
220
+ | Data to Curves dialog & conversion | `src/fit/data-to-curves.ts` |
221
+ | Multi-curve overlay viewer | `src/fit/multi-curve-viewer.ts` |
222
+ | XML 3DX format parsing | `src/fit/fit-parser.ts` |
223
+ | Inspect/edit a single curve | `src/fit/fit-inspection.ts` + `inspectCurve` in `fit-renderer.ts` |
224
+ | Fit data types (IFitChartData, etc.) | `@datagrok-libraries/statistics/src/fit/fit-curve.ts` |
225
+ | Fit functions & optimizer | `@datagrok-libraries/statistics/src/fit/fit-data.ts` |
226
+ | Constants (tags, sizes, thresholds) | `@datagrok-libraries/statistics/src/fit/const.ts` |
227
+ | New fit API (FitFunction classes) | `@datagrok-libraries/statistics/src/fit/new-fit-API.ts` |
228
+ | Viewport (coordinate transforms) | `@datagrok-libraries/utils/src/transform.ts` |
229
+ | Semantic type detection | `detectors.js` |
230
+ | MSR calculation (Python) | `scripts/calculateMSR.py` |
231
+ | Auto-generated function wrappers | `src/package.g.ts` / `src/package-api.ts` |
232
+ | Test entry point | `src/package-test.ts` |
233
+ | Demo data | `files/curves-demo.csv` |
package/detectors.js CHANGED
@@ -8,11 +8,10 @@
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 RAW_PNG_SEM_TYPE = 'rawPng';
12
11
  const likelyPNGColNames = ['image', 'png', 'thumbnail', 'img', 'glyph', 'icon', 'picture', 'photo'];
13
12
  /// <reference path="../../globals.d.ts" />
14
13
  class CurvesPackageDetectors extends DG.Package {
15
- //tags: semTypeDetector
14
+ //meta.role: semTypeDetector
16
15
  //input: column col
17
16
  //output: string semType
18
17
  detectXMLCurveChart(col) {
@@ -24,7 +23,7 @@ class CurvesPackageDetectors extends DG.Package {
24
23
  return null;
25
24
  }
26
25
 
27
- //tags: semTypeDetector
26
+ //meta.role: semTypeDetector
28
27
  //input: column col
29
28
  //output: string semType
30
29
  detectFit(col) {
@@ -36,17 +35,4 @@ class CurvesPackageDetectors extends DG.Package {
36
35
  }
37
36
  return null;
38
37
  }
39
-
40
- //tags: semTypeDetector
41
- //input: column col
42
- //output: string semType
43
- detectRawPng(col) {
44
- const colName = col.name.toLowerCase();
45
- if (col.type === DG.COLUMN_TYPE.STRING &&
46
- likelyPNGColNames.some((name) => colName.includes(name)) && DG.Detector.sampleCategories(col, (s) => {
47
- return s && s.length > 1000 && s.startsWith('iVBORw0KGgo');
48
- }, 1))
49
- return RAW_PNG_SEM_TYPE;
50
- return null;
51
- }
52
38
  }