@datagrok/curves 1.12.2 → 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 (39) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/CLAUDE.md +118 -15
  3. package/README.md +51 -4
  4. package/dist/package-test.js +11551 -8501
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3368 -2022
  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 +10 -5
  12. package/src/fit/fit-chart-data.ts +323 -0
  13. package/src/fit/fit-grid-cell-handler.ts +98 -231
  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 +46 -20
  23. package/src/fit/render-utils.ts +208 -150
  24. package/src/package-api.ts +78 -0
  25. package/src/package-test.ts +6 -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 +310 -3
  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/transform-tests.ts +3 -2
  38. package/test-console-output-1.log +347 -103
  39. package/test-record-1.mp4 +0 -0
@@ -4,233 +4,85 @@ import * as ui from 'datagrok-api/ui';
4
4
  import * as grok from 'datagrok-api/grok';
5
5
 
6
6
  import {
7
- getSeriesStatistics,
8
7
  getSeriesFitFunction,
9
- LogOptions,
10
8
  getChartBounds,
11
9
  } from '@datagrok-libraries/statistics/src/fit/fit-data';
10
+ import {LogOptions} from '@datagrok-libraries/statistics/src/fit/fit-curve';
11
+ import {FitChartCellRenderer} from './fit-renderer';
12
12
  import {
13
- statisticsProperties,
14
- fitChartDataProperties,
15
- IFitChartData,
16
- IFitSeries,
17
- IFitChartOptions,
18
- IFitSeriesOptions,
19
- FitStatistics,
20
- FIT_FUNCTION_4PL_REGRESSION, FIT_FUNCTION_SIGMOID,
21
- } from '@datagrok-libraries/statistics/src/fit/fit-curve';
22
- import {
23
- getOrCreateParsedChartData,
24
- getColumnChartOptions,
25
- getDataFrameChartOptions,
26
- isColorValid,
27
- mergeProperties,
28
- substituteZeroes, getOrCreateCachedFitCurve, getOrCreateCachedCurvesDataPoints, FitChartCellRenderer
29
- } from './fit-renderer';
13
+ getOrCreateParsedChartData, getColumnChartOptions, getDataFrameChartOptions, mergeProperties,
14
+ substituteZeroes, CHART_OPTIONS, SERIES_OPTIONS,
15
+ } from './fit-chart-data';
30
16
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
31
- import {parseCellValue, isNativeFormat} from './curve-converter';
32
- import {ColorType, getSeriesColor} from './render-utils';
33
- import {fitSeriesProperties} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
34
-
35
-
36
- const CHART_OPTIONS = 'chartOptions';
37
- const SERIES_OPTIONS = 'seriesOptions';
38
- enum MANIPULATION_LEVEL {
39
- DATAFRAME = 'Dataframe',
40
- COLUMN = 'Column',
41
- CELL = 'Cell'
42
- }
43
- const AGGREGATION_TYPES: {[key: string]: string} = {
44
- 'count': 'totalCount',
45
- 'nulls': 'missingValueCount',
46
- 'unique': 'uniqueCount',
47
- 'values': 'valueCount',
48
- 'min': 'min',
49
- 'max': 'max',
50
- 'sum': 'sum',
51
- 'avg': 'avg',
52
- 'stdev': 'stdev',
53
- 'variance': 'variance',
54
- 'skew': 'skew',
55
- 'kurt': 'kurt',
56
- 'med': 'med',
57
- 'q1': 'q1',
58
- 'q2': 'q2',
59
- 'q3': 'q3'
60
- };
61
-
62
-
63
- export function calculateSeriesStats(series: IFitSeries, seriesIdx: number, chartLogOptions: LogOptions,
64
- tableCell: DG.Cell, useCache: boolean = true): FitStatistics {
65
- const fitFunction = getSeriesFitFunction(series);
66
- if (series.parameters) {
67
- if (chartLogOptions.logX) {
68
- if (series.parameters[2] > 0)
69
- series.parameters[2] = Math.log10(series.parameters[2]);
70
- }
71
- } else {
72
- const params = getOrCreateCachedFitCurve(series, seriesIdx, fitFunction, chartLogOptions, tableCell, useCache).parameters;
73
- series.parameters = [...params];
17
+ import {ColorType, SeriesColorType, getSeriesColor, isColorValid} from './render-utils';
18
+ import {calculateSeriesFit, getChartDataAggrStats, aggregatedStatisticsProperties} from './fit-statistics';
19
+ import {fitChartDataProperties} from '@datagrok-libraries/statistics/src/fit/fit-curve';
20
+ import {fitSeriesProperties} from '@datagrok-libraries/statistics/src/fit/fit-engine';
21
+ import {
22
+ changeCurvesOptions, chartPropertiesFor, normalizeStatisticNames, seriesPropertiesFor, ManipulationLevel,
23
+ } from './fit-options';
24
+
25
+ type CurveStatisticParams = {propName: string, seriesNumber: number} | {propName: string, aggrType: string};
26
+
27
+ /** Runs a curve statistic so its `join(table)` output makes the platform add it as a calculated column. */
28
+ export async function addStatisticColumn(gridCell: DG.GridCell, funcName: string,
29
+ params: CurveStatisticParams): Promise<void> {
30
+ const func = DG.Func.find({package: 'Curves', name: funcName})[0];
31
+ if (!func) {
32
+ grok.shell.error(`Curves: ${funcName} is not registered`);
33
+ return;
74
34
  }
75
-
76
- const seriesStatistics = getSeriesStatistics(series, fitFunction,
77
- getOrCreateCachedCurvesDataPoints(series, seriesIdx, chartLogOptions, false, tableCell), chartLogOptions);
78
- if ([FIT_FUNCTION_4PL_REGRESSION, FIT_FUNCTION_SIGMOID].includes(fitFunction.name) && chartLogOptions.logX && seriesStatistics.interceptX !== undefined && seriesStatistics.interceptX < 0)
79
- seriesStatistics.interceptX = Math.pow(10, seriesStatistics.interceptX);
80
- return seriesStatistics;
81
- }
82
-
83
- export function getChartDataAggrStats(chartData: IFitChartData, aggrType: string, tableCell: DG.Cell): FitStatistics {
84
- const chartLogOptions: LogOptions = {logX: chartData.chartOptions?.logX, logY: chartData.chartOptions?.logY};
85
- const rSquaredValues: number[] = []; const aucValues: number[] = []; const interceptXValues: number[] = []; const interceptYValues: number[] = [];
86
- const slopeValues: number[] = []; const topValues: number[] = []; const bottomValues: number[] = [];
87
- for (let i = 0, j = 0; i < chartData.series?.length!; i++) {
88
- if (chartData.series![i].points.every((p) => p.outlier))
89
- continue;
90
- const seriesStats = calculateSeriesStats(chartData.series![i], i, chartLogOptions, tableCell);
91
- rSquaredValues[j] = seriesStats.rSquared!;
92
- aucValues[j] = seriesStats.auc!;
93
- interceptXValues[j] = seriesStats.interceptX!;
94
- interceptYValues[j] = seriesStats.interceptY!;
95
- slopeValues[j] = seriesStats.slope!;
96
- topValues[j] = seriesStats.top!;
97
- bottomValues[j] = seriesStats.bottom!;
98
- j++;
35
+ const df = gridCell.cell.dataFrame;
36
+ const curveColumnName = gridCell.cell.column.name;
37
+ const before = new Set(df.columns.names());
38
+ try {
39
+ await func.prepare({table: df, curveColumn: gridCell.cell.column, ...params})
40
+ .call(false, undefined, {processed: false});
41
+ } catch (e) {
42
+ // the caller is an icon click handler, so an unhandled rejection just looks like a dead button
43
+ grok.shell.error(`Could not add the statistic column: ${e}`);
44
+ return;
99
45
  }
100
-
101
- return {
102
- rSquared: rSquaredValues.some((elem) => elem === undefined || elem === null) ? undefined:
103
- DG.Stats.fromValues(rSquaredValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
104
- auc: aucValues.some((elem) => elem === undefined || elem === null) ? undefined :
105
- DG.Stats.fromValues(aucValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
106
- interceptX: interceptXValues.some((elem) => elem === undefined || elem === null) ? undefined :
107
- DG.Stats.fromValues(interceptXValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
108
- interceptY: interceptYValues.some((elem) => elem === undefined || elem === null) ? undefined :
109
- DG.Stats.fromValues(interceptYValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
110
- slope: slopeValues.some((elem) => elem === undefined || elem === null) ? undefined :
111
- DG.Stats.fromValues(slopeValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
112
- top: topValues.some((elem) => elem === undefined || elem === null) ? undefined :
113
- DG.Stats.fromValues(topValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number,
114
- bottom: bottomValues.some((elem) => elem === undefined || elem === null) ? undefined :
115
- DG.Stats.fromValues(bottomValues)[AGGREGATION_TYPES[aggrType] as keyof DG.Stats] as number
116
- };
46
+ placeAfterCurveColumn(gridCell, df.columns.names().filter((name) => !before.has(name)), curveColumnName);
117
47
  }
118
48
 
119
- function changePlotOptions(chartData: IFitChartData, inputBase: DG.InputBase, options: string): void {
120
- const propertyName = inputBase.property.name as string;
121
- if (options === CHART_OPTIONS) {
122
- if (chartData.chartOptions === undefined) return;
123
- (chartData.chartOptions[propertyName as keyof IFitChartOptions] as any) = inputBase.value;
124
- } else if (options === SERIES_OPTIONS) {
125
- if (chartData.series === undefined) return;
126
- for (let i = 0; i < chartData.series.length; i++)
127
- (chartData.series[i][propertyName as keyof IFitSeries] as any) = inputBase.value;
49
+ /** `join(table)` appends, so the position is restored afterwards - in the grid too, which takes a
50
+ * column's position from the dataframe only when it first builds a GridColumn for it. */
51
+ function placeAfterCurveColumn(gridCell: DG.GridCell, added: string[], curveColumnName: string): void {
52
+ if (added.length === 0)
53
+ return;
54
+ const df = gridCell.cell.dataFrame;
55
+ df.columns.setOrder(insertedAfter(df.columns.names(), added, curveColumnName));
56
+
57
+ const grid = gridCell.grid;
58
+ if (!grid)
59
+ return;
60
+ const gridNames: string[] = [];
61
+ for (let i = 0; i < grid.columns.length; i++) {
62
+ const name = grid.columns.byIndex(i)?.name;
63
+ if (name)
64
+ gridNames.push(name);
128
65
  }
66
+ grid.columns.setOrder(insertedAfter(gridNames, added, curveColumnName));
129
67
  }
130
68
 
131
- function detectSettings(df: DG.DataFrame): void {
132
- const fitColumns = df.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
133
- for (let i = 0; i < fitColumns.length; i++) {
134
- fitChartDataProperties.map((prop) => {
135
- fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = false;
136
- });
137
- fitSeriesProperties.map((prop) => {
138
- fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = false;
139
- });
140
-
141
- for (let j = 0; j < fitColumns[i].length; j++) {
142
- if (fitColumns[i].get(j) === '') continue;
143
- const chartData = parseCellValue(fitColumns[i].get(j), fitColumns[i]);
144
-
145
- fitChartDataProperties.map((prop) => {
146
- if (!chartData.chartOptions) return;
147
- if (chartData.chartOptions[prop.name as keyof IFitChartOptions] !== undefined)
148
- fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = true;
149
- });
150
-
151
- fitSeriesProperties.map((prop) => {
152
- if (!chartData.series) return;
153
- for (const series of chartData.series) {
154
- if (series[prop.name as keyof IFitSeriesOptions] !== undefined)
155
- fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = true;
156
- }
157
- });
158
- }
159
- }
69
+ function insertedAfter(names: string[], added: string[], anchor: string): string[] {
70
+ const rest = names.filter((name) => !added.includes(name));
71
+ const at = rest.indexOf(anchor) + 1;
72
+ return [...rest.slice(0, at), ...added, ...rest.slice(at)];
160
73
  }
161
74
 
162
- function changeCurvesOptions(gridCell: DG.GridCell, inputBase: DG.InputBase, options: string, manipulationLevel: string): void {
163
- if (gridCell.cell.column.temp[`${CHART_OPTIONS}-custom-title`] === undefined)
164
- detectSettings(gridCell.cell.dataFrame);
165
- const propertyName = inputBase.property.name as string;
166
- const chartOptions = manipulationLevel === MANIPULATION_LEVEL.DATAFRAME ?
167
- getDataFrameChartOptions(gridCell.cell.dataFrame) : getColumnChartOptions(gridCell.cell.column);
168
- if (options === CHART_OPTIONS)
169
- (chartOptions.chartOptions![propertyName as keyof IFitChartOptions] as any) = inputBase.value;
170
- else if (options === SERIES_OPTIONS)
171
- (chartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions] as any) = inputBase.value;
172
-
173
- if (manipulationLevel === MANIPULATION_LEVEL.CELL) {
174
- // Cell-level editing only works for native JSON format
175
- if (!isNativeFormat(gridCell.cell.column))
176
- return;
177
- const value = gridCell.cell.value;
178
- if (value === '') return;
179
- const chartData: IFitChartData = JSON.parse(value ?? '{}') ?? {};
180
- changePlotOptions(chartData, inputBase, options);
181
- gridCell.cell.value = JSON.stringify(chartData);
182
- } else {
183
- let columns: DG.Column[];
184
- if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
185
- gridCell.cell.dataFrame.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
186
- columns = gridCell.cell.dataFrame.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
187
- } else {
188
- gridCell.cell.column.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
189
- columns = [gridCell.cell.column];
190
- }
191
-
192
- for (let i = 0; i < columns.length; i++) {
193
- if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
194
- const columnChartOptions = getColumnChartOptions(columns[i]);
195
- options === CHART_OPTIONS ? delete columnChartOptions.chartOptions![propertyName as keyof IFitChartOptions] :
196
- delete columnChartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions];
197
- columns[i].tags[FitConstants.TAG_FIT] = JSON.stringify(columnChartOptions);
198
- }
199
- if (columns[i].temp[`${options}-custom-${propertyName}`] === false) continue;
200
- // Skip cell-level value mutation for non-native format columns
201
- if (!isNativeFormat(columns[i])) continue;
202
-
203
- columns[i].init((j) => {
204
- const value = columns[i].get(j);
205
- if (value === '') return value;
206
- const chartData = (JSON.parse(columns[i].get(j) ?? '{}') ?? {}) as IFitChartData;
207
- if (options === CHART_OPTIONS) {
208
- if (chartData.chartOptions === undefined) return value;
209
- if (chartData.chartOptions[propertyName as keyof IFitChartOptions] === undefined)
210
- return value;
211
- delete chartData.chartOptions[propertyName as keyof IFitChartOptions];
212
- } else {
213
- if (chartData.series === undefined) return value;
214
- let isSeriesChanged = false;
215
- for (const series of chartData.series) {
216
- if (series[propertyName as keyof IFitSeriesOptions] !== undefined) {
217
- delete series[propertyName as keyof IFitSeriesOptions];
218
- isSeriesChanged = true;
219
- }
220
- }
221
- if (chartData.seriesOptions)
222
- delete chartData.seriesOptions[propertyName as keyof IFitSeriesOptions];
223
- if (!isSeriesChanged) return value;
224
- }
225
- return JSON.stringify(chartData);
226
- });
227
- columns[i].temp[`${options}-custom-${propertyName}`] = false;
228
- }
75
+ /** A multi-choice is capped at 155px and always draws its scrollbar, which cut the statistics off and
76
+ * left a second scrollbar inside a panel that already scrolls. These lists are short enough to read. */
77
+ function showWholeList(input: DG.InputBase): DG.InputBase {
78
+ const checks = input.root.querySelector('.ui-input-multi-choice-checks') as HTMLElement | null;
79
+ if (checks) {
80
+ checks.style.maxHeight = 'none';
81
+ checks.style.overflowY = 'visible';
229
82
  }
230
- gridCell.grid.invalidate();
83
+ return input;
231
84
  }
232
85
 
233
-
234
86
  export class FitGridCellHandler extends DG.ObjectHandler {
235
87
  get type(): string {
236
88
  return 'GridCell';
@@ -260,11 +112,11 @@ export class FitGridCellHandler extends DG.ObjectHandler {
260
112
  const dfChartOptions = getDataFrameChartOptions(gridCell.cell.dataFrame);
261
113
 
262
114
  const seriesOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
263
- changeCurvesOptions(gridCell, inputBase, SERIES_OPTIONS, switchLevelInput.value)};
115
+ changeCurvesOptions(gridCell, inputBase, SERIES_OPTIONS, switchLevelInput.value as ManipulationLevel)};
264
116
  const chartOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
265
- changeCurvesOptions(gridCell, inputBase, CHART_OPTIONS, switchLevelInput.value)};
117
+ changeCurvesOptions(gridCell, inputBase, CHART_OPTIONS, switchLevelInput.value as ManipulationLevel)};
266
118
 
267
- const setValidColors = (colorFieldName: string) => {
119
+ const setValidColors = (colorFieldName: SeriesColorType) => {
268
120
  if (dfChartOptions.seriesOptions && !isColorValid(dfChartOptions.seriesOptions[colorFieldName]) &&
269
121
  columnChartOptions.seriesOptions && !isColorValid(columnChartOptions.seriesOptions[colorFieldName])) {
270
122
  if (chartData.seriesOptions) {
@@ -299,9 +151,27 @@ chartData.series![0][colorFieldName] = DG.Color.toHtml(colorFieldName === 'outli
299
151
  substituteZeroes(chartData);
300
152
 
301
153
  const form = ui.form([switchLevelInput]);
302
- const fitSeriesChildren = fitSeriesProperties.map((p) => ui.input.forProperty(p, chartData.seriesOptions ? chartData.seriesOptions : chartData.series![0], seriesOptionsRefresh));
154
+ const seriesSource = chartData.seriesOptions ? chartData.seriesOptions : chartData.series![0];
155
+ // a custom JS fit function is stored as a description object, which a choice input cannot display
156
+ const customFitFunction = seriesSource && typeof seriesSource.fitFunction === 'object' ?
157
+ seriesSource.fitFunction : null;
158
+ const fitSeriesChildren = seriesPropertiesFor(chartData, customFitFunction).map((p) => {
159
+ if (p.name !== 'fitFunction' || !customFitFunction)
160
+ return showWholeList(ui.input.forProperty(p, seriesSource, seriesOptionsRefresh));
161
+ // the input is bound to the name, so a pick has to be written back to the series
162
+ const named = {...seriesSource, fitFunction: customFitFunction.name};
163
+ return ui.input.forProperty(p, named, {onValueChanged: (v: any, inputBase: DG.InputBase) => {
164
+ if (v !== customFitFunction.name)
165
+ seriesSource.fitFunction = v;
166
+ seriesOptionsRefresh.onValueChanged(v, inputBase);
167
+ }});
168
+ });
303
169
  ui.forms.addGroup(form, 'Series options', fitSeriesChildren);
304
- ui.forms.addGroup(form, 'Chart options', fitChartDataProperties.map((p) => ui.input.forProperty(p, chartData.chartOptions, chartOptionsRefresh)));
170
+ // normalize the stored legacy names in place, so the input binds to the real options object
171
+ if (chartData.chartOptions?.showStatistics)
172
+ chartData.chartOptions.showStatistics = normalizeStatisticNames(chartData, chartData.chartOptions.showStatistics);
173
+ ui.forms.addGroup(form, 'Chart options', chartPropertiesFor(chartData).map((p) =>
174
+ showWholeList(ui.input.forProperty(p, chartData.chartOptions, chartOptionsRefresh))));
305
175
  acc.addPane('Options', () => form);
306
176
 
307
177
  const choices = (chartData.series?.length ?? 0) > 1 ? ['all', 'aggregated'] : ['all'];
@@ -330,22 +200,18 @@ chartData.series![0][colorFieldName] = DG.Color.toHtml(colorFieldName === 'outli
330
200
  const chartLogOptions: LogOptions = {logX: chartData.chartOptions?.logX, logY: chartData.chartOptions?.logY};
331
201
  for (let i = 0; i < chartData.series!.length; i++) {
332
202
  const series = chartData.series![i];
333
- const seriesStatistics = calculateSeriesStats(series, i, chartLogOptions, tableCell);
203
+ const seriesFit = calculateSeriesFit(series, i, chartLogOptions, tableCell);
334
204
 
335
205
  const color = getSeriesColor(series, i, ColorType.FIT_LINE);
336
206
  const seriesName = series.name ?? 'series ' + i;
337
207
  host.appendChild(ui.panel([
338
208
  ui.h1(seriesName, {style: {color: color}}),
339
- ui.input.form(seriesStatistics, statisticsProperties, {
340
- onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
341
- const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, seriesNumber: i};
342
- await DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
343
- }, `Calculate ${input.property.name} for the whole column`))
344
-
345
- // TODO: Replace with this one after dima merges his branch
346
- // const newName = gridCell.cell.dataFrame.columns.getUnusedName(`${gridCell.gridColumn.name} ${seriesName} ${input.property.name}`);
347
- // await gridCell.cell.dataFrame.columns.addNewCalculated(newName, `Curves:addStatisticsColumn("table", \$\{${gridCell.gridColumn.name}\}, "${input.property.name}", ${i})`, undefined, undefined, false);
348
- // }, `Calculate ${input.property.name} for the whole column`))
209
+ // descriptors come from the series' own fit function, so only applicable statistics are listed
210
+ ui.input.form(seriesFit, getSeriesFitFunction(series).statisticsProperties, {
211
+ onCreated: (input) => input.root.appendChild(ui.iconFA('plus', () =>
212
+ addStatisticColumn(gridCell, 'curveStatistic',
213
+ {propName: input.property.name, seriesNumber: i}),
214
+ `Calculate ${input.property.name} for the whole column`))
349
215
  })
350
216
  ]));
351
217
  }
@@ -353,11 +219,12 @@ chartData.series![0][colorFieldName] = DG.Color.toHtml(colorFieldName === 'outli
353
219
  const seriesStatistics = getChartDataAggrStats(chartData, aggrTypeInput.stringValue, tableCell);
354
220
  host.appendChild(ui.panel([
355
221
  ui.h1(`series ${aggrTypeInput.stringValue}`),
356
- ui.input.form(seriesStatistics, statisticsProperties, {
357
- onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
358
- const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, aggrType: aggrTypeInput.stringValue};
359
- await DG.Func.find({name: 'addAggrStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
360
- }, `Calculate ${input.property.name} ${aggrTypeInput.stringValue} for the whole column`))
222
+ // same per-fit-function descriptors as the single-series pane, deduplicated across series
223
+ ui.input.form(seriesStatistics, aggregatedStatisticsProperties(chartData, aggrTypeInput.stringValue), {
224
+ onCreated: (input) => input.root.appendChild(ui.iconFA('plus', () =>
225
+ addStatisticColumn(gridCell, 'curveAggrStatistic',
226
+ {propName: input.property.name, aggrType: aggrTypeInput.stringValue}),
227
+ `Calculate ${input.property.name} ${aggrTypeInput.stringValue} for the whole column`))
361
228
  })
362
229
  ]));
363
230
  }
@@ -1,7 +1,7 @@
1
1
  /* eslint-disable max-len */
2
2
  import * as DG from 'datagrok-api/dg';
3
- import {FitSeries, FitFunctionType} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
4
- import {inspectCurve} from './fit-renderer';
3
+ import {FitSeries, FitFunctionType} from '@datagrok-libraries/statistics/src/fit/fit-engine';
4
+ import {inspectCurve} from './fit-interaction';
5
5
  import * as grok from 'datagrok-api/grok';
6
6
 
7
7
  export function randomizeTableId() {
@@ -24,7 +24,7 @@ export function inspectSeries(series: FitSeries, fitFunctionName: FitFunctionTyp
24
24
  logX: true,
25
25
  title: seriesName,
26
26
  },
27
- series: [{...series, fit: undefined, fitFunction: fitFunctionName, clickToToggle: true, droplines: ['IC50'], name: seriesName}],
27
+ series: [{...series, fitFunction: fitFunctionName, clickToToggle: true, droplines: ['IC50'], name: seriesName}],
28
28
  }), false);
29
29
  const df = DG.DataFrame.fromColumns([curveCol]);
30
30
  df.name = seriesName;
@@ -0,0 +1,181 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+ import * as grok from 'datagrok-api/grok';
4
+ import * as ui from 'datagrok-api/ui';
5
+ import {merge} from 'rxjs';
6
+
7
+ import {IFitChartData, IFitPoint, LogOptions} from '@datagrok-libraries/statistics/src/fit/fit-curve';
8
+ import {getChartBounds} from '@datagrok-libraries/statistics/src/fit/fit-data';
9
+ import {getStatistic} from '@datagrok-libraries/statistics/src/fit/fit-engine';
10
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
11
+ import {Viewport} from '@datagrok-libraries/utils/src/transform';
12
+
13
+ import {isNativeFormat} from './curve-converter';
14
+ import {getOrCreateParsedChartData} from './fit-chart-data';
15
+ import {calculateSeriesFit, getChartDataAggrStats} from './fit-statistics';
16
+ import {inflateScreenBounds, isTitleShown, layoutChart, shownAxesNames} from './fit-layout';
17
+ import {isLegendVisible, legendTooltip, legendTooltipElement} from './fit-legend';
18
+
19
+ /** What a user does to a curve in the grid: toggling an outlier, hovering a point, opening the editor. */
20
+
21
+ export function setOutlier(gridCell: DG.GridCell, p: IFitPoint, seriesIdx: number, pointIdx: number, _data?: IFitChartData) {
22
+ p.outlier = !p.outlier;
23
+ // outlier toggling works only for native JSON format (no converter)
24
+ if (isNativeFormat(gridCell.cell.column)) {
25
+ const gridCellValue = JSON.parse(gridCell.cell.value) as IFitChartData;
26
+ gridCellValue.series![seriesIdx].points[pointIdx].outlier = p.outlier;
27
+ gridCell.cell.column.set(gridCell.cell.rowIndex, JSON.stringify(gridCellValue), true);
28
+ grok.events.fireCustomEvent('fit-cell-outlier-toggle', {
29
+ gridCell: gridCell,
30
+ series: gridCellValue.series![seriesIdx],
31
+ seriesIdx: seriesIdx,
32
+ pointIdx: pointIdx,
33
+ });
34
+ }
35
+ const columns = gridCell.grid.dataFrame.columns.byTags({'.sourceColumn': gridCell.cell.column.name});
36
+ if (columns) {
37
+ _data ??= getOrCreateParsedChartData(gridCell.cell);
38
+ for (const column of columns) {
39
+ const chartLogOptions: LogOptions = {logX: _data.chartOptions?.logX, logY: _data.chartOptions?.logY};
40
+ const statName = column.tags['.statistics'];
41
+ // resolved by name - the legacy seven-key shape has no ic50/pIC50/maxY slot
42
+ let value: number | undefined;
43
+ if (column.tags['.seriesAggregation'] !== null)
44
+ value = getChartDataAggrStats(_data, column.tags['.seriesAggregation'], gridCell.cell)[statName];
45
+ else if (column.tags['.seriesNumber'] === seriesIdx.toString())
46
+ value = getStatistic(calculateSeriesFit(_data.series![seriesIdx], seriesIdx, chartLogOptions, gridCell.cell), statName);
47
+ else
48
+ continue;
49
+ column.set(gridCell.cell.rowIndex, value ?? null);
50
+ }
51
+ }
52
+ }
53
+
54
+ export function inspectCurve(gridCell: DG.GridCell, size?: Partial<DG.Size>, rerenderOnChange: boolean = false): void {
55
+ if (!gridCell.cell.value)
56
+ return;
57
+
58
+ const gridCellWidget = DG.GridCellWidget.fromGridCell(gridCell);
59
+ gridCellWidget.root.style.removeProperty('aspectRatio');
60
+ gridCellWidget.root.style.height = '100%';
61
+ gridCellWidget.canvas.style.removeProperty('height');
62
+ gridCellWidget.canvas.style.removeProperty('width');
63
+ gridCellWidget.canvas.style.left = '18px';
64
+ gridCellWidget.canvas.style.top = '18px';
65
+
66
+ const dlg = ui.dialog({title: 'Edit chart'})
67
+ .add(gridCellWidget.root)
68
+ .show({resizable: true, width: size?.width ?? 500, height: size?.height ?? 430});
69
+ dlg.getButton('CANCEL').textContent = 'Close';
70
+ if (rerenderOnChange)
71
+ dlg.sub(merge(gridCell.grid.dataFrame.onDataChanged, gridCell.grid.dataFrame.onMetadataChanged).subscribe(() => gridCellWidget.render()));
72
+ }
73
+
74
+ export function hitTest(at: {x: number, y: number}, point: IFitPoint, viewport: Viewport): boolean {
75
+ const screenX = viewport.xToScreen(point.x);
76
+ const screenY = viewport.yToScreen(point.y);
77
+ const pxPerMarkerType = ((point.outlier ? FitConstants.OUTLIER_PX_SIZE : FitConstants.POINT_PX_SIZE) / 2) + FitConstants.OUTLIER_HITBOX_RADIUS;
78
+ const pointRect = new DG.Rect(screenX - pxPerMarkerType, screenY - pxPerMarkerType,
79
+ 2 * pxPerMarkerType, 2 * pxPerMarkerType);
80
+ return pointRect.containsPoint(new DG.Point(at.x, at.y));
81
+ }
82
+
83
+ function pointViewport(screenBounds: DG.Rect, data: IFitChartData): Viewport {
84
+ const axesNames = shownAxesNames(screenBounds, data);
85
+ const dataBox = layoutChart(screenBounds, axesNames.x, axesNames.y, isTitleShown(screenBounds, data))[0];
86
+ return new Viewport(getChartBounds(data), dataBox, data.chartOptions?.logX ?? false, data.chartOptions?.logY ?? false);
87
+ }
88
+
89
+ export function handleClick(gridCell: DG.GridCell, e: MouseEvent): void {
90
+ if (!gridCell.cell.value || !gridCell.cell.column)
91
+ return;
92
+
93
+ const data = getOrCreateParsedChartData(gridCell.cell, false);
94
+
95
+ for (const [message, condition] of Object.entries(FitConstants.CONDITION_MAP)) {
96
+ if (condition(data.series)) {
97
+ grok.shell.o = ui.divText(message, {style: {color: 'red'}});
98
+ return;
99
+ }
100
+ }
101
+
102
+ grok.shell.o = gridCell;
103
+
104
+ const screenBounds = inflateScreenBounds(gridCell.bounds);
105
+ const viewport = pointViewport(screenBounds, data);
106
+
107
+ for (let i = 0; i < data.series?.length!; i++) {
108
+ if (data.series![i].connectDots || !data.series![i].clickToToggle || data.series![i].showPoints !== 'points' ||
109
+ screenBounds.width < FitConstants.MIN_AXES_CELL_PX_WIDTH || screenBounds.height < FitConstants.MIN_AXES_CELL_PX_HEIGHT)
110
+ continue;
111
+ for (let j = 0; j < data.series![i].points.length!; j++) {
112
+ const p = data.series![i].points[j];
113
+ if (p.outlier && !data.series![i].showOutliers)
114
+ continue;
115
+ if (hitTest({x: e.offsetX, y: e.offsetY}, p, viewport)) {
116
+ setOutlier(gridCell, p, i, j, data);
117
+ return;
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ /** `renderer` is the base type on purpose - taking the concrete one back would make this module and
124
+ * the renderer import each other. */
125
+ /** The tooltips a chart answers with, wherever it is drawn: a legend row it had to shorten, the rest
126
+ * of a legend that did not fit, or the point under the pointer. */
127
+ export function chartTooltip(data: IFitChartData, screenBounds: DG.Rect, e: MouseEvent,
128
+ offset: {x: number, y: number}): boolean {
129
+ const viewport = pointViewport(screenBounds, data);
130
+
131
+ const legendRows = isLegendVisible(data, screenBounds) ?
132
+ legendTooltip(data, viewport.screen, offset.x, offset.y) : null;
133
+ if (legendRows !== null) {
134
+ ui.tooltip.show(legendTooltipElement(legendRows), e.x + 16, e.y + 16);
135
+ return true;
136
+ }
137
+
138
+ for (let i = 0; i < data.series?.length!; i++) {
139
+ if (data.series![i].showPoints !== 'points')
140
+ continue;
141
+ for (let j = 0; j < data.series![i].points.length!; j++) {
142
+ const p = data.series![i].points[j];
143
+ if (p.outlier && !data.series![i].showOutliers)
144
+ continue;
145
+ if (hitTest(offset, p, viewport)) {
146
+ ui.tooltip.show(ui.divV([ui.divText(`${data.chartOptions?.xAxisName ?? 'x'}: ${DG.format(p.x, !data.chartOptions?.logX ? '#0.000' : 'scientific')}`),
147
+ ui.divText(`${data.chartOptions?.yAxisName ?? 'y'}: ${DG.format(p.y, !data.chartOptions?.logY ? '#0.000' : 'scientific')}`)]), e.x + 16, e.y + 16);
148
+ if (!data.series![i].connectDots && data.series![i].clickToToggle && screenBounds.width >= FitConstants.MIN_AXES_CELL_PX_WIDTH &&
149
+ screenBounds.height >= FitConstants.MIN_AXES_CELL_PX_HEIGHT)
150
+ document.body.style.cursor = 'pointer';
151
+ return true;
152
+ }
153
+ }
154
+ }
155
+ return false;
156
+ }
157
+
158
+ /** `renderer` is the base type on purpose - taking the concrete one back would make this module and
159
+ * the renderer import each other. */
160
+ export function handleMouseMove(gridCell: DG.GridCell, e: MouseEvent, renderer: DG.GridCellRenderer): void {
161
+ if (!gridCell?.cell?.value)
162
+ return;
163
+
164
+ const screenBounds = inflateScreenBounds(gridCell.bounds);
165
+ if (screenBounds.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ||
166
+ screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT) {
167
+ const canvas = ui.canvas(300, 200);
168
+ renderer.render(canvas.getContext('2d')!, 0, 0, 300, 200, gridCell, null as any);
169
+ ui.tooltip.show(ui.divV([canvas]), e.x, e.y);
170
+ }
171
+
172
+ const data = getOrCreateParsedChartData(gridCell?.cell);
173
+
174
+ if (screenBounds.width >= FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH &&
175
+ screenBounds.height >= FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT) {
176
+ if (chartTooltip(data, screenBounds, e, {x: e.offsetX, y: e.offsetY}))
177
+ return;
178
+ ui.tooltip.hide();
179
+ }
180
+ document.body.style.cursor = 'default';
181
+ }
@@ -0,0 +1,64 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+
7
+ /** Chart geometry and what a cell of a given size has room for. */
8
+
9
+ export function inflateScreenBounds(rect: DG.Rect): DG.Rect {
10
+ return rect.inflate(rect.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ? FitConstants.MIN_INFLATE_SIZE : FitConstants.INFLATE_SIZE,
11
+ rect.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT ? FitConstants.MIN_INFLATE_SIZE : FitConstants.INFLATE_SIZE);
12
+ }
13
+
14
+ /** Performs a chart layout, returning [viewport, xAxis, yAxis] */
15
+ export function layoutChart(rect: DG.Rect, showXAxisName: boolean, showYAxisName: boolean, showTitle: boolean):
16
+ [DG.Rect, DG.Rect?, DG.Rect?] {
17
+ if (rect.width < FitConstants.MIN_AXES_CELL_PX_WIDTH || rect.height < FitConstants.MIN_AXES_CELL_PX_HEIGHT)
18
+ return [rect, undefined, undefined];
19
+ // room is made for the name that is drawn, not for both because one of them is
20
+ const axesLeftPxMargin = showYAxisName ? FitConstants.AXES_LEFT_PX_MARGIN_WITH_AXES_LABELS : FitConstants.AXES_LEFT_PX_MARGIN;
21
+ const axesBottomPxMargin = showXAxisName ? FitConstants.AXES_BOTTOM_PX_MARGIN_WITH_AXES_LABELS : FitConstants.AXES_BOTTOM_PX_MARGIN;
22
+ const axesTopPxMargin = showTitle ? FitConstants.AXES_TOP_PX_MARGIN_WITH_TITLE : FitConstants.AXES_TOP_PX_MARGIN;
23
+ const rightPxMargin = FitConstants.AXES_RIGHT_PX_MARGIN;
24
+ return [
25
+ rect.cutLeft(axesLeftPxMargin).cutBottom(axesBottomPxMargin).cutTop(axesTopPxMargin).cutRight(rightPxMargin),
26
+ rect.getBottom(axesBottomPxMargin).getTop(axesTopPxMargin).cutLeft(axesLeftPxMargin).cutRight(rightPxMargin),
27
+ rect.getLeft(axesLeftPxMargin).getRight(FitConstants.AXES_RIGHT_PX_MARGIN).cutBottom(axesBottomPxMargin).cutTop(axesTopPxMargin),
28
+ ];
29
+ }
30
+
31
+ export function areAxesShown(screenBounds: DG.Rect): boolean {
32
+ return screenBounds.width >= FitConstants.MIN_AXES_CELL_PX_WIDTH && screenBounds.height >= FitConstants.MIN_AXES_CELL_PX_HEIGHT;
33
+ }
34
+
35
+ /** Naming one axis is not naming the other, so each is asked about on its own. */
36
+ export function shownAxesNames(screenBounds: DG.Rect, data: IFitChartData): {x: boolean, y: boolean} {
37
+ const roomy = screenBounds.width >= FitConstants.MIN_X_AXIS_NAME_VISIBILITY_PX_WIDTH &&
38
+ screenBounds.height >= FitConstants.MIN_Y_AXIS_NAME_VISIBILITY_PX_HEIGHT;
39
+ return {x: roomy && !!data.chartOptions?.xAxisName, y: roomy && !!data.chartOptions?.yAxisName};
40
+ }
41
+
42
+ export function areAxesLabelsShown(screenBounds: DG.Rect, data: IFitChartData): boolean {
43
+ const shown = shownAxesNames(screenBounds, data);
44
+ return shown.x || shown.y;
45
+ }
46
+
47
+ export function isTitleShown(screenBounds: DG.Rect, data: IFitChartData): boolean {
48
+ return screenBounds.width >= FitConstants.MIN_TITLE_PX_WIDTH && screenBounds.height >= FitConstants.MIN_TITLE_PX_HEIGHT &&
49
+ !!data.chartOptions?.title;
50
+ }
51
+
52
+ export function isLegendShown(screenBounds: DG.Rect): boolean {
53
+ return screenBounds.width >= FitConstants.MIN_LEGEND_PX_WIDTH && screenBounds.height >= FitConstants.MIN_LEGEND_PX_HEIGHT;
54
+ }
55
+
56
+ export function areDroplineLabelsShown(screenBounds: DG.Rect): boolean {
57
+ return screenBounds.width >= FitConstants.MIN_DROPLINE_LABELS_PX_WIDTH &&
58
+ screenBounds.height >= FitConstants.MIN_DROPLINE_LABELS_PX_HEIGHT;
59
+ }
60
+
61
+ export function areDroplinesShown(screenBounds: DG.Rect): boolean {
62
+ return screenBounds.width >= FitConstants.MIN_DROPLINES_VISIBILITY_PX_WIDTH &&
63
+ screenBounds.height >= FitConstants.MIN_DROPLINES_VISIBILITY_PX_HEIGHT;
64
+ }