@datagrok/curves 1.12.1 → 1.13.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/CLAUDE.md +118 -15
  3. package/README.md +51 -4
  4. package/dist/package-test.js +7963 -4867
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3411 -2024
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +5 -4
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/curve-converter.ts +8 -1
  12. package/src/fit/data-to-curves.ts +10 -5
  13. package/src/fit/fit-chart-data.ts +323 -0
  14. package/src/fit/fit-grid-cell-handler.ts +98 -231
  15. package/src/fit/fit-inspection.ts +3 -3
  16. package/src/fit/fit-interaction.ts +181 -0
  17. package/src/fit/fit-layout.ts +64 -0
  18. package/src/fit/fit-legend.ts +292 -0
  19. package/src/fit/fit-options.ts +222 -0
  20. package/src/fit/fit-parser.ts +16 -5
  21. package/src/fit/fit-renderer.ts +180 -469
  22. package/src/fit/fit-statistics.ts +154 -0
  23. package/src/fit/multi-curve-viewer.ts +46 -20
  24. package/src/fit/render-utils.ts +208 -150
  25. package/src/package-api.ts +92 -14
  26. package/src/package-test.ts +6 -0
  27. package/src/package.g.ts +70 -15
  28. package/src/package.ts +121 -15
  29. package/src/tests/calculated-columns-tests.ts +299 -0
  30. package/src/tests/converter-tests.ts +29 -0
  31. package/src/tests/curve-data.ts +82 -0
  32. package/src/tests/fit-cache-tests.ts +128 -0
  33. package/src/tests/fit-tests.ts +310 -3
  34. package/src/tests/legend-tests.ts +243 -0
  35. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  36. package/src/tests/panel-renderer-tests.ts +502 -0
  37. package/src/tests/project-tests.ts +99 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +357 -110
  40. package/test-record-1.mp4 +0 -0
@@ -0,0 +1,299 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ import {category, test, expect, expectArray, expectFloat, awaitCheck} from '@datagrok-libraries/test/src/test';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
7
+ import {getStatistic} from '@datagrok-libraries/statistics/src/fit/fit-engine';
8
+ import {getChartDataAggrStats, aggregatedStatisticsProperties, calculateSeriesFit, curveStatisticAt} from '../fit/fit-statistics';
9
+ import {setOutlier} from '../fit/fit-interaction';
10
+ import {getOrCreateParsedChartData} from '../fit/fit-chart-data';
11
+ import {CONCENTRATIONS, curveJson, multiSeriesCurveJson} from './curve-data';
12
+ import {addStatisticColumn as addStatisticColumnFromPanel} from '../fit/fit-grid-cell-handler';
13
+
14
+ /** Same curve, but with logX left to the column level rather than baked into the cell. */
15
+ function curveJsonNoChartOptions(logIC50: number): string {
16
+ const parsed = JSON.parse(curveJson(logIC50));
17
+ delete parsed.chartOptions;
18
+ return JSON.stringify(parsed);
19
+ }
20
+
21
+ function curveTable(name: string, logIC50s: number[]): DG.DataFrame {
22
+ const col = DG.Column.fromStrings('curve', logIC50s.map(curveJson));
23
+ col.semType = FitConstants.FIT_SEM_TYPE;
24
+ const df = DG.DataFrame.fromColumns([col]);
25
+ df.name = name;
26
+ return df;
27
+ }
28
+
29
+ /** Runs a curve statistic function the way the property panel's "+" button does. */
30
+ async function addStatisticColumn(df: DG.DataFrame, funcName: string,
31
+ params: {[key: string]: string | number}): Promise<void> {
32
+ await DG.Func.find({name: funcName})[0]
33
+ .prepare({table: df, curveColumn: df.col('curve')!, ...params})
34
+ .call(false, undefined, {processed: false});
35
+ }
36
+
37
+ /** Grid column names in grid order; index 0 is the row header, which has no name. */
38
+ function gridColumnNames(grid: DG.Grid): string[] {
39
+ const names: string[] = [];
40
+ for (let i = 0; i < grid.columns.length; i++) {
41
+ const name = grid.columns.byIndex(i)?.name;
42
+ if (name)
43
+ names.push(name);
44
+ }
45
+ return names;
46
+ }
47
+
48
+ category('calculated columns', () => {
49
+ test('the statistic column is added right after the curve column', async () => {
50
+ // `join(table)` appends, so the position the legacy addStatisticsColumn inserted at is restored
51
+ const df = curveTable('calcColPosition', [-6.5]);
52
+ df.columns.addNewString('trailing').set(0, 'x');
53
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
54
+
55
+ await addStatisticColumnFromPanel(gridCell, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
56
+
57
+ expectArray(df.columns.names(), ['curve', 'curve 1 ic50', 'trailing']);
58
+ // the grid only takes a position from the dataframe when it first builds a GridColumn
59
+ expectArray(gridColumnNames(gridCell.grid), ['curve', 'curve 1 ic50', 'trailing']);
60
+ });
61
+
62
+ test('placing the statistic column keeps a manually reordered grid', async () => {
63
+ // a dragged grid is no longer in dataframe order, and must not be snapped back to it
64
+ const df = curveTable('calcColGridOrder', [-6.5]);
65
+ df.columns.addNewString('a').set(0, 'x');
66
+ df.columns.addNewString('b').set(0, 'y');
67
+ const grid = DG.Viewer.grid(df);
68
+ grid.columns.setOrder(['b', 'curve', 'a']);
69
+
70
+ await addStatisticColumnFromPanel(grid.cell('curve', 0), 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
71
+
72
+ expectArray(gridColumnNames(grid), ['b', 'curve', 'curve 1 ic50', 'a']);
73
+ expectArray(df.columns.names(), ['curve', 'curve 1 ic50', 'a', 'b']);
74
+ });
75
+
76
+ test('plot-level labels combine across levels instead of the nearest one winning', async () => {
77
+ // labels are data rather than a setting: an assay name on the column and a plate statistic on the
78
+ // cell both belong on the plot, which a whole-property merge would not allow
79
+ const cell = JSON.stringify({
80
+ chartOptions: {logX: true, labels: {'Z prime': 0.72}},
81
+ series: [{fitFunction: 'sigmoid', name: 's', points: CONCENTRATIONS.map((x) => ({x: x, y: x}))}],
82
+ });
83
+ const col = DG.Column.fromStrings('curve', [cell]);
84
+ col.semType = FitConstants.FIT_SEM_TYPE;
85
+ const df = DG.DataFrame.fromColumns([col]);
86
+ df.name = 'calcColLabels';
87
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {labels: {'assay': 'GPCR', 'Z prime': 0.1}}}));
88
+
89
+ const labels = getOrCreateParsedChartData(df.cell(0, 'curve')).chartOptions!.labels!;
90
+ expect(labels['assay'], 'GPCR', 'the column-level label did not reach the plot');
91
+ expectFloat(labels['Z prime'] as number, 0.72, 0.001);
92
+ });
93
+
94
+ test('curveStatistic adds a calculated column', async () => {
95
+ const df = curveTable('calcColAdd', [-6.5, -6.5]);
96
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
97
+
98
+ const col = df.col('curve 1 ic50');
99
+ expect(col !== null);
100
+ expect(col!.type, DG.COLUMN_TYPE.FLOAT);
101
+ // the statistic must come back in data space, not as the log-space fitted parameter
102
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
103
+
104
+ // the platform owns the formula, and binds the curve column as a column rather than a per-row value
105
+ expect(col!.getTag(DG.TAGS.FORMULA).includes('Curves:curveStatistic'));
106
+ expect(col!.getTag(DG.TAGS.FORMULA).includes('${curve}'));
107
+ expect(col!.getTag('.%formula-column-is-vector-func'), 'true');
108
+ });
109
+
110
+ test('recalculates when the source curve changes', async () => {
111
+ const df = curveTable('calcColRecalc', [-6.5, -6.5]);
112
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
113
+ const before = df.col('curve 1 ic50')!.get(1);
114
+
115
+ // an unstable result name, or reading through column.dataFrame, leaves this silently stale
116
+ df.col('curve')!.set(1, curveJson(-5.0), true);
117
+ await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
118
+ 'statistic column did not recalculate after the source curve changed', 5000);
119
+
120
+ expectFloat(Math.log10(df.col('curve 1 ic50')!.get(1)), -5.0, 0.3);
121
+ expect(df.col('curve 1 ic50')!.get(0), before, 'untouched row must not be recalculated');
122
+ });
123
+
124
+ test('legacy statistic names still resolve', async () => {
125
+ const df = curveTable('calcColLegacy', [-6.5]);
126
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'interceptX', seriesNumber: 0});
127
+
128
+ // interceptX is the pre-refactor name for the sigmoid inflection point
129
+ const col = df.col('curve 1 interceptX');
130
+ expect(col !== null);
131
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
132
+ });
133
+
134
+ test('curveAggrStatistic aggregates across series', async () => {
135
+ const df = curveTable('calcColAggr', [-6.5, -5.5]);
136
+ await addStatisticColumn(df, 'curveAggrStatistic', {propName: 'ic50', aggrType: 'med'});
137
+
138
+ const col = df.col('curve med ic50');
139
+ expect(col !== null);
140
+ // single-series cells, so the median across series is that series' own IC50
141
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
142
+ expectFloat(Math.log10(col!.get(1)), -5.5, 0.15);
143
+ });
144
+
145
+ test('averaging IC50 across series is a geometric mean', async () => {
146
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
147
+
148
+ // aggregated in log space, so 1e-7 and 1e-5 give 1e-6; per-series conversion would give 5.05e-6
149
+ expectFloat(Math.log10(getChartDataAggrStats(data, 'avg').ic50!), -6, 0.1);
150
+ });
151
+
152
+ test('mixed fit functions only aggregate statistics common to all series', async () => {
153
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
154
+ data.series![1].fitFunction = 'linear';
155
+
156
+ // ic50 belongs to the sigmoid only; rSquared is produced by both
157
+ const names = aggregatedStatisticsProperties(data).map((p) => p.name);
158
+ expect(names.includes('ic50'), false, 'ic50 is not viable across a sigmoid and a linear fit');
159
+ expect(names.includes('rSquared'), true);
160
+ expect(getChartDataAggrStats(data, 'avg').ic50 === undefined, true, 'ic50 must not be aggregated over a subset');
161
+ });
162
+
163
+ test('repeated calculation does not re-log stored parameters', async () => {
164
+ // an IC50 above 1 stays positive after one log, so an in-place conversion drifts: 100 -> 2 -> 0.301
165
+ const series = JSON.parse(curveJson(-6.5)).series[0];
166
+ series.parameters = [100, 1, 100, 5];
167
+ const logX = {logX: true, logY: false};
168
+
169
+ const first = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
170
+ const second = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
171
+ expect(first, second, 'stored parameters drifted between calls');
172
+ expectFloat(first!, 100, 1);
173
+ });
174
+
175
+ test('fitting a series does not write fit-space parameters back onto it', async () => {
176
+ // the first call fits; writing the log-space parameters back would make the second log them again
177
+ const data = JSON.parse(multiSeriesCurveJson([2])) as IFitChartData;
178
+ const series = data.series![0];
179
+ const logX = {logX: true, logY: false};
180
+
181
+ const first = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
182
+ expect(series.parameters === undefined, true, 'the series must keep its data-space contract');
183
+ const second = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
184
+ expect(first, second, 'the reported IC50 drifted between calls');
185
+ });
186
+
187
+ test('recalculation applies column-level chart options', async () => {
188
+ const col = DG.Column.fromStrings('curve', [curveJsonNoChartOptions(-6.5), curveJsonNoChartOptions(-6.5)]);
189
+ col.semType = FitConstants.FIT_SEM_TYPE;
190
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {logX: true}}));
191
+ const df = DG.DataFrame.fromColumns([col]);
192
+ df.name = 'calcColColumnOptions';
193
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
194
+ const before = df.col('curve 1 ic50')!.get(1);
195
+
196
+ df.col('curve')!.set(1, curveJsonNoChartOptions(-5.0), true);
197
+ await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
198
+ 'statistic column did not recalculate', 5000);
199
+
200
+ // the detached recalculation column has no dataframe, so it must read logX off its own tags
201
+ expectFloat(Math.log10(df.col('curve 1 ic50')!.get(1)), -5.0, 0.3);
202
+ });
203
+
204
+ test('log-space statistics are not offered for aggregations we do not convert', async () => {
205
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
206
+
207
+ // pIC50 is only derived during the conversion, so it is the one that cannot be produced
208
+ const counted = aggregatedStatisticsProperties(data, 'count').map((p) => p.name);
209
+ expect(counted.includes('pIC50'), false, 'pIC50 is only derived in data space');
210
+ expect(counted.includes('rSquared'), true, 'space-independent statistics stay');
211
+
212
+ // ic50 stays available and is reported in fit space, which is what a stdev of it should be, and
213
+ // what a saved project recorded before this refactor - it must not come back as a null column
214
+ expect(counted.includes('ic50'), true, 'ic50 must stay available for aggregations we do not convert');
215
+ expectFloat(getChartDataAggrStats(data, 'avg').ic50!, 1e-6, 1e-7);
216
+ expectFloat(getChartDataAggrStats(data, 'count').ic50!, 2, 0.001);
217
+ expectFloat(getChartDataAggrStats(data, 'count').interceptX!, 2, 0.001);
218
+ });
219
+
220
+ test('stored parameters round-trip through fit space on both axes', async () => {
221
+ // seriesInFitSpace and toDataSpace must be inverses, or a top of 100 comes back as 1e100
222
+ for (const logOptions of [{logX: false, logY: false}, {logX: true, logY: false},
223
+ {logX: false, logY: true}, {logX: true, logY: true}]) {
224
+ const series = JSON.parse(curveJson(-6.5)).series[0];
225
+ series.parameters = [100, 1, 1e-6, 5];
226
+ const fit = calculateSeriesFit(series, 0, logOptions, undefined, false);
227
+
228
+ expectFloat(getStatistic(fit, 'top')!, 100, 1e-6, `top under ${JSON.stringify(logOptions)}`);
229
+ expectFloat(getStatistic(fit, 'bottom')!, 5, 1e-6, `bottom under ${JSON.stringify(logOptions)}`);
230
+ expectFloat(getStatistic(fit, 'ic50')!, 1e-6, 1e-12, `ic50 under ${JSON.stringify(logOptions)}`);
231
+ }
232
+ });
233
+
234
+ test('a detached column strips the stray pipe like the initial parse does', async () => {
235
+ // recalculation hands the function a detached column, whose parse must sanitize the value too
236
+ const col = DG.Column.fromStrings('curve', [curveJson(-6.5).replace('{', '{|')]);
237
+ col.semType = FitConstants.FIT_SEM_TYPE;
238
+ expect(col.dataFrame === null || col.dataFrame === undefined, true, 'the column must be detached');
239
+
240
+ const value = curveStatisticAt(col, 0, 'ic50', 0);
241
+ expect(value !== null, true, 'a pipe in the cell value blanked the row');
242
+ expectFloat(Math.log10(value!), -6.5, 0.3);
243
+ });
244
+
245
+ test('a legacy statistic reads the same per series and aggregated', async () => {
246
+ // `top` on a linear fit resolves through the positional fallback, per series and aggregated alike
247
+ const data = JSON.parse(multiSeriesCurveJson([-6.5])) as IFitChartData;
248
+ data.series![0].fitFunction = 'linear';
249
+ const logX = {logX: true, logY: false};
250
+
251
+ const perSeries = getStatistic(calculateSeriesFit(data.series![0], 0, logX, undefined, false), 'top');
252
+ const aggregated = getChartDataAggrStats(data, 'med').top;
253
+ expect(perSeries !== undefined, true, 'the per-series path lost the fallback');
254
+ expect(aggregated !== undefined, true, 'the aggregated path drops a statistic the per-series one reports');
255
+ });
256
+
257
+ test('a legacy name and its canonical field agree after aggregation', async () => {
258
+ // interceptX aliases onto ic50, so collecting it before the conversion leaves it in fit space
259
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
260
+ const stats = getChartDataAggrStats(data, 'avg');
261
+
262
+ expect(stats.interceptX, stats.ic50, 'interceptX must be reported in the same space as ic50');
263
+ expectFloat(Math.log10(stats.interceptX!), -6, 0.1);
264
+ });
265
+
266
+ test('mergeSeries does not change a statistic', async () => {
267
+ // it merges on a copy for the plot only, so it cannot change an extracted statistic
268
+ const plain = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
269
+ const merged = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
270
+ merged.chartOptions!.mergeSeries = true;
271
+ const logX = {logX: true, logY: false};
272
+
273
+ for (const i of [0, 1]) {
274
+ const a = getStatistic(calculateSeriesFit(plain.series![i], i, logX, undefined, false), 'ic50');
275
+ const b = getStatistic(calculateSeriesFit(merged.series![i], i, logX, undefined, false), 'ic50');
276
+ expect(a, b, `series ${i} changed when mergeSeries was set`);
277
+ }
278
+ expect(getChartDataAggrStats(merged, 'med').ic50, getChartDataAggrStats(plain, 'med').ic50);
279
+ });
280
+
281
+ test('outlier toggle refreshes statistic columns named by the new API', async () => {
282
+ const df = curveTable('calcColOutlierToggle', [-6.5]);
283
+ const stat = DG.Column.float('ic50 col', df.rowCount);
284
+ // tags the legacy "+" writes; ic50 has no slot in the seven legacy keys
285
+ stat.tags['.sourceColumn'] = 'curve';
286
+ stat.tags['.seriesNumber'] = '0';
287
+ stat.tags['.statistics'] = 'ic50';
288
+ stat.init(() => 1e-6);
289
+ df.columns.add(stat);
290
+
291
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
292
+ const data = getOrCreateParsedChartData(gridCell.cell, true);
293
+ setOutlier(gridCell, data.series![0].points[0], 0, 0, data);
294
+
295
+ const value = df.col('ic50 col')!.get(0);
296
+ expect(value != null && !isNaN(value), true, 'outlier toggle blanked the ic50 column');
297
+ expectFloat(Math.log10(value), -6.5, 0.3);
298
+ });
299
+ });
@@ -78,6 +78,29 @@ category('converters', () => {
78
78
  expect(chartData.chartOptions?.logX, true);
79
79
  });
80
80
 
81
+ test('xmlConverter.booleanAttributes', async () => {
82
+ // XML attributes are strings, so `!!getAttribute(...)` read "False" as true - real 3DX exports
83
+ // carry drawLine="False" on most series and would have drawn a fit line anyway
84
+ const off = SAMPLE_XML.replace('drawLine="True"', 'drawLine="False"').replace('logX="true"', 'logX="false"');
85
+ const chartData: IFitChartData = JSON.parse(convertXmlCurveToJson(off));
86
+ expect(chartData.series![0].showFitLine, false);
87
+ expect(chartData.chartOptions?.logX, false);
88
+
89
+ const on: IFitChartData = JSON.parse(convertXmlCurveToJson(SAMPLE_XML));
90
+ expect(on.series![0].showFitLine, true);
91
+ expect(on.chartOptions?.logX, true);
92
+ });
93
+
94
+ test('xmlConverter.logYNotInvented', async () => {
95
+ // an always-present key owns it, and mergeProperties only fills absent ones - so emitting
96
+ // logY: false would stop a Column or Dataframe level option cascading onto the cell
97
+ const chartData: IFitChartData = JSON.parse(convertXmlCurveToJson(SAMPLE_XML));
98
+ expect('logY' in chartData.chartOptions!, false, 'the cell must not own logY when the export omits it');
99
+
100
+ const declared = SAMPLE_XML.replace('logX="true"', 'logX="true" logY="true"');
101
+ expect(JSON.parse(convertXmlCurveToJson(declared)).chartOptions.logY, true);
102
+ });
103
+
81
104
  test('xmlConverter.parameterReordering', async () => {
82
105
  const result = convertXmlCurveToJson(SAMPLE_XML);
83
106
  const chartData: IFitChartData = JSON.parse(result);
@@ -181,6 +204,12 @@ category('converters', () => {
181
204
  expect(chartData.series !== undefined && chartData.series.length === 0, true);
182
205
  });
183
206
 
207
+ test('parseCellValue.malformedJson', async () => {
208
+ // Unquoted-key value that passes the substring-based fit detection but is not valid JSON.
209
+ const chartData = parseCellValue('{series: [{name: "A", points: [{x:0,y:50}]}]}', null);
210
+ expect(chartData.series !== undefined && chartData.series.length === 0, true);
211
+ });
212
+
184
213
  test('converterCaching', async () => {
185
214
  registerCurveConverter('compact-dr', convertCompactDrToJson);
186
215
 
@@ -0,0 +1,82 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as ui from 'datagrok-api/ui';
3
+
4
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {FitChartCellRenderer} from '../fit/fit-renderer';
7
+ import {isTitleShown, layoutChart, shownAxesNames} from '../fit/fit-layout';
8
+ import {getOrCreateParsedChartData} from '../fit/fit-chart-data';
9
+
10
+ /** Renders a cell onto a canvas and returns every string the chart drew, with where it put it and
11
+ * the plot it was laid out in - which is what the legend hover is asked about. */
12
+ export function renderedRows(json: string, name: string, width: number = 400, height: number = 300):
13
+ {rows: {text: string, x: number, y: number}[], data: IFitChartData, dataBox: DG.Rect} {
14
+ const col = DG.Column.fromStrings('curve', [json]);
15
+ col.semType = FitConstants.FIT_SEM_TYPE;
16
+ const df = DG.DataFrame.fromColumns([col]);
17
+ df.name = name;
18
+
19
+ const rows: {text: string, x: number, y: number}[] = [];
20
+ const g = ui.canvas(width, height).getContext('2d')!;
21
+ const fillText = g.fillText.bind(g);
22
+ g.fillText = ((text: string, x: number, y: number) => {
23
+ rows.push({text: text, x: x, y: y});
24
+ fillText(text, x, y);
25
+ }) as any;
26
+
27
+ const rect = new DG.Rect(0, 0, width, height);
28
+ const data = getOrCreateParsedChartData(df.cell(0, 'curve'));
29
+ new FitChartCellRenderer().renderCurves(g, rect, data);
30
+ const axesNames = shownAxesNames(rect, data);
31
+ const dataBox = layoutChart(rect, axesNames.x, axesNames.y, isTitleShown(rect, data))[0];
32
+ return {rows: rows, data: data, dataBox: dataBox};
33
+ }
34
+
35
+ /** Every string the chart drew. */
36
+ export function renderedTexts(json: string, name: string, width: number = 400, height: number = 300): string[] {
37
+ return renderedRows(json, name, width, height).rows.map((row) => row.text);
38
+ }
39
+
40
+ export const CONCENTRATIONS = [1e-9, 3e-9, 1e-8, 3e-8, 1e-7, 3e-7, 1e-6, 3e-6, 1e-5, 3e-5, 1e-4];
41
+
42
+ /** Sigmoid dose-response points with the inflection point at 10^`logIC50`. */
43
+ export function sigmoidPoints(logIC50: number): {x: number, y: number}[] {
44
+ return CONCENTRATIONS.map((x) => ({x: x, y: 5 + 95 / (1 + Math.pow(10, Math.log10(x) - logIC50))}));
45
+ }
46
+
47
+ /** One sigmoid series in a cell, with logX baked into the cell's chart options. */
48
+ export function curveJson(logIC50: number): string {
49
+ return JSON.stringify({
50
+ chartOptions: {logX: true},
51
+ series: [{fitFunction: 'sigmoid', name: 'series', points: sigmoidPoints(logIC50)}],
52
+ } as IFitChartData);
53
+ }
54
+
55
+ /** One sigmoid series that declares a confidence interval, the way the demo data does. */
56
+ export function ciCurveJson(): string {
57
+ return JSON.stringify({
58
+ chartOptions: {logX: true},
59
+ series: [{fitFunction: 'sigmoid', name: 'series', showCurveConfidenceInterval: true, points: sigmoidPoints(-6.5)}],
60
+ } as IFitChartData);
61
+ }
62
+
63
+ /** One cell holding several sigmoid series, each with its own inflection point. */
64
+ export function multiSeriesCurveJson(logIC50s: number[]): string {
65
+ return JSON.stringify({
66
+ chartOptions: {logX: true},
67
+ series: logIC50s.map((logIC50, i) => ({
68
+ fitFunction: 'sigmoid', name: `series ${i}`, points: sigmoidPoints(logIC50),
69
+ })),
70
+ } as IFitChartData);
71
+ }
72
+
73
+ /** Two sigmoid series, one plot-level label and one per curve. */
74
+ export function labelledCurveJson(): string {
75
+ return JSON.stringify({
76
+ chartOptions: {logX: true, labels: {'Z prime': 0.72}, showLabels: ['Z prime', 'compound']},
77
+ series: [
78
+ {fitFunction: 'sigmoid', name: 's0', labels: {compound: 'GRK-1'}, points: sigmoidPoints(-6.5)},
79
+ {fitFunction: 'sigmoid', name: 's1', labels: {compound: 'GRK-2'}, points: sigmoidPoints(-5.5)},
80
+ ],
81
+ } as IFitChartData);
82
+ }
@@ -0,0 +1,128 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as ui from 'datagrok-api/ui';
3
+
4
+ import {category, test, expect} from '@datagrok-libraries/test/src/test';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
7
+ import {getSeriesFitFunction} from '@datagrok-libraries/statistics/src/fit/fit-data';
8
+ import {FitChartCellRenderer} from '../fit/fit-renderer';
9
+ import {chartDataId, getOrCreateCachedFitCurve, getOrCreateParsedChartData, viewerFits} from '../fit/fit-chart-data';
10
+
11
+ import {curveJson, multiSeriesCurveJson} from './curve-data';
12
+
13
+ /** A one-curve table, and the cell the caches are keyed on. */
14
+ function curveCell(name: string, logIC50: number = -6.5): DG.Cell {
15
+ const col = DG.Column.fromStrings('curve', [curveJson(logIC50)]);
16
+ col.semType = FitConstants.FIT_SEM_TYPE;
17
+ const df = DG.DataFrame.fromColumns([col]);
18
+ df.name = name;
19
+ return df.cell(0, 'curve');
20
+ }
21
+
22
+ category('fit cache', () => {
23
+ test('a curve fitted in log space is not handed to a linear plot', async () => {
24
+ // the grid, the property panel and a trellis can each show one cell in a different space at once
25
+ const cell = curveCell('fitCacheLogSpace');
26
+ const series = getOrCreateParsedChartData(cell).series![0];
27
+ const fitFunc = getSeriesFitFunction(series);
28
+
29
+ const inLog = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: true, logY: false}, cell);
30
+ const linear = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: false, logY: false}, cell);
31
+ expect(Array.from(inLog.parameters).toString() !== Array.from(linear.parameters).toString(), true,
32
+ `the two spaces should fit differently, both gave ${Array.from(inLog.parameters)}`);
33
+
34
+ const again = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: true, logY: false}, cell);
35
+ expect(again === inLog, true, 'asking twice in the same space should come from the cache');
36
+ });
37
+
38
+ test('a viewer fit is reused, and never confused with another cell', async () => {
39
+ // both at row 0, which with an unsaved table is most of what the grid's key looks at
40
+ const one = curveCell('fitCacheRowsOne', -7);
41
+ const other = curveCell('fitCacheRowsOther', -5);
42
+ const oneData = getOrCreateParsedChartData(one);
43
+ const otherData = getOrCreateParsedChartData(other);
44
+ expect(chartDataId(oneData) !== chartDataId(otherData), true, 'two cells should not share an identity');
45
+
46
+ const logOptions = {logX: true, logY: false};
47
+ const fitFunc = getSeriesFitFunction(oneData.series![0]);
48
+ const first = getOrCreateCachedFitCurve(oneData.series![0], 0, fitFunc, logOptions, undefined, false,
49
+ `${chartDataId(oneData)} || idx: 0`);
50
+ const second = getOrCreateCachedFitCurve(otherData.series![0], 0, fitFunc, logOptions, undefined, false,
51
+ `${chartDataId(otherData)} || idx: 0`);
52
+ expect(first === second, false, 'two different curves must not answer for each other');
53
+ expect(Array.from(first.parameters).toString() !== Array.from(second.parameters).toString(), true,
54
+ 'and they fit differently, so a collision would be visible');
55
+
56
+ const repeat = getOrCreateCachedFitCurve(oneData.series![0], 0, fitFunc, logOptions, undefined, false,
57
+ `${chartDataId(oneData)} || idx: 0`);
58
+ expect(repeat === first, true, 'the same curve should be fitted once');
59
+ });
60
+
61
+ test('the viewer cache is kept apart from the grid one, and agrees with it', async () => {
62
+ const cell = curveCell('fitCacheApart');
63
+ const data = getOrCreateParsedChartData(cell);
64
+ const series = data.series![0];
65
+ const fitFunc = getSeriesFitFunction(series);
66
+ const logOptions = {logX: true, logY: false};
67
+
68
+ const forGrid = getOrCreateCachedFitCurve(series, 0, fitFunc, logOptions, cell);
69
+ const forViewer = getOrCreateCachedFitCurve(series, 0, fitFunc, logOptions, cell, true,
70
+ `${chartDataId(data)} || idx: 0`);
71
+ expect(forGrid === forViewer, false, 'the two caches must not share storage');
72
+ expect(Array.from(forGrid.parameters).toString(), Array.from(forViewer.parameters).toString(),
73
+ 'but keeping them apart must not change the answer');
74
+ });
75
+
76
+ test('a render that names its curves fits them once', async () => {
77
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
78
+ const g = ui.canvas(300, 200).getContext('2d')!;
79
+ const bounds = new DG.Rect(0, 0, 300, 200);
80
+ const identities = ['probeCell || idx: 0', 'probeCell || idx: 1'];
81
+ new FitChartCellRenderer().renderCurves(g, bounds, data, undefined, identities);
82
+
83
+ const keys = (viewerFits as unknown as {K: string[]}).K.filter(Boolean);
84
+ expect(identities.every((id) => keys.some((k) => k.startsWith(id))), true,
85
+ `the render should have cached a fit per identity, holds ${keys.length}`);
86
+
87
+ let refitted = false;
88
+ const options = data.chartOptions;
89
+ viewerFits.getOrCreate(`${identities[0]} || logX: ${options?.logX} || logY: ${options?.logY}`, () => {
90
+ refitted = true;
91
+ return null as any;
92
+ });
93
+ expect(refitted, false, 'a second render of the same curve should not fit it again');
94
+ });
95
+
96
+ test('a pipe in a title survives, and one that breaks the value is still stripped', async () => {
97
+ const titled = JSON.parse(curveJson(-6.5)) as IFitChartData;
98
+ titled.chartOptions!.title = 'compound 10 | Collapse Assay | run 4';
99
+ // the second value is valid only once the stray pipe is gone
100
+ const col = DG.Column.fromStrings('curve', [JSON.stringify(titled), '{"series":|[{"points":[]}]}']);
101
+ col.semType = FitConstants.FIT_SEM_TYPE;
102
+ const df = DG.DataFrame.fromColumns([col]);
103
+ df.name = 'pipeTitles';
104
+
105
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).chartOptions!.title,
106
+ 'compound 10 | Collapse Assay | run 4', 'a pipe inside a title is not part of the value');
107
+ // the rescue still applies to a value the pipes actually break
108
+ expect(getOrCreateParsedChartData(df.cell(1, 'curve')).series!.length, 1,
109
+ 'stripping should still rescue a value that does not parse as it stands');
110
+ });
111
+
112
+ test('editing a cell retires the fits made from it', async () => {
113
+ const cell = curveCell('fitCacheEdit', -7);
114
+ const before = getOrCreateParsedChartData(cell);
115
+ const fitFunc = getSeriesFitFunction(before.series![0]);
116
+ const logOptions = {logX: true, logY: false};
117
+ const beforeFit = getOrCreateCachedFitCurve(before.series![0], 0, fitFunc, logOptions, undefined, false,
118
+ `${chartDataId(before)} || idx: 0`);
119
+
120
+ cell.column.set(0, curveJson(-5));
121
+ const after = getOrCreateParsedChartData(cell);
122
+ expect(chartDataId(after) !== chartDataId(before), true, 'a re-parsed cell should get a new identity');
123
+ const afterFit = getOrCreateCachedFitCurve(after.series![0], 0, fitFunc, logOptions, undefined, false,
124
+ `${chartDataId(after)} || idx: 0`);
125
+ expect(Array.from(afterFit.parameters).toString() !== Array.from(beforeFit.parameters).toString(), true,
126
+ 'so the edited curve is fitted afresh');
127
+ });
128
+ });