@datagrok/curves 1.10.12 → 1.10.14

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 (48) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/package-test.js +468 -4270
  3. package/dist/package-test.js.map +1 -1
  4. package/dist/package.js +252 -3895
  5. package/dist/package.js.map +1 -1
  6. package/package.json +4 -4
  7. package/src/fit/fit-demo.ts +1 -1
  8. package/src/fit/fit-grid-cell-handler.ts +385 -385
  9. package/src/fit/fit-inspection.ts +39 -0
  10. package/src/fit/fit-renderer.ts +1 -8
  11. package/src/fit/multi-curve-viewer.ts +1 -3
  12. package/src/fit/render-utils.ts +9 -7
  13. package/src/package-api.ts +2 -125
  14. package/src/package-test.ts +2 -3
  15. package/src/package.g.ts +0 -82
  16. package/src/package.ts +21 -128
  17. package/src/tests/curves-cell-renderer-tests.ts +15 -15
  18. package/src/tests/detector-tests.ts +1 -1
  19. package/src/tests/transform-tests.ts +1 -1
  20. package/test-console-output-1.log +21 -242
  21. package/test-record-1.mp4 +0 -0
  22. package/databases/plates/0000_init.sql +0 -167
  23. package/queries/plates-crud.sql +0 -148
  24. package/src/fit/const.ts +0 -73
  25. package/src/plate/excel-plates.ts +0 -112
  26. package/src/plate/plate-cell-renderer.ts +0 -50
  27. package/src/plate/plate-drc-analysis.ts +0 -262
  28. package/src/plate/plate-reader.ts +0 -28
  29. package/src/plate/plate-well-validators.ts +0 -41
  30. package/src/plate/plate-widget.ts +0 -242
  31. package/src/plate/plate.ts +0 -557
  32. package/src/plate/plates-folder-preview.ts +0 -63
  33. package/src/plate/readers/bmg-pherastar-96.ts +0 -42
  34. package/src/plate/readers/delfia-envision-96-max-rlu.ts +0 -16
  35. package/src/plate/readers/delfia-envision-by-row.ts +0 -18
  36. package/src/plate/readers/spectramax.ts +0 -42
  37. package/src/plate/utils.ts +0 -141
  38. package/src/plates/numeric_matcher.ts +0 -191
  39. package/src/plates/objects/plate-template-handler.ts +0 -48
  40. package/src/plates/plates-app.ts +0 -64
  41. package/src/plates/plates-crud.ts +0 -502
  42. package/src/plates/plates-demo.ts +0 -107
  43. package/src/plates/plates.sql +0 -169
  44. package/src/plates/views/plates-create-view.ts +0 -123
  45. package/src/plates/views/plates-schema-view.ts +0 -58
  46. package/src/plates/views/plates-search-view.ts +0 -137
  47. package/src/plates/views/plates-templates-view.ts +0 -37
  48. package/src/tests/plate-tests.ts +0 -153
@@ -1,385 +1,385 @@
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 {
7
- getSeriesStatistics,
8
- getSeriesFitFunction,
9
- LogOptions,
10
- getChartBounds,
11
- } from '@datagrok-libraries/statistics/src/fit/fit-data';
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';
30
- import {convertXMLToIFitChartData} from './fit-parser';
31
- import {FitConstants} from './const';
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];
74
- }
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++;
99
- }
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
- };
117
- }
118
-
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;
128
- }
129
- }
130
-
131
- function convertJnJColumnToJSON(column: DG.Column): void {
132
- for (let i = 0; i < column.length; i++) {
133
- const value = column.get(i);
134
- if (value === '') continue;
135
- const chartData: IFitChartData = convertXMLToIFitChartData(value);
136
- column.set(i, JSON.stringify(chartData));
137
- }
138
- column.setTag(FitConstants.TAG_FIT_CHART_FORMAT, '');
139
- }
140
-
141
- function detectSettings(df: DG.DataFrame): void {
142
- const fitColumns = df.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
143
- for (let i = 0; i < fitColumns.length; i++) {
144
- fitChartDataProperties.map((prop) => {
145
- fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = false;
146
- });
147
- fitSeriesProperties.map((prop) => {
148
- fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = false;
149
- });
150
- if (fitColumns[i].getTag(FitConstants.TAG_FIT_CHART_FORMAT) === FitConstants.TAG_FIT_CHART_FORMAT_3DX)
151
- convertJnJColumnToJSON(fitColumns[i]);
152
-
153
- for (let j = 0; j < fitColumns[i].length; j++) {
154
- if (fitColumns[i].get(j) === '') continue;
155
- const chartData = (JSON.parse(fitColumns[i].get(j) ?? '{}') ?? {}) as IFitChartData;
156
-
157
- fitChartDataProperties.map((prop) => {
158
- if (!chartData.chartOptions) return;
159
- if (chartData.chartOptions[prop.name as keyof IFitChartOptions] !== undefined)
160
- fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = true;
161
- });
162
-
163
- fitSeriesProperties.map((prop) => {
164
- if (!chartData.series) return;
165
- for (const series of chartData.series) {
166
- if (series[prop.name as keyof IFitSeriesOptions] !== undefined)
167
- fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = true;
168
- }
169
- });
170
- }
171
- }
172
- }
173
-
174
- function changeCurvesOptions(gridCell: DG.GridCell, inputBase: DG.InputBase, options: string, manipulationLevel: string): void {
175
- if (gridCell.cell.column.temp[`${CHART_OPTIONS}-custom-title`] === undefined)
176
- detectSettings(gridCell.cell.dataFrame);
177
- const propertyName = inputBase.property.name as string;
178
- const chartOptions = manipulationLevel === MANIPULATION_LEVEL.DATAFRAME ?
179
- getDataFrameChartOptions(gridCell.cell.dataFrame) : getColumnChartOptions(gridCell.cell.column);
180
- if (options === CHART_OPTIONS)
181
- (chartOptions.chartOptions![propertyName as keyof IFitChartOptions] as any) = inputBase.value;
182
- else if (options === SERIES_OPTIONS)
183
- (chartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions] as any) = inputBase.value;
184
-
185
- if (manipulationLevel === MANIPULATION_LEVEL.CELL) {
186
- const value = gridCell.cell.value;
187
- if (value === '') return;
188
- const chartData: IFitChartData = JSON.parse(value ?? '{}') ?? {};
189
- changePlotOptions(chartData, inputBase, options);
190
- gridCell.cell.value = JSON.stringify(chartData);
191
- } else {
192
- let columns: DG.Column[];
193
- if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
194
- gridCell.cell.dataFrame.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
195
- columns = gridCell.cell.dataFrame.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
196
- } else {
197
- gridCell.cell.column.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
198
- columns = [gridCell.cell.column];
199
- }
200
-
201
- for (let i = 0; i < columns.length; i++) {
202
- if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
203
- const columnChartOptions = getColumnChartOptions(columns[i]);
204
- options === CHART_OPTIONS ? delete columnChartOptions.chartOptions![propertyName as keyof IFitChartOptions] :
205
- delete columnChartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions];
206
- columns[i].tags[FitConstants.TAG_FIT] = JSON.stringify(columnChartOptions);
207
- }
208
- if (columns[i].temp[`${options}-custom-${propertyName}`] === false) continue;
209
-
210
- columns[i].init((j) => {
211
- const value = columns[i].get(j);
212
- if (value === '') return value;
213
- const chartData = (JSON.parse(columns[i].get(j) ?? '{}') ?? {}) as IFitChartData;
214
- if (options === CHART_OPTIONS) {
215
- if (chartData.chartOptions === undefined) return value;
216
- if (chartData.chartOptions[propertyName as keyof IFitChartOptions] === undefined)
217
- return value;
218
- delete chartData.chartOptions[propertyName as keyof IFitChartOptions];
219
- } else {
220
- if (chartData.series === undefined) return value;
221
- let isSeriesChanged = false;
222
- for (const series of chartData.series) {
223
- if (series[propertyName as keyof IFitSeriesOptions] !== undefined) {
224
- delete series[propertyName as keyof IFitSeriesOptions];
225
- isSeriesChanged = true;
226
- }
227
- }
228
- if (chartData.seriesOptions)
229
- delete chartData.seriesOptions[propertyName as keyof IFitSeriesOptions];
230
- if (!isSeriesChanged) return value;
231
- }
232
- return JSON.stringify(chartData);
233
- });
234
- columns[i].temp[`${options}-custom-${propertyName}`] = false;
235
- }
236
- }
237
- gridCell.grid.invalidate();
238
- }
239
-
240
-
241
- export class FitGridCellHandler extends DG.ObjectHandler {
242
- get type(): string {
243
- return 'GridCell';
244
- }
245
-
246
- isApplicable(x: any): boolean {
247
- return x instanceof DG.GridCell && x.cellType === FitConstants.FIT_CELL_TYPE;
248
- }
249
-
250
- // TODO: add aspect ratio for the cell
251
- // TODO: add legend
252
- // TODO: add the table for the values on the cell or don't render it at all
253
- // TODO: fix the curves demo app
254
-
255
- renderProperties(gridCell: DG.GridCell, _context: any = null): HTMLElement {
256
- const acc = ui.accordion('Curves property panel');
257
- // TODO: make just the base ui.input.choice after nullable option is added
258
- const switchProperty = DG.Property.js('level', DG.TYPE.STRING, {description: 'Controls the level at which properties will be switched',
259
- defaultValue: 'Column', choices: ['Dataframe', 'Column', 'Cell'], nullable: false});
260
- const switchLevelInput = ui.input.forProperty(switchProperty);
261
-
262
- // temporarily because input doesn't show the tooltip
263
- ui.tooltip.bind(switchLevelInput.captionLabel, 'Controls the level at which properties will be switched');
264
-
265
- const chartData = getOrCreateParsedChartData(gridCell.cell);
266
- const columnChartOptions = getColumnChartOptions(gridCell.cell.column);
267
- const dfChartOptions = getDataFrameChartOptions(gridCell.cell.dataFrame);
268
-
269
- const seriesOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
270
- changeCurvesOptions(gridCell, inputBase, SERIES_OPTIONS, switchLevelInput.value)};
271
- const chartOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
272
- changeCurvesOptions(gridCell, inputBase, CHART_OPTIONS, switchLevelInput.value)};
273
-
274
- const setValidColors = (colorFieldName: string) => {
275
- if (dfChartOptions.seriesOptions && !isColorValid(dfChartOptions.seriesOptions[colorFieldName]) &&
276
- columnChartOptions.seriesOptions && !isColorValid(columnChartOptions.seriesOptions[colorFieldName])) {
277
- if (chartData.seriesOptions) {
278
- if (!isColorValid(chartData.seriesOptions[colorFieldName])) {
279
- chartData.seriesOptions[colorFieldName] = DG.Color.toHtml(colorFieldName === 'outlierColor' ?
280
- DG.Color.red : DG.Color.getCategoricalColor(0));
281
- }
282
- } else {
283
- if (!isColorValid(chartData.series ? chartData.series[0][colorFieldName] : '')) {
284
- chartData.series![0][colorFieldName] = DG.Color.toHtml(colorFieldName === 'outlierColor' ?
285
- DG.Color.red : DG.Color.getCategoricalColor(0));
286
- }
287
- }
288
- }
289
- };
290
- const tableCell = gridCell.cell;
291
- setValidColors('pointColor');
292
- setValidColors('fitLineColor');
293
- setValidColors('outlierColor');
294
-
295
- mergeProperties(fitSeriesProperties, columnChartOptions.seriesOptions, chartData.seriesOptions ? chartData.seriesOptions :
296
- chartData.series ? chartData.series[0] ?? {} : {});
297
- mergeProperties(fitSeriesProperties, dfChartOptions.seriesOptions, chartData.seriesOptions ? chartData.seriesOptions :
298
- chartData.series ? chartData.series[0] ?? {} : {});
299
- mergeProperties(fitChartDataProperties, columnChartOptions.chartOptions,
300
- chartData.chartOptions ? chartData.chartOptions : {});
301
- mergeProperties(fitChartDataProperties, dfChartOptions.chartOptions,
302
- chartData.chartOptions ? chartData.chartOptions : {});
303
-
304
- if (chartData.chartOptions?.allowXZeroes && chartData.chartOptions?.logX &&
305
- chartData.series?.some((series) => series.points.some((p) => p.x === 0)))
306
- substituteZeroes(chartData);
307
-
308
- const form = ui.form([switchLevelInput]);
309
- const fitSeriesChildren = fitSeriesProperties.map((p) => ui.input.forProperty(p, chartData.seriesOptions ? chartData.seriesOptions : chartData.series![0], seriesOptionsRefresh));
310
- ui.forms.addGroup(form, 'Series options', fitSeriesChildren);
311
- ui.forms.addGroup(form, 'Chart options', fitChartDataProperties.map((p) => ui.input.forProperty(p, chartData.chartOptions, chartOptionsRefresh)));
312
- acc.addPane('Options', () => form);
313
-
314
- const choices = (chartData.series?.length ?? 0) > 1 ? ['all', 'aggregated'] : ['all'];
315
- const seriesStatsProperty = DG.Property.js('series', DG.TYPE.STRING,
316
- {description: 'Controls whether to show series statistics or aggregated statistics',
317
- defaultValue: 'all', choices: choices, nullable: false});
318
- const seriesStatsInput = ui.input.forProperty(seriesStatsProperty, null, {onValueChanged: () => {
319
- acc.getPane('Fit').root.lastElementChild!.replaceChildren(createFitPane());
320
- }});
321
- const aggrTypeProperty = DG.Property.js('aggregation type', DG.TYPE.STRING,
322
- {description: 'Controls which aggregation to use on the series statistics',
323
- defaultValue: 'med', choices: Object.values(DG.STATS), nullable: false});
324
- const aggrTypeInput = ui.input.forProperty(aggrTypeProperty, null, {onValueChanged: () => {
325
- acc.getPane('Fit').root.lastElementChild!.replaceChildren(createFitPane());
326
- }});
327
-
328
- function createFitPane(): HTMLElement {
329
- const hostItems = (chartData.series?.length ?? 0) > 1 ? seriesStatsInput.stringValue === 'aggregated' ?
330
- [seriesStatsInput.root, aggrTypeInput.root] : [seriesStatsInput.root] : null;
331
- const host = ui.divV(hostItems!);
332
- const dataBounds = getChartBounds(chartData);
333
- if (dataBounds.x <= 0 && chartData.chartOptions) chartData.chartOptions.logX = false;
334
- if (dataBounds.y <= 0 && chartData.chartOptions) chartData.chartOptions.logY = false;
335
-
336
- if (seriesStatsInput.stringValue === 'all') {
337
- const chartLogOptions: LogOptions = {logX: chartData.chartOptions?.logX, logY: chartData.chartOptions?.logY};
338
- for (let i = 0; i < chartData.series!.length; i++) {
339
- const series = chartData.series![i];
340
- const seriesStatistics = calculateSeriesStats(series, i, chartLogOptions, tableCell);
341
-
342
- const color = getSeriesColor(series, i, ColorType.FIT_LINE);
343
- const seriesName = series.name ?? 'series ' + i;
344
- host.appendChild(ui.panel([
345
- ui.h1(seriesName, {style: {color: color}}),
346
- ui.input.form(seriesStatistics, statisticsProperties, {
347
- onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
348
- const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, seriesNumber: i};
349
- await DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
350
- }, `Calculate ${input.property.name} for the whole column`))
351
-
352
- // TODO: Replace with this one after dima merges his branch
353
- // const newName = gridCell.cell.dataFrame.columns.getUnusedName(`${gridCell.gridColumn.name} ${seriesName} ${input.property.name}`);
354
- // await gridCell.cell.dataFrame.columns.addNewCalculated(newName, `Curves:addStatisticsColumn("table", \$\{${gridCell.gridColumn.name}\}, "${input.property.name}", ${i})`, undefined, undefined, false);
355
- // }, `Calculate ${input.property.name} for the whole column`))
356
- })
357
- ]));
358
- }
359
- } else {
360
- const seriesStatistics = getChartDataAggrStats(chartData, aggrTypeInput.stringValue, tableCell);
361
- host.appendChild(ui.panel([
362
- ui.h1(`series ${aggrTypeInput.stringValue}`),
363
- ui.input.form(seriesStatistics, statisticsProperties, {
364
- onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
365
- const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, aggrType: aggrTypeInput.stringValue};
366
- await DG.Func.find({name: 'addAggrStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
367
- }, `Calculate ${input.property.name} ${aggrTypeInput.stringValue} for the whole column`))
368
- })
369
- ]));
370
- }
371
-
372
- return host;
373
- }
374
-
375
- const chartPane = acc.addPane('Chart', () => DG.GridCellWidget.fromGridCell(gridCell).root);
376
- const screenBounds = FitChartCellRenderer.inflateScreenBounds(gridCell.bounds);
377
- if (screenBounds.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ||
378
- screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT)
379
- chartPane.expanded = true;
380
-
381
- acc.addPane('Fit', () => createFitPane());
382
-
383
- return acc.root;
384
- }
385
- }
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 {
7
+ getSeriesStatistics,
8
+ getSeriesFitFunction,
9
+ LogOptions,
10
+ getChartBounds,
11
+ } from '@datagrok-libraries/statistics/src/fit/fit-data';
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';
30
+ import {convertXMLToIFitChartData} from './fit-parser';
31
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
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];
74
+ }
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++;
99
+ }
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
+ };
117
+ }
118
+
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;
128
+ }
129
+ }
130
+
131
+ function convertJnJColumnToJSON(column: DG.Column): void {
132
+ for (let i = 0; i < column.length; i++) {
133
+ const value = column.get(i);
134
+ if (value === '') continue;
135
+ const chartData: IFitChartData = convertXMLToIFitChartData(value);
136
+ column.set(i, JSON.stringify(chartData));
137
+ }
138
+ column.setTag(FitConstants.TAG_FIT_CHART_FORMAT, '');
139
+ }
140
+
141
+ function detectSettings(df: DG.DataFrame): void {
142
+ const fitColumns = df.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
143
+ for (let i = 0; i < fitColumns.length; i++) {
144
+ fitChartDataProperties.map((prop) => {
145
+ fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = false;
146
+ });
147
+ fitSeriesProperties.map((prop) => {
148
+ fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = false;
149
+ });
150
+ if (fitColumns[i].getTag(FitConstants.TAG_FIT_CHART_FORMAT) === FitConstants.TAG_FIT_CHART_FORMAT_3DX)
151
+ convertJnJColumnToJSON(fitColumns[i]);
152
+
153
+ for (let j = 0; j < fitColumns[i].length; j++) {
154
+ if (fitColumns[i].get(j) === '') continue;
155
+ const chartData = (JSON.parse(fitColumns[i].get(j) ?? '{}') ?? {}) as IFitChartData;
156
+
157
+ fitChartDataProperties.map((prop) => {
158
+ if (!chartData.chartOptions) return;
159
+ if (chartData.chartOptions[prop.name as keyof IFitChartOptions] !== undefined)
160
+ fitColumns[i].temp[`${CHART_OPTIONS}-custom-${prop.name}`] = true;
161
+ });
162
+
163
+ fitSeriesProperties.map((prop) => {
164
+ if (!chartData.series) return;
165
+ for (const series of chartData.series) {
166
+ if (series[prop.name as keyof IFitSeriesOptions] !== undefined)
167
+ fitColumns[i].temp[`${SERIES_OPTIONS}-custom-${prop.name}`] = true;
168
+ }
169
+ });
170
+ }
171
+ }
172
+ }
173
+
174
+ function changeCurvesOptions(gridCell: DG.GridCell, inputBase: DG.InputBase, options: string, manipulationLevel: string): void {
175
+ if (gridCell.cell.column.temp[`${CHART_OPTIONS}-custom-title`] === undefined)
176
+ detectSettings(gridCell.cell.dataFrame);
177
+ const propertyName = inputBase.property.name as string;
178
+ const chartOptions = manipulationLevel === MANIPULATION_LEVEL.DATAFRAME ?
179
+ getDataFrameChartOptions(gridCell.cell.dataFrame) : getColumnChartOptions(gridCell.cell.column);
180
+ if (options === CHART_OPTIONS)
181
+ (chartOptions.chartOptions![propertyName as keyof IFitChartOptions] as any) = inputBase.value;
182
+ else if (options === SERIES_OPTIONS)
183
+ (chartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions] as any) = inputBase.value;
184
+
185
+ if (manipulationLevel === MANIPULATION_LEVEL.CELL) {
186
+ const value = gridCell.cell.value;
187
+ if (value === '') return;
188
+ const chartData: IFitChartData = JSON.parse(value ?? '{}') ?? {};
189
+ changePlotOptions(chartData, inputBase, options);
190
+ gridCell.cell.value = JSON.stringify(chartData);
191
+ } else {
192
+ let columns: DG.Column[];
193
+ if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
194
+ gridCell.cell.dataFrame.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
195
+ columns = gridCell.cell.dataFrame.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
196
+ } else {
197
+ gridCell.cell.column.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
198
+ columns = [gridCell.cell.column];
199
+ }
200
+
201
+ for (let i = 0; i < columns.length; i++) {
202
+ if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
203
+ const columnChartOptions = getColumnChartOptions(columns[i]);
204
+ options === CHART_OPTIONS ? delete columnChartOptions.chartOptions![propertyName as keyof IFitChartOptions] :
205
+ delete columnChartOptions.seriesOptions![propertyName as keyof IFitSeriesOptions];
206
+ columns[i].tags[FitConstants.TAG_FIT] = JSON.stringify(columnChartOptions);
207
+ }
208
+ if (columns[i].temp[`${options}-custom-${propertyName}`] === false) continue;
209
+
210
+ columns[i].init((j) => {
211
+ const value = columns[i].get(j);
212
+ if (value === '') return value;
213
+ const chartData = (JSON.parse(columns[i].get(j) ?? '{}') ?? {}) as IFitChartData;
214
+ if (options === CHART_OPTIONS) {
215
+ if (chartData.chartOptions === undefined) return value;
216
+ if (chartData.chartOptions[propertyName as keyof IFitChartOptions] === undefined)
217
+ return value;
218
+ delete chartData.chartOptions[propertyName as keyof IFitChartOptions];
219
+ } else {
220
+ if (chartData.series === undefined) return value;
221
+ let isSeriesChanged = false;
222
+ for (const series of chartData.series) {
223
+ if (series[propertyName as keyof IFitSeriesOptions] !== undefined) {
224
+ delete series[propertyName as keyof IFitSeriesOptions];
225
+ isSeriesChanged = true;
226
+ }
227
+ }
228
+ if (chartData.seriesOptions)
229
+ delete chartData.seriesOptions[propertyName as keyof IFitSeriesOptions];
230
+ if (!isSeriesChanged) return value;
231
+ }
232
+ return JSON.stringify(chartData);
233
+ });
234
+ columns[i].temp[`${options}-custom-${propertyName}`] = false;
235
+ }
236
+ }
237
+ gridCell.grid.invalidate();
238
+ }
239
+
240
+
241
+ export class FitGridCellHandler extends DG.ObjectHandler {
242
+ get type(): string {
243
+ return 'GridCell';
244
+ }
245
+
246
+ isApplicable(x: any): boolean {
247
+ return x instanceof DG.GridCell && x.cellType === FitConstants.FIT_CELL_TYPE;
248
+ }
249
+
250
+ // TODO: add aspect ratio for the cell
251
+ // TODO: add legend
252
+ // TODO: add the table for the values on the cell or don't render it at all
253
+ // TODO: fix the curves demo app
254
+
255
+ renderProperties(gridCell: DG.GridCell, _context: any = null): HTMLElement {
256
+ const acc = ui.accordion('Curves property panel');
257
+ // TODO: make just the base ui.input.choice after nullable option is added
258
+ const switchProperty = DG.Property.js('level', DG.TYPE.STRING, {description: 'Controls the level at which properties will be switched',
259
+ defaultValue: 'Column', choices: ['Dataframe', 'Column', 'Cell'], nullable: false});
260
+ const switchLevelInput = ui.input.forProperty(switchProperty);
261
+
262
+ // temporarily because input doesn't show the tooltip
263
+ ui.tooltip.bind(switchLevelInput.captionLabel, 'Controls the level at which properties will be switched');
264
+
265
+ const chartData = getOrCreateParsedChartData(gridCell.cell);
266
+ const columnChartOptions = getColumnChartOptions(gridCell.cell.column);
267
+ const dfChartOptions = getDataFrameChartOptions(gridCell.cell.dataFrame);
268
+
269
+ const seriesOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
270
+ changeCurvesOptions(gridCell, inputBase, SERIES_OPTIONS, switchLevelInput.value)};
271
+ const chartOptionsRefresh = {onValueChanged: (v: any, inputBase: DG.InputBase) =>
272
+ changeCurvesOptions(gridCell, inputBase, CHART_OPTIONS, switchLevelInput.value)};
273
+
274
+ const setValidColors = (colorFieldName: string) => {
275
+ if (dfChartOptions.seriesOptions && !isColorValid(dfChartOptions.seriesOptions[colorFieldName]) &&
276
+ columnChartOptions.seriesOptions && !isColorValid(columnChartOptions.seriesOptions[colorFieldName])) {
277
+ if (chartData.seriesOptions) {
278
+ if (!isColorValid(chartData.seriesOptions[colorFieldName])) {
279
+ chartData.seriesOptions[colorFieldName] = DG.Color.toHtml(colorFieldName === 'outlierColor' ?
280
+ DG.Color.red : DG.Color.getCategoricalColor(0));
281
+ }
282
+ } else {
283
+ if (!isColorValid(chartData.series ? chartData.series[0][colorFieldName] : '')) {
284
+ chartData.series![0][colorFieldName] = DG.Color.toHtml(colorFieldName === 'outlierColor' ?
285
+ DG.Color.red : DG.Color.getCategoricalColor(0));
286
+ }
287
+ }
288
+ }
289
+ };
290
+ const tableCell = gridCell.cell;
291
+ setValidColors('pointColor');
292
+ setValidColors('fitLineColor');
293
+ setValidColors('outlierColor');
294
+
295
+ mergeProperties(fitSeriesProperties, columnChartOptions.seriesOptions, chartData.seriesOptions ? chartData.seriesOptions :
296
+ chartData.series ? chartData.series[0] ?? {} : {});
297
+ mergeProperties(fitSeriesProperties, dfChartOptions.seriesOptions, chartData.seriesOptions ? chartData.seriesOptions :
298
+ chartData.series ? chartData.series[0] ?? {} : {});
299
+ mergeProperties(fitChartDataProperties, columnChartOptions.chartOptions,
300
+ chartData.chartOptions ? chartData.chartOptions : {});
301
+ mergeProperties(fitChartDataProperties, dfChartOptions.chartOptions,
302
+ chartData.chartOptions ? chartData.chartOptions : {});
303
+
304
+ if (chartData.chartOptions?.allowXZeroes && chartData.chartOptions?.logX &&
305
+ chartData.series?.some((series) => series.points.some((p) => p.x === 0)))
306
+ substituteZeroes(chartData);
307
+
308
+ const form = ui.form([switchLevelInput]);
309
+ const fitSeriesChildren = fitSeriesProperties.map((p) => ui.input.forProperty(p, chartData.seriesOptions ? chartData.seriesOptions : chartData.series![0], seriesOptionsRefresh));
310
+ ui.forms.addGroup(form, 'Series options', fitSeriesChildren);
311
+ ui.forms.addGroup(form, 'Chart options', fitChartDataProperties.map((p) => ui.input.forProperty(p, chartData.chartOptions, chartOptionsRefresh)));
312
+ acc.addPane('Options', () => form);
313
+
314
+ const choices = (chartData.series?.length ?? 0) > 1 ? ['all', 'aggregated'] : ['all'];
315
+ const seriesStatsProperty = DG.Property.js('series', DG.TYPE.STRING,
316
+ {description: 'Controls whether to show series statistics or aggregated statistics',
317
+ defaultValue: 'all', choices: choices, nullable: false});
318
+ const seriesStatsInput = ui.input.forProperty(seriesStatsProperty, null, {onValueChanged: () => {
319
+ acc.getPane('Fit').root.lastElementChild!.replaceChildren(createFitPane());
320
+ }});
321
+ const aggrTypeProperty = DG.Property.js('aggregation type', DG.TYPE.STRING,
322
+ {description: 'Controls which aggregation to use on the series statistics',
323
+ defaultValue: 'med', choices: Object.values(DG.STATS), nullable: false});
324
+ const aggrTypeInput = ui.input.forProperty(aggrTypeProperty, null, {onValueChanged: () => {
325
+ acc.getPane('Fit').root.lastElementChild!.replaceChildren(createFitPane());
326
+ }});
327
+
328
+ function createFitPane(): HTMLElement {
329
+ const hostItems = (chartData.series?.length ?? 0) > 1 ? seriesStatsInput.stringValue === 'aggregated' ?
330
+ [seriesStatsInput.root, aggrTypeInput.root] : [seriesStatsInput.root] : null;
331
+ const host = ui.divV(hostItems!);
332
+ const dataBounds = getChartBounds(chartData);
333
+ if (dataBounds.x <= 0 && chartData.chartOptions) chartData.chartOptions.logX = false;
334
+ if (dataBounds.y <= 0 && chartData.chartOptions) chartData.chartOptions.logY = false;
335
+
336
+ if (seriesStatsInput.stringValue === 'all') {
337
+ const chartLogOptions: LogOptions = {logX: chartData.chartOptions?.logX, logY: chartData.chartOptions?.logY};
338
+ for (let i = 0; i < chartData.series!.length; i++) {
339
+ const series = chartData.series![i];
340
+ const seriesStatistics = calculateSeriesStats(series, i, chartLogOptions, tableCell);
341
+
342
+ const color = getSeriesColor(series, i, ColorType.FIT_LINE);
343
+ const seriesName = series.name ?? 'series ' + i;
344
+ host.appendChild(ui.panel([
345
+ ui.h1(seriesName, {style: {color: color}}),
346
+ ui.input.form(seriesStatistics, statisticsProperties, {
347
+ onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
348
+ const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, seriesNumber: i};
349
+ await DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
350
+ }, `Calculate ${input.property.name} for the whole column`))
351
+
352
+ // TODO: Replace with this one after dima merges his branch
353
+ // const newName = gridCell.cell.dataFrame.columns.getUnusedName(`${gridCell.gridColumn.name} ${seriesName} ${input.property.name}`);
354
+ // await gridCell.cell.dataFrame.columns.addNewCalculated(newName, `Curves:addStatisticsColumn("table", \$\{${gridCell.gridColumn.name}\}, "${input.property.name}", ${i})`, undefined, undefined, false);
355
+ // }, `Calculate ${input.property.name} for the whole column`))
356
+ })
357
+ ]));
358
+ }
359
+ } else {
360
+ const seriesStatistics = getChartDataAggrStats(chartData, aggrTypeInput.stringValue, tableCell);
361
+ host.appendChild(ui.panel([
362
+ ui.h1(`series ${aggrTypeInput.stringValue}`),
363
+ ui.input.form(seriesStatistics, statisticsProperties, {
364
+ onCreated: (input) => input.root.appendChild(ui.iconFA('plus', async () => {
365
+ const funcParams = {table: gridCell.cell.dataFrame, colName: gridCell.gridColumn.name, propName: input.property.name, aggrType: aggrTypeInput.stringValue};
366
+ await DG.Func.find({name: 'addAggrStatisticsColumn'})[0].prepare(funcParams).call(undefined, undefined, {processed: false});
367
+ }, `Calculate ${input.property.name} ${aggrTypeInput.stringValue} for the whole column`))
368
+ })
369
+ ]));
370
+ }
371
+
372
+ return host;
373
+ }
374
+
375
+ const chartPane = acc.addPane('Chart', () => DG.GridCellWidget.fromGridCell(gridCell).root);
376
+ const screenBounds = FitChartCellRenderer.inflateScreenBounds(gridCell.bounds);
377
+ if (screenBounds.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ||
378
+ screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT)
379
+ chartPane.expanded = true;
380
+
381
+ acc.addPane('Fit', () => createFitPane());
382
+
383
+ return acc.root;
384
+ }
385
+ }