@datagrok/curves 1.12.2 → 1.13.1

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 +8819 -5223
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3014 -1659
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +2 -2
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/data-to-curves.ts +11 -6
  12. package/src/fit/fit-chart-data.ts +330 -0
  13. package/src/fit/fit-grid-cell-handler.ts +102 -235
  14. package/src/fit/fit-inspection.ts +3 -3
  15. package/src/fit/fit-interaction.ts +181 -0
  16. package/src/fit/fit-layout.ts +64 -0
  17. package/src/fit/fit-legend.ts +292 -0
  18. package/src/fit/fit-options.ts +222 -0
  19. package/src/fit/fit-parser.ts +16 -5
  20. package/src/fit/fit-renderer.ts +180 -469
  21. package/src/fit/fit-statistics.ts +154 -0
  22. package/src/fit/multi-curve-viewer.ts +48 -22
  23. package/src/fit/render-utils.ts +208 -150
  24. package/src/package-api.ts +78 -0
  25. package/src/package-test.ts +7 -0
  26. package/src/package.g.ts +59 -11
  27. package/src/package.ts +97 -18
  28. package/src/tests/calculated-columns-tests.ts +299 -0
  29. package/src/tests/converter-tests.ts +23 -0
  30. package/src/tests/curve-data.ts +82 -0
  31. package/src/tests/fit-cache-tests.ts +128 -0
  32. package/src/tests/fit-tests.ts +344 -4
  33. package/src/tests/legend-tests.ts +243 -0
  34. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  35. package/src/tests/panel-renderer-tests.ts +502 -0
  36. package/src/tests/project-tests.ts +99 -0
  37. package/src/tests/statistics-tests.ts +127 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +410 -109
  40. package/test-record-1.mp4 +0 -0
@@ -0,0 +1,502 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+ import * as ui from 'datagrok-api/ui';
4
+ import * as grok from 'datagrok-api/grok';
5
+
6
+ import {category, test, expect, expectArray, expectFloat, awaitCheck, delay} from '@datagrok-libraries/test/src/test';
7
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
8
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
9
+ import {FitChartCellRenderer} from '../fit/fit-renderer';
10
+ import {stdevWhisker} from '../fit/render-utils';
11
+ import {FitGridCellHandler} from '../fit/fit-grid-cell-handler';
12
+ import {normalizeStatisticNames, chartPropertiesFor, changeCurvesOptions, seriesPropertiesFor} from '../fit/fit-options';
13
+ import {sigmoidPoints, ciCurveJson, labelledCurveJson, curveJson, renderedTexts} from './curve-data';
14
+ import {multiSeriesCurveJson} from './curve-data';
15
+ import {getOrCreateParsedChartData, getColumnChartOptions} from '../fit/fit-chart-data';
16
+ import {getSeriesFitFunction} from '@datagrok-libraries/statistics/src/fit/fit-data';
17
+ import {fitFunctions, fitFunctionDescriptions} from '@datagrok-libraries/statistics/src/fit/fit-engine';
18
+
19
+ /** Curve carrying stored parameters whose inflection point is above 1, where converting in place
20
+ * would log it again on the next pass. */
21
+ function curveWithParameters(): IFitChartData {
22
+ return {
23
+ chartOptions: {logX: true},
24
+ series: [{fitFunction: 'sigmoid', name: 'series', parameters: [100, 1, 100, 5], points: sigmoidPoints(-6.5)}],
25
+ } as IFitChartData;
26
+ }
27
+
28
+ function curveTable(name: string, chartOptions: boolean, showStatistics?: string[]): DG.DataFrame {
29
+ const cell = JSON.stringify({
30
+ ...(chartOptions ? {chartOptions: {logX: true, ...(showStatistics ? {showStatistics} : {})}} : {}),
31
+ series: [{fitFunction: 'sigmoid', name: 'series', points: sigmoidPoints(-6.5)}],
32
+ });
33
+ const col = DG.Column.fromStrings('curve', [cell, cell]);
34
+ col.semType = FitConstants.FIT_SEM_TYPE;
35
+ const df = DG.DataFrame.fromColumns([col]);
36
+ df.name = name;
37
+ return df;
38
+ }
39
+
40
+ async function addStatisticColumn(df: DG.DataFrame, params: {[key: string]: string | number}): Promise<void> {
41
+ await DG.Func.find({package: 'Curves', name: 'curveStatistic'})[0]
42
+ .prepare({table: df, curveColumn: df.col('curve')!, ...params})
43
+ .call(false, undefined, {processed: false});
44
+ }
45
+
46
+ category('panel and renderer', () => {
47
+ test('every registered aggregation input offers only convertible aggregations', async () => {
48
+ // enumerated from the registry: a hand-written list of the ones we fixed missed a third
49
+ const CONVERTIBLE = ['min', 'max', 'avg', 'med', 'q1', 'q2', 'q3'];
50
+ const checked: string[] = [];
51
+ for (const func of DG.Func.find({package: 'Curves'})) {
52
+ for (const input of func.inputs.filter((p: DG.Property) => /^(aggrType|aggregation)$/.test(p.name))) {
53
+ checked.push(func.name);
54
+ expect(input.choices !== undefined && input.choices !== null, true,
55
+ `${func.name} takes a free-text aggregation`);
56
+ for (const choice of input.choices!)
57
+ expect(CONVERTIBLE.includes(choice), true, `${func.name} offers ${choice}`);
58
+ }
59
+ }
60
+ expect(checked.length >= 3, true, `expected every aggregation function to be checked, saw ${checked}`);
61
+ });
62
+
63
+ test('rendering does not mutate the cached series parameters', async () => {
64
+ const chartData = curveWithParameters();
65
+ const before = [...chartData.series![0].parameters!];
66
+
67
+ const canvas = ui.canvas(200, 120);
68
+ const g = canvas.getContext('2d')!;
69
+ const renderer = new FitChartCellRenderer();
70
+ const bounds = FitChartCellRenderer.inflateScreenBounds(new DG.Rect(0, 0, 200, 120));
71
+ // the cached chart data is shared with the statistics, so a repaint must not convert in place
72
+ renderer.renderCurves(g, bounds, chartData);
73
+ renderer.renderCurves(g, bounds, chartData);
74
+
75
+ expectArray(chartData.series![0].parameters!, before);
76
+ });
77
+
78
+ test('firing values-changed on a curve column recalculates its statistic columns', async () => {
79
+ // logX lives only on the column, so flipping it changes the space the curve is fitted in
80
+ const df = curveTable('panelColumnOption', false);
81
+ const col = df.col('curve')!;
82
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {logX: true}}));
83
+ await addStatisticColumn(df, {propName: 'ic50', seriesNumber: 0});
84
+ const before = df.col('curve 1 ic50')!.get(0);
85
+ expectFloat(Math.log10(before), -6.5, 0.3);
86
+
87
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {logX: false}}));
88
+ // pins the platform contract the panel relies on, not the call site in changeCurvesOptions
89
+ col.fireValuesChanged();
90
+ await awaitCheck(() => df.col('curve 1 ic50')!.get(0) !== before,
91
+ 'statistic column did not recalculate after the column-level option changed', 5000);
92
+ });
93
+
94
+ test('clearing a cell-level override does not recalculate on its own', async () => {
95
+ // the rewrite that drops cell claims must not read as a data change; a recalculation bumps version
96
+ const cell = JSON.stringify({
97
+ chartOptions: {logX: true},
98
+ series: [{fitFunction: 'sigmoid', name: 'series', pointColor: '#ff0000', points: sigmoidPoints(-6.5)}],
99
+ });
100
+ const col = DG.Column.fromStrings('curve', [cell, cell]);
101
+ col.semType = FitConstants.FIT_SEM_TYPE;
102
+ const df = DG.DataFrame.fromColumns([col]);
103
+ df.name = 'panelNoRecalcOnCosmetic';
104
+ await addStatisticColumn(df, {propName: 'ic50', seriesNumber: 0});
105
+
106
+ const stat = df.col('curve 1 ic50')!;
107
+ const before = stat.version;
108
+ for (let j = 0; j < col.length; j++) {
109
+ const data = JSON.parse(col.get(j));
110
+ delete data.series[0].pointColor;
111
+ col.set(j, JSON.stringify(data), false);
112
+ }
113
+ await delay(500);
114
+ expect(stat.version, before, 'a cosmetic rewrite recalculated the statistic column');
115
+ });
116
+
117
+ test('a column-level option overrides a cell-level one, without recalculating', async () => {
118
+ // both halves in one test: notifying recalculates, not notifying used to leave the cache stale
119
+ const cell = JSON.stringify({
120
+ chartOptions: {logX: true},
121
+ series: [{fitFunction: 'sigmoid', name: 'series', pointColor: '#ff0000', points: sigmoidPoints(-6.5)}],
122
+ });
123
+ const col = DG.Column.fromStrings('curve', [cell, cell]);
124
+ col.semType = FitConstants.FIT_SEM_TYPE;
125
+ const df = DG.DataFrame.fromColumns([col]);
126
+ df.name = 'panelColumnOverridesCell';
127
+ await addStatisticColumn(df, {propName: 'ic50', seriesNumber: 0});
128
+
129
+ const stat = df.col('curve 1 ic50')!;
130
+ const version = stat.version;
131
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
132
+ const input = {property: {name: 'pointColor'}, value: '#00ff00'} as unknown as DG.InputBase;
133
+
134
+ changeCurvesOptions(gridCell, input, 'seriesOptions', 'Column');
135
+ await delay(500);
136
+
137
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).series![0].pointColor === '#ff0000', false,
138
+ 'the cell-level value still wins after the column-level change');
139
+ expect(stat.version, version, 'a cosmetic option change recalculated the statistic column');
140
+ });
141
+
142
+ test('clearing cell overrides marks the table changed without recalculating', async () => {
143
+ // silent so a cosmetic option does not refit, but the table still has to read as modified
144
+ const col = DG.Column.fromStrings('curve', [ciCurveJson(), ciCurveJson()]);
145
+ col.semType = FitConstants.FIT_SEM_TYPE;
146
+ const df = DG.DataFrame.fromColumns([col]);
147
+ df.name = 'panelMarksTableChanged';
148
+ await addStatisticColumn(df, {propName: 'ic50', seriesNumber: 0});
149
+
150
+ const stat = df.col('curve 1 ic50')!;
151
+ const version = stat.version;
152
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
153
+ let fired = 0;
154
+ const sub = df.onValuesChanged.subscribe(() => fired++);
155
+
156
+ changeCurvesOptions(gridCell,
157
+ {property: {name: 'showCurveConfidenceInterval'}, value: false} as unknown as DG.InputBase,
158
+ 'seriesOptions', 'Column');
159
+ await delay(500);
160
+ sub.unsubscribe();
161
+
162
+ // the value the data declares is left alone - it just stops winning
163
+ expect(JSON.parse(col.get(0)).series[0].showCurveConfidenceInterval, true, 'the cell data was mutated');
164
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).series![0].showCurveConfidenceInterval, false,
165
+ 'the column-level value did not outrank the value declared in the cell');
166
+ expect(fired > 0, true, 'nothing marked the table changed, so the option would not be saved');
167
+ expect(stat.version, version, 'a cosmetic option change recalculated the statistic column');
168
+ });
169
+
170
+ test('a column-level change overrides a value set at cell level first', async () => {
171
+ // detectSettings recorded "no cell claims this" once, so a later cell write was invisible to it
172
+ const df = curveTable('panelCellThenColumn', true);
173
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
174
+ const prop = (value: any) => ({property: {name: 'connectDots'}, value}) as unknown as DG.InputBase;
175
+
176
+ changeCurvesOptions(gridCell, prop(true), 'seriesOptions', 'Cell');
177
+ expect(JSON.parse(df.col('curve')!.get(0)).series[0].connectDots, true, 'cell-level write failed');
178
+ expect(JSON.parse(df.col('curve')!.get(0)).explicit.seriesOptions.includes('connectDots'), true,
179
+ 'a cell-level change did not claim the property');
180
+
181
+ changeCurvesOptions(gridCell, prop(false), 'seriesOptions', 'Column');
182
+ expect(JSON.parse(df.col('curve')!.get(0)).explicit.seriesOptions.includes('connectDots'), false,
183
+ 'the cell-level claim survived a column-level change');
184
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).series![0].connectDots, false,
185
+ 'the column-level value did not reach the cell');
186
+ });
187
+
188
+ test('a column-level option outranks a value the fresh data declares', async () => {
189
+ // a layout applied to fresh data: the column tag comes back, the cells still declare the property
190
+ const col = DG.Column.fromStrings('curve', [ciCurveJson(), ciCurveJson()]);
191
+ col.semType = FitConstants.FIT_SEM_TYPE;
192
+ const df = DG.DataFrame.fromColumns([col]);
193
+ df.name = 'panelFreshDataClaim';
194
+ // the column tag as a layout would restore it: the value plus the record that it was set here
195
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({
196
+ seriesOptions: {showCurveConfidenceInterval: false},
197
+ explicit: {seriesOptions: ['showCurveConfidenceInterval']},
198
+ }));
199
+
200
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).series![0].showCurveConfidenceInterval, false,
201
+ 'the restored column-level option lost to the value the cell declares');
202
+ // and without the record it stays advisory, so a series keeps whatever the data gave it
203
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({seriesOptions: {showCurveConfidenceInterval: false}}));
204
+ expect(getOrCreateParsedChartData(df.cell(1, 'curve')).series![0].showCurveConfidenceInterval, true,
205
+ 'an option nobody set explicitly overrode the data');
206
+ });
207
+
208
+ test('a column-level option survives a layout applied to a fresh table', async () => {
209
+ // the round trip this work exists for: the layout carries the column tag, the fresh table brings
210
+ // the source's own cells back, and the option has to win anyway
211
+ const cells = () => [ciCurveJson(), ciCurveJson()];
212
+ const table = (name: string) => {
213
+ const col = DG.Column.fromStrings('curve', cells());
214
+ col.semType = FitConstants.FIT_SEM_TYPE;
215
+ const df = DG.DataFrame.fromColumns([col]);
216
+ df.name = name;
217
+ return df;
218
+ };
219
+
220
+ const source = table('layoutSource');
221
+ const sourceView = grok.shell.addTableView(source);
222
+ const fresh = table('layoutTarget');
223
+ const freshView = grok.shell.addTableView(fresh);
224
+ try {
225
+ expect(getOrCreateParsedChartData(fresh.cell(0, 'curve')).series![0].showCurveConfidenceInterval, true,
226
+ 'the fresh table should start with the value its data declares');
227
+
228
+ changeCurvesOptions(sourceView.grid.cell('curve', 0),
229
+ {property: {name: 'showCurveConfidenceInterval'}, value: false} as unknown as DG.InputBase,
230
+ 'seriesOptions', 'Column');
231
+ changeCurvesOptions(sourceView.grid.cell('curve', 0),
232
+ {property: {name: 'statisticsMode'}, value: 'both'} as unknown as DG.InputBase,
233
+ 'chartOptions', 'Column');
234
+ const layout = sourceView.saveLayout();
235
+
236
+ freshView.loadLayout(layout);
237
+ await delay(500);
238
+
239
+ expect(getOrCreateParsedChartData(fresh.cell(0, 'curve')).series![0].showCurveConfidenceInterval, false,
240
+ 'the column-level option did not survive the layout');
241
+ expect(getOrCreateParsedChartData(fresh.cell(0, 'curve')).chartOptions?.statisticsMode, 'both',
242
+ 'a chart option did not survive the layout');
243
+ } finally {
244
+ sourceView.close();
245
+ freshView.close();
246
+ }
247
+ });
248
+
249
+ test('options stored under the legacy tag are read and migrate onto the layout-carried one', async () => {
250
+ // only '.%' tags reach a layout, so options in '.fit' never travelled to a fresh table
251
+ expect(FitConstants.TAG_FIT.startsWith('.%'), true, 'the fit tag is no longer carried by layouts');
252
+
253
+ const df = curveTable('panelLegacyTag', false);
254
+ const col = df.col('curve')!;
255
+ col.setTag(FitConstants.TAG_FIT_LEGACY, JSON.stringify({chartOptions: {logX: true}}));
256
+
257
+ expect(getColumnChartOptions(col).chartOptions!.logX, true, 'options under the legacy tag were ignored');
258
+ expect(JSON.parse(col.getTag(FitConstants.TAG_FIT)).chartOptions.logX, true,
259
+ 'reading did not migrate the options onto the layout-carried tag');
260
+ });
261
+
262
+ test('the panel offers the label names the cell carries', async () => {
263
+ const chartData = JSON.parse(labelledCurveJson()) as IFitChartData;
264
+ const choices = chartPropertiesFor(chartData).find((p) => p.name === 'showLabels')!.choices!;
265
+
266
+ // plot-level first, then whatever the curves add - a name is offered once however many carry it
267
+ expectArray(choices, ['Z prime', 'compound']);
268
+ });
269
+
270
+ test('a plot-level label is drawn once, a per-curve one per curve', async () => {
271
+ const drawn = renderedTexts(labelledCurveJson(), 'panelLabels');
272
+
273
+ // the plate statistic describes the cell, so it appears once however many curves there are
274
+ expect(drawn.filter((t) => t.startsWith('Z prime')).length, 1, 'the plot-level label was not drawn once');
275
+ expect(drawn.filter((t) => t.startsWith('compound')).length, 2, 'each curve should carry its own label');
276
+ expect(drawn.includes('compound: GRK-1'), true);
277
+ expect(drawn.includes('compound: GRK-2'), true);
278
+ });
279
+
280
+ test('only the labels named in showLabels are drawn', async () => {
281
+ const chartData = JSON.parse(labelledCurveJson()) as IFitChartData;
282
+ chartData.chartOptions!.showLabels = ['compound'];
283
+ const drawn = renderedTexts(JSON.stringify(chartData), 'panelLabelsFiltered');
284
+
285
+ expect(drawn.some((t) => t.startsWith('Z prime')), false, 'a label not named in showLabels was drawn');
286
+ expect(drawn.filter((t) => t.startsWith('compound')).length, 2);
287
+ });
288
+
289
+ test('an error bar starts at the marker edge and hides when the marker covers it', async () => {
290
+ // screen y grows downwards, so the top of the bar is the smaller number
291
+ const marker4 = stdevWhisker(100, 70, 130, 2)!;
292
+ expect(marker4 !== null, true, 'a deviation larger than the marker should be drawn');
293
+ expectArray(marker4.top, [70, 98]);
294
+ expectArray(marker4.bottom, [102, 130]);
295
+
296
+ // a point can set its own size, and a large marker used to swallow the bar whole
297
+ const bigMarker = stdevWhisker(100, 70, 130, 40);
298
+ expect(bigMarker === null, true, 'a deviation smaller than the marker must not be drawn inside it');
299
+
300
+ // the boundary: exactly at the marker edge is still nothing to show
301
+ expect(stdevWhisker(100, 80, 120, 20) === null, true);
302
+ expect(stdevWhisker(100, 79, 121, 20) !== null, true);
303
+ });
304
+
305
+ test('one list of statistics, and the mode decides where it is drawn', async () => {
306
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
307
+ data.chartOptions!.showStatistics = ['ic50'];
308
+ data.chartOptions!.statisticsMode = 'both';
309
+ data.chartOptions!.aggrType = 'med';
310
+ const both = renderedTexts(JSON.stringify(data), 'panelAggrBoth');
311
+
312
+ // named the way the extracted column is, so the plot and the column agree
313
+ const line = both.find((t) => t.startsWith('med ic50'));
314
+ expect(line !== undefined, true, 'the aggregated statistic was not drawn');
315
+ expect(both.filter((t) => t.startsWith('med ic50')).length, 1, 'it describes the cell, so it is drawn once');
316
+ expect(both.filter((t) => t.startsWith('IC50')).length, 2, 'each curve should still show its own');
317
+ // aggregated in fit space, so two decades apart give the middle one, not the arithmetic mean
318
+ expect(line!.includes('1.0') || line!.includes('1e-6') || line!.includes('9.9'), true, `unexpected value: ${line}`);
319
+
320
+ data.chartOptions!.statisticsMode = 'aggregated';
321
+ const aggregated = renderedTexts(JSON.stringify(data), 'panelAggrOnly');
322
+ expect(aggregated.filter((t) => t.startsWith('med ic50')).length, 1);
323
+ expect(aggregated.some((t) => t.startsWith('IC50')), false, 'the per-series values should give way to the summary');
324
+
325
+ data.chartOptions!.statisticsMode = 'series';
326
+ const series = renderedTexts(JSON.stringify(data), 'panelAggrSeries');
327
+ expect(series.some((t) => t.startsWith('med ')), false, 'nothing should be summarised in series mode');
328
+ expect(series.filter((t) => t.startsWith('IC50')).length, 2);
329
+ });
330
+
331
+ test('a single-series cell has nothing to aggregate', async () => {
332
+ const data = JSON.parse(multiSeriesCurveJson([-6.5])) as IFitChartData;
333
+ data.chartOptions!.showStatistics = ['ic50'];
334
+ data.chartOptions!.statisticsMode = 'aggregated';
335
+ const drawn = renderedTexts(JSON.stringify(data), 'panelAggrSingle');
336
+
337
+ expect(drawn.some((t) => t.startsWith('med ')), false,
338
+ 'with one curve the aggregate is that curve, so it should not be drawn');
339
+ // and the mode falls back to per series rather than drawing nothing at all
340
+ expect(drawn.some((t) => t.startsWith('IC50')), true, 'the single curve should still show its own');
341
+ });
342
+
343
+ test('the panel offers droplines only for a fit that has asymptotes', async () => {
344
+ const named = (json: string): string[] =>
345
+ seriesPropertiesFor(JSON.parse(json) as IFitChartData, null).map((p) => p.name);
346
+
347
+ expect(named(curveJson(-6.5)).includes('droplines'), true, 'a sigmoid levels off at both ends');
348
+
349
+ const linear = JSON.parse(curveJson(-6.5)) as IFitChartData;
350
+ linear.series![0].fitFunction = 'linear';
351
+ expect(named(JSON.stringify(linear)).includes('droplines'), false,
352
+ 'a line has no asymptotes, so an ICxx would never be drawn');
353
+ // the rest of the series options are untouched
354
+ expect(named(JSON.stringify(linear)).includes('markerType'), true);
355
+ // the render stamps this one on every paint, so editing it never took
356
+ expect(named(curveJson(-6.5)).includes('columnName'), false, 'the column a series came from is not a setting');
357
+ });
358
+
359
+ test('a custom fit function is offered once, everywhere, and never an empty one', async () => {
360
+ const custom = {name: 'TestCustomFit', function: '(params, x) => params[0] * x',
361
+ getInitialParameters: '(x, y) => new Float32Array([1])', parameterNames: ['Slope']};
362
+ const withCustom = JSON.parse(curveJson(-6.5)) as IFitChartData;
363
+ withCustom.series![0].fitFunction = custom as any;
364
+ try {
365
+ // rendering the cell is what registers it, and the panel is opened after that
366
+ getSeriesFitFunction(withCustom.series![0]);
367
+ const choices = seriesPropertiesFor(withCustom, custom as any).find((p) => p.name === 'fitFunction')!.choices!;
368
+ expect(choices.filter((c) => c === custom.name).length, 1, 'a registered function is named once');
369
+ expect(choices.includes(''), false, 'a series is fitted with something, so none is not a choice');
370
+
371
+ // registered once, it can be picked for any curve, not only the one that brought it
372
+ const plain = seriesPropertiesFor(JSON.parse(curveJson(-6.5)) as IFitChartData, null)
373
+ .find((p) => p.name === 'fitFunction')!.choices!;
374
+ expect(plain.includes(custom.name), true, 'and offered wherever a fit function is picked');
375
+ expect(plain.includes(''), false, 'here too');
376
+ } finally {
377
+ delete fitFunctions[custom.name];
378
+ }
379
+ });
380
+
381
+ test('picking a custom fit function stores the notation, not a name nothing can resolve', async () => {
382
+ const custom = {name: 'TestStoredFit', function: '(params, x) => params[0] * x',
383
+ getInitialParameters: '(x, y) => new Float32Array([1])', parameterNames: ['Slope']};
384
+ try {
385
+ // rendering the column that carries it is what registers it, and its notation with it
386
+ const carrier = JSON.parse(curveJson(-6.5)) as IFitChartData;
387
+ carrier.series![0].fitFunction = custom as any;
388
+ getSeriesFitFunction(carrier.series![0]);
389
+
390
+ // a curve that has never seen that function, the way another column would be
391
+ const cell = curveJson(-6.5);
392
+ const col = DG.Column.fromStrings('curve', [cell, cell]);
393
+ col.semType = FitConstants.FIT_SEM_TYPE;
394
+ const df = DG.DataFrame.fromColumns([col]);
395
+ df.name = 'customFitNotationStored';
396
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
397
+
398
+ changeCurvesOptions(gridCell, {property: {name: 'fitFunction'}, value: custom.name} as unknown as DG.InputBase,
399
+ 'seriesOptions', 'Cell');
400
+ await delay(300);
401
+ const stored = JSON.parse(df.col('curve')!.get(0)!).series[0].fitFunction;
402
+ expect(typeof stored, 'object', 'the name alone would not resolve in a session that never loaded it');
403
+ expect(stored.name, custom.name);
404
+ expect(!!stored.function && !!stored.getInitialParameters, true, 'the notation travels with the curve');
405
+
406
+ changeCurvesOptions(gridCell, {property: {name: 'fitFunction'}, value: 'linear'} as unknown as DG.InputBase,
407
+ 'seriesOptions', 'Cell');
408
+ await delay(300);
409
+ expect(JSON.parse(df.col('curve')!.get(0)!).series[0].fitFunction, 'linear',
410
+ 'a built-in one is always there, so it stays a name');
411
+ } finally {
412
+ delete fitFunctions[custom.name];
413
+ delete fitFunctionDescriptions[custom.name];
414
+ }
415
+ });
416
+
417
+ test('statistics are written in the plot font, not the one the caller left', async () => {
418
+ const data = JSON.parse(curveJson(-6.5)) as IFitChartData;
419
+ data.chartOptions!.showStatistics = ['auc', 'rSquared'];
420
+ const col = DG.Column.fromStrings('curve', [JSON.stringify(data)]);
421
+ col.semType = FitConstants.FIT_SEM_TYPE;
422
+ const df = DG.DataFrame.fromColumns([col]);
423
+ df.name = 'statisticsFont';
424
+
425
+ // the grid hands the renderer whatever font it last drew with, which is what used to change
426
+ // the statistics when the filter opened and change them back when the panel was scrolled
427
+ const fontsWhenCallerLeft = (callerFont: string): string[] => {
428
+ const fonts: string[] = [];
429
+ const g = ui.canvas(400, 300).getContext('2d')!;
430
+ const fillText = g.fillText.bind(g);
431
+ g.fillText = ((text: string, x: number, y: number) => {
432
+ if (text.includes(':')) fonts.push(g.font);
433
+ fillText(text, x, y);
434
+ }) as any;
435
+ g.font = callerFont;
436
+ new FitChartCellRenderer().renderCurves(g, new DG.Rect(0, 0, 400, 300),
437
+ getOrCreateParsedChartData(df.cell(0, 'curve')));
438
+ return [...new Set(fonts)];
439
+ };
440
+
441
+ const seeded = fontsWhenCallerLeft('20px Comic Sans MS');
442
+ expect(seeded.length, 1, 'every statistic should be written alike');
443
+ expect(seeded[0].includes('Comic Sans'), false, 'and not in whatever the caller was using');
444
+ expect(fontsWhenCallerLeft('11px Roboto, "Roboto Local"')[0], seeded[0],
445
+ 'the same font however the canvas reached the renderer');
446
+ });
447
+
448
+ test('several droplines are named, and one off the plot is not drawn', async () => {
449
+ // the curve levels off at 5 and 100, so IC50 sits at the inflection and IC90 a decade later
450
+ const data = JSON.parse(curveJson(-6.5)) as IFitChartData;
451
+ data.series![0].droplines = ['IC50', 'IC90'];
452
+ const both = renderedTexts(JSON.stringify(data), 'droplinesBoth');
453
+ expect(both.filter((t) => t === 'IC50').length, 1, 'each drawn dropline should be named');
454
+ expect(both.filter((t) => t === 'IC90').length, 1);
455
+
456
+ // a single line has nothing to be confused with, so it stays unlabelled as before
457
+ data.series![0].droplines = ['IC50'];
458
+ expect(renderedTexts(JSON.stringify(data), 'droplinesOne').includes('IC50'), false,
459
+ 'one dropline needs no caption');
460
+
461
+ // a grid cell has no room for captions, and crammed ones read worse than none
462
+ data.series![0].droplines = ['IC50', 'IC90'];
463
+ expect(renderedTexts(JSON.stringify(data), 'droplinesSmall', 200, 150).includes('IC50'), false,
464
+ 'captions should give way when the plot is small');
465
+
466
+ // IC99 of a curve centred at 1e-5 lands at 1e-3, past the highest concentration tested
467
+ const late = JSON.parse(curveJson(-5)) as IFitChartData;
468
+ late.series![0].droplines = ['IC50', 'IC99'];
469
+ const drawn = renderedTexts(JSON.stringify(late), 'droplinesOffPlot');
470
+ expect(drawn.includes('IC50'), true);
471
+ expect(drawn.includes('IC99'), false, 'a dropline off the plot should not be drawn at all');
472
+ });
473
+
474
+ test('property panel renders for a saved legacy statistic', async () => {
475
+ // no test covered this panel before, and it is the surface this ticket changed most
476
+ const df = curveTable('panelBinding', true, ['interceptX']);
477
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
478
+
479
+ // the panes build their contents lazily, so this asserts the panel is constructed without
480
+ // throwing - which nothing covered before, on the surface this ticket changed most
481
+ const root = new FitGridCellHandler().renderProperties(gridCell);
482
+ expect(root instanceof HTMLElement, true, 'the property panel failed to render');
483
+ });
484
+
485
+ test('statistic names stored under a legacy name map onto the current ones', async () => {
486
+ const chartData = JSON.parse(JSON.stringify({
487
+ chartOptions: {logX: true},
488
+ series: [{fitFunction: 'sigmoid', name: 's', points: sigmoidPoints(-6.5)}],
489
+ })) as IFitChartData;
490
+
491
+ // a saved project ticks its checkbox only if the stored name resolves to the current one
492
+ expectArray(normalizeStatisticNames(chartData, ['interceptX']), ['ic50']);
493
+ expectArray(normalizeStatisticNames(chartData, ['auc', 'rSquared']), ['auc', 'rSquared']);
494
+ // the same statistic under both names collapses to one entry
495
+ expectArray(normalizeStatisticNames(chartData, ['interceptX', 'ic50']), ['ic50']);
496
+
497
+ // and the choices the panel offers come from the cell's own fit function
498
+ const names = chartPropertiesFor(chartData).find((p) => p.name === 'showStatistics')!.choices!;
499
+ expect(names.includes('ic50'), true);
500
+ expect(names.includes('ec50'), false, 'a sigmoid cell must not offer the 4PL-regression name');
501
+ });
502
+ });
@@ -0,0 +1,99 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as grok from 'datagrok-api/grok';
3
+
4
+ import {awaitCheck, category, delay, expect, test} from '@datagrok-libraries/test/src/test';
5
+ import {changeCurvesOptions} from '../fit/fit-options';
6
+ import {getColumnChartOptions, getOrCreateParsedChartData} from '../fit/fit-chart-data';
7
+
8
+ const DEMO_FILE = 'curves-demo.csv';
9
+ // every cell of this column declares showCurveConfidenceInterval, so a column-level "off" only shows
10
+ // up if the option outranks the data rather than being written into it
11
+ const CURVE_COLUMN = 'multiple styled series';
12
+
13
+ async function createTableView(tableName: string): Promise<DG.TableView> {
14
+ const df = await grok.dapi.files.readCsv(`System:AppData/Curves/${tableName}`);
15
+ df.name = tableName.replace('.csv', '');
16
+ await grok.data.detectSemanticTypes(df);
17
+ return grok.shell.addTableView(df);
18
+ }
19
+
20
+ async function saveAndOpenProject(tv: DG.TableView, dataSync?: boolean): Promise<void> {
21
+ const project = DG.Project.create();
22
+ project.name = 'Curves test project';
23
+ const tableInfo = tv.dataFrame.getTableInfo();
24
+ if (dataSync) {
25
+ //@ts-ignore
26
+ tableInfo.tags[DG.Tags.DataSync] = 'sync';
27
+ //@ts-ignore
28
+ tableInfo.tags[DG.Tags.CreationScript] = tv.dataFrame.getTag(DG.Tags.CreationScript);
29
+ }
30
+ // saveLayout, not getInfo: only saveLayout runs saveSyncTags, which is what puts the column tags
31
+ // into the layout - without them a refetched table comes back with nothing but its own data
32
+ const layoutInfo = tv.saveLayout();
33
+ project.addChild(tableInfo);
34
+ project.addChild(layoutInfo);
35
+ await grok.dapi.tables.uploadDataFrame(tv.dataFrame);
36
+ await grok.dapi.tables.save(tableInfo);
37
+ await grok.dapi.views.save(layoutInfo);
38
+ await grok.dapi.projects.save(project);
39
+ const projId = project.id;
40
+ // the fit cell renderer keeps painting while the view tears down, and closeAll() surfaces that as
41
+ // an unhandled exception - let the grid settle first
42
+ await delay(500);
43
+ grok.shell.closeAll();
44
+ await delay(500);
45
+ const p = await grok.dapi.projects.find(projId);
46
+ await p.open();
47
+ }
48
+
49
+ async function dataFrameContainsColumn(colName: string): Promise<void> {
50
+ await awaitCheck(() => grok.shell.tv?.dataFrame?.col(colName) != null,
51
+ `${colName} is missing from the reopened project`, 30000);
52
+ }
53
+
54
+ function turnOffConfidenceIntervals(tv: DG.TableView): void {
55
+ if (tv.dataFrame.col(CURVE_COLUMN) === null)
56
+ throw new Error(`no ${CURVE_COLUMN} column - the table has: ${tv.dataFrame.columns.names().join(', ')}`);
57
+ changeCurvesOptions(tv.grid.cell(CURVE_COLUMN, 0),
58
+ {property: {name: 'showCurveConfidenceInterval'}, value: false} as unknown as DG.InputBase,
59
+ 'seriesOptions', 'Column');
60
+ }
61
+
62
+ async function runSaveAndOpenProjectTest(dataSync?: boolean): Promise<void> {
63
+ let tv: DG.TableView;
64
+ if (dataSync) {
65
+ await DG.Func.find({name: 'OpenFile'})[0].prepare({
66
+ fullPath: `System:AppData/Curves/${DEMO_FILE}`,
67
+ }).call(undefined, undefined, {processed: false});
68
+ tv = grok.shell.tv;
69
+ await grok.data.detectSemanticTypes(tv.dataFrame);
70
+ } else { tv = await createTableView(DEMO_FILE); }
71
+ await delay(100);
72
+ turnOffConfidenceIntervals(tv);
73
+ await delay(10);
74
+ await saveAndOpenProject(tv, dataSync);
75
+ await delay(10);
76
+ await dataFrameContainsColumn(CURVE_COLUMN);
77
+ // the tags are restored after the table, so wait for the option rather than for the column
78
+ await awaitCheck(() => getColumnChartOptions(grok.shell.tv.dataFrame.col(CURVE_COLUMN)!)
79
+ .seriesOptions?.showCurveConfidenceInterval === false,
80
+ 'the column tag did not come back with the project', 30000);
81
+
82
+ const df = grok.shell.tv.dataFrame;
83
+ expect(getOrCreateParsedChartData(df.cell(0, CURVE_COLUMN)).series![0].showCurveConfidenceInterval, false,
84
+ 'the column-level option did not outrank the data after reopening');
85
+ }
86
+
87
+ category('projects', () => {
88
+ test('column-level option survives a project', async () => {
89
+ await runSaveAndOpenProjectTest();
90
+ await delay(100);
91
+ }, {timeout: 120000});
92
+
93
+ test('column-level option survives a datasync project', async () => {
94
+ // the table is rebuilt from its creation script, so the cells come back declaring the interval
95
+ // and only the tag the layout carries can turn it off
96
+ await runSaveAndOpenProjectTest(true);
97
+ await delay(100);
98
+ }, {timeout: 120000});
99
+ });