@datagrok/curves 1.12.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/CLAUDE.md +118 -15
  3. package/README.md +51 -4
  4. package/dist/package-test.js +7963 -4867
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3411 -2024
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +5 -4
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/curve-converter.ts +8 -1
  12. package/src/fit/data-to-curves.ts +10 -5
  13. package/src/fit/fit-chart-data.ts +323 -0
  14. package/src/fit/fit-grid-cell-handler.ts +98 -231
  15. package/src/fit/fit-inspection.ts +3 -3
  16. package/src/fit/fit-interaction.ts +181 -0
  17. package/src/fit/fit-layout.ts +64 -0
  18. package/src/fit/fit-legend.ts +292 -0
  19. package/src/fit/fit-options.ts +222 -0
  20. package/src/fit/fit-parser.ts +16 -5
  21. package/src/fit/fit-renderer.ts +180 -469
  22. package/src/fit/fit-statistics.ts +154 -0
  23. package/src/fit/multi-curve-viewer.ts +46 -20
  24. package/src/fit/render-utils.ts +208 -150
  25. package/src/package-api.ts +92 -14
  26. package/src/package-test.ts +6 -0
  27. package/src/package.g.ts +70 -15
  28. package/src/package.ts +121 -15
  29. package/src/tests/calculated-columns-tests.ts +299 -0
  30. package/src/tests/converter-tests.ts +29 -0
  31. package/src/tests/curve-data.ts +82 -0
  32. package/src/tests/fit-cache-tests.ts +128 -0
  33. package/src/tests/fit-tests.ts +310 -3
  34. package/src/tests/legend-tests.ts +243 -0
  35. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  36. package/src/tests/panel-renderer-tests.ts +502 -0
  37. package/src/tests/project-tests.ts +99 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +357 -110
  40. package/test-record-1.mp4 +0 -0
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@datagrok/curves",
3
3
  "friendlyName": "Curves",
4
- "version": "1.12.1",
4
+ "version": "1.13.0",
5
5
  "description": "Curves provides support for fitted curves (such as dose-response curves), including in-grid rendering, storing charts in cells, interactivity, and automatic fitting.",
6
6
  "author": {
7
7
  "name": "Dmytro Kovalyov",
8
8
  "email": "dkovalyov@datagrok.ai"
9
9
  },
10
10
  "dependencies": {
11
- "@datagrok-libraries/statistics": "^1.12.3",
12
- "@datagrok-libraries/utils": "^4.6.5",
11
+ "@datagrok-libraries/statistics": "^1.12.10",
13
12
  "@datagrok-libraries/test": "^1.2.0",
13
+ "@datagrok-libraries/utils": "^4.6.5",
14
14
  "@types/wu": "^2.1.42",
15
15
  "@typescript-eslint/eslint-plugin": "^5.62.0",
16
16
  "@typescript-eslint/parser": "^5.62.0",
@@ -34,7 +34,8 @@
34
34
  "webpack-cli": "^5.1.4"
35
35
  },
36
36
  "overrides": {
37
- "datagrok-api": "$datagrok-api"
37
+ "datagrok-api": "$datagrok-api",
38
+ "uuid": "^11.1.1"
38
39
  },
39
40
  "scripts": {
40
41
  "link-all": "npm link datagrok-api @datagrok-libraries/utils @datagrok-libraries/statistics",
@@ -5,11 +5,11 @@
5
5
  #tags: Transform
6
6
  #top-menu: Data | Curves | Calculate MSR...
7
7
  #input: dataframe table [Input data table]
8
- #input: column ic50Column [IC50 column]
9
- #input: column compoundIdColumn [Compound ID column]
10
- #input: column runDateColumn [Run date column]
11
- #input: column assayNameColumn [Assay name column]
12
- #input: column targetEntityColumn [Target entity column]
8
+ #input: column ic50Column {type: numerical; caption: IC50} [IC50 values, one row per measurement]
9
+ #input: column compoundIdColumn {type: categorical; caption: Compound ID} [Compound identifier the measurements are grouped by]
10
+ #input: column runDateColumn {caption: Run date} [Date of the run; used as the repeat axis]
11
+ #input: column assayNameColumn {type: categorical; caption: Assay} [Assay name]
12
+ #input: column targetEntityColumn {type: categorical; caption: Target entity} [Target entity]
13
13
  #output: dataframe res {action:join(table)}
14
14
 
15
15
  import pandas as pd
@@ -332,8 +332,17 @@ odf = table
332
332
  # assayNameColumn = 'assay_name'
333
333
  # targetEntityColumn = 'cell_line'
334
334
  # ic50Column = 'reported_ic50'
335
- sufficient_compounds = get_compounds_for_msr(odf, compound_col=compoundIdColumn, run_date_col=runDateColumn, assay_col=assayNameColumn, target_col=targetEntityColumn)
336
- msr_results = calculate_compound_database_msr(odf, min_runs=2, min_measurements=2, ic50_col=ic50Column, compound_col=compoundIdColumn, run_date_col=runDateColumn, assay_col=assayNameColumn, target_col=targetEntityColumn)
335
+
336
+ work_df = pd.DataFrame({
337
+ 'ic50': odf[ic50Column],
338
+ 'compound_id': odf[compoundIdColumn],
339
+ 'run_date': odf[runDateColumn],
340
+ 'assay_name': odf[assayNameColumn],
341
+ 'target_entity': odf[targetEntityColumn],
342
+ })
343
+
344
+ sufficient_compounds = get_compounds_for_msr(work_df, compound_col='compound_id', run_date_col='run_date', assay_col='assay_name', target_col='target_entity')
345
+ msr_results = calculate_compound_database_msr(work_df, min_runs=2, min_measurements=2, ic50_col='ic50', compound_col='compound_id', run_date_col='run_date', assay_col='assay_name', target_col='target_entity')
337
346
 
338
347
  # generate a dataset which is the same length as the input data, and for each corresponding row, have the results from the msr_results dataset except the compound_id, assay_name and target_entity. use these three for matching between the two
339
348
  # res = msr_results
@@ -69,7 +69,14 @@ export function parseCellValue(cellValue: string, column?: DG.Column | null): IF
69
69
  return {series: []};
70
70
 
71
71
  const jsonStr = column ? convertCellValue(cellValue, column) : cellValue;
72
- return JSON.parse(jsonStr ?? '{}') ?? {};
72
+ try {
73
+ return JSON.parse(jsonStr ?? '{}') ?? {};
74
+ } catch (_e) {
75
+ // Cell value is not valid fit JSON (e.g. a column mis-detected as 'fit' via a substring match).
76
+ // Degrade to an empty chart so the renderer hits the existing 'No series to show' path and draws the
77
+ // incorrect-fit marker, instead of throwing a SyntaxError on every grid redraw.
78
+ return {series: []};
79
+ }
73
80
  }
74
81
 
75
82
  /** Returns true if the column uses a non-native format (has a converter). */
@@ -6,10 +6,15 @@ import * as grok from 'datagrok-api/grok';
6
6
  import * as ui from 'datagrok-api/ui';
7
7
  import * as api from '../package-api';
8
8
  import wu from 'wu';
9
- import {FitFunctionType, FitFunctionTypes} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
9
+ import {FitFunctionType, FitFunctionTypes} from '@datagrok-libraries/statistics/src/fit/fit-engine';
10
10
 
11
11
  const groupColumnName = 'Compound|Assay|Target';
12
12
 
13
+ /** A group key read out loud: the parts that are actually there, spaced apart. */
14
+ function groupLabel(groupKey: string): string {
15
+ return groupKey.split('||').filter((part) => part !== '' && part !== 'null' && part !== 'undefined').join(' | ');
16
+ }
17
+
13
18
  function setColumnDefaultValue(table: DG.DataFrame, input: DG.InputBase<DG.Column | null>, check: (col: DG.Column) => boolean, values: string[]) {
14
19
  const col = table.columns.toList().filter((c) => check(c)).sort((a, b) => a.name.length - b.name.length).find((c) => values.some((v) => c.name.toLowerCase().includes(v)));
15
20
  if (col)
@@ -588,7 +593,7 @@ export async function convertDataToCurves(df: DG.DataFrame,
588
593
  const color = getColor(colorKey);
589
594
  const fitFunctionName = parentObj?.[curveKey]?.fitFunction ? parentObj[curveKey].fitFunction : FIT_FUNCTION_4PL_DOSE_RESPONSE;
590
595
  const s: IFitSeries = {
591
- fit: undefined, fitFunction: fitFunctionName, clickToToggle: true, droplines: ['IC50'], name: `${runID}`,
596
+ fitFunction: fitFunctionName as FitFunctionType, clickToToggle: true, droplines: ['IC50'], name: `${runID}`,
592
597
  points: x.map((xv, i) => ({x: xv, y: y[i], outlier: outliers[i], marker: markerType, size: 5})).sort((a, b) => a.x - b.x), parameters: params, fitLineColor: color, pointColor: DG.Color.toHtml(DG.Color.gray)
593
598
  };
594
599
  const fitData: Omit<FitChartData, 'seriesOptions'> = {
@@ -596,7 +601,7 @@ export async function convertDataToCurves(df: DG.DataFrame,
596
601
  xAxisName: concentrationCol.name,
597
602
  yAxisName: readoutCol.name,
598
603
  logX: true,
599
- title: `${curve.name ?? curveKey ?? ''}`,
604
+ title: groupLabel(`${curve.name ?? curveKey ?? ''}`),
600
605
  },
601
606
  series: [s],
602
607
  };
@@ -605,8 +610,8 @@ export async function convertDataToCurves(df: DG.DataFrame,
605
610
  tableColList.push(curvesCol);
606
611
  curvesCol.semType = 'fit';
607
612
  curvesCol.setTag('cell.renderer', 'fit');
608
- // add group column
609
- tableColList.push(DG.Column.fromStrings(groupColumnName, curvesObjsArray.map((c) => c[1].groupKey)));
613
+ // the key identifies a group; the column is what a person reads off a trellis header
614
+ tableColList.push(DG.Column.fromStrings(groupColumnName, curvesObjsArray.map((c) => groupLabel(c[1].groupKey))));
610
615
 
611
616
  const otherColumns = curvesObjsArray.reduce((acc, c) => { Object.keys(c[1].info).forEach((k) => acc.add(k)); return acc; }, new Set<string>());
612
617
 
@@ -0,0 +1,323 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ import {
5
+ IFitChartData,
6
+ IFitSeries,
7
+ IFitChartOptions,
8
+ FitCurve,
9
+ fitChartDataProperties,
10
+ LogOptions,
11
+ } from '@datagrok-libraries/statistics/src/fit/fit-curve';
12
+ import {createDefaultChartData} from '@datagrok-libraries/statistics/src/fit/fit-data';
13
+ import {Fit, FitFunction, fitSeries, fitSeriesProperties} from '@datagrok-libraries/statistics/src/fit/fit-engine';
14
+ import {getDataPoints} from '@datagrok-libraries/statistics/src/fit/fit-points';
15
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
16
+ import {parseCellValue} from './curve-converter';
17
+
18
+ /** Chart data assembly and the fit caches. A leaf, so the renderer and the statistics do not import
19
+ * each other through it. */
20
+
21
+ export const fittedCurves: DG.LruCache<string, FitCurve> = new DG.LruCache<string, FitCurve>(1000);
22
+ export const parsedCurves: DG.LruCache<string, IFitChartData> = new DG.LruCache<string, IFitChartData>(1000);
23
+ export const curvesDataPoints: DG.LruCache<string, {x: number[], y: number[]}> = new DG.LruCache<string, {x: number[], y: number[]}>(2000);
24
+
25
+ /** Copies the {@link properties} that {@link target} does not define yet from {@link source}. */
26
+ export function mergeProperties(properties: DG.Property[], source: any, target: any): void {
27
+ if (!source || !target)
28
+ return;
29
+
30
+ for (const p of properties) {
31
+ if (!(p.name in target) && p.name in source)
32
+ target[p.name] = source[p.name];
33
+ }
34
+ }
35
+
36
+ export const CHART_OPTIONS = 'chartOptions';
37
+ export const SERIES_OPTIONS = 'seriesOptions';
38
+
39
+ /** Assigns over {@link target}, unlike {@link mergeProperties} - this is how an explicitly set level
40
+ * outranks the value a series declares for itself. */
41
+ function applyExplicit(source: any, names: string[] | undefined, target: any, claimedByCell?: string[]): void {
42
+ if (!source || !target || !names)
43
+ return;
44
+ for (const name of names) {
45
+ if (name in source && !claimedByCell?.includes(name))
46
+ target[name] = source[name];
47
+ }
48
+ }
49
+
50
+ /** Column and dataframe levels applied over a cell, in that order, skipping anything the cell claims. */
51
+ function applySourceExplicit(cellChartData: IFitChartData, columnChartData: IFitChartData,
52
+ dfChartData: IFitChartData, section: 'chartOptions' | 'seriesOptions', target: any): void {
53
+ const claimed = cellChartData.explicit?.[section];
54
+ applyExplicit(dfChartData[section], dfChartData.explicit?.[section], target, claimed);
55
+ applyExplicit(columnChartData[section], columnChartData.explicit?.[section], target, claimed);
56
+ }
57
+
58
+ /** Labels are data rather than a setting, so the levels combine per key instead of the nearest one
59
+ * winning outright - an assay name set on the column and a plate statistic set on the cell both
60
+ * belong on the plot. */
61
+ function mergeLabels(target: IFitChartOptions | undefined, ...sources: (IFitChartOptions | undefined)[]): void {
62
+ if (!target)
63
+ return;
64
+ for (const source of sources) {
65
+ if (source?.labels)
66
+ target.labels = {...source.labels, ...target.labels};
67
+ }
68
+ }
69
+
70
+ export function mergeChartOptions(chartOptions: IFitChartOptions[], series: IFitSeries[] = []): IFitChartOptions {
71
+ if (chartOptions.length === 0)
72
+ return {};
73
+
74
+ let minX = Number.MAX_VALUE;
75
+ let minY = Number.MAX_VALUE;
76
+ let maxX = Number.MIN_VALUE;
77
+ let maxY = Number.MIN_VALUE;
78
+ let xAxisName: string | undefined;
79
+ let yAxisName: string | undefined;
80
+ let title: string | undefined;
81
+ let logX: boolean = false;
82
+ let logY: boolean = false;
83
+ let allowXZeroes: boolean = false;
84
+
85
+ for (const options of chartOptions) {
86
+ if (options.minX !== null && options.minX !== undefined)
87
+ minX = Math.min(minX, options.minX);
88
+ if (options.minY !== null && options.minY !== undefined)
89
+ minY = Math.min(minY, options.minY);
90
+ if (options.maxX !== null && options.maxX !== undefined)
91
+ maxX = Math.max(maxX, options.maxX);
92
+ if (options.maxY !== null && options.maxY !== undefined)
93
+ maxY = Math.max(maxY, options.maxY);
94
+ if (options.title !== null && options.title !== undefined)
95
+ title ??= options.title;
96
+ if (options.xAxisName !== null && options.xAxisName !== undefined)
97
+ xAxisName ??= options.xAxisName;
98
+ if (options.yAxisName !== null && options.yAxisName !== undefined)
99
+ yAxisName ??= options.yAxisName;
100
+ if (options.logX !== null && options.logX !== undefined && options.logX)
101
+ logX = true;
102
+ if (options.logY !== null && options.logY !== undefined && options.logY)
103
+ logY = true;
104
+ if (options.allowXZeroes !== null && options.allowXZeroes !== undefined && options.allowXZeroes)
105
+ allowXZeroes = true;
106
+ }
107
+
108
+ // a range a cell declares for its own chart is not one for an overlay of many: it would cut off
109
+ // the curves a wider column contributes, and adding a column could no longer widen the axis
110
+ for (const s of series)
111
+ for (const p of s.points) {
112
+ if (p.x < minX) minX = Number.MAX_VALUE;
113
+ if (p.x > maxX) maxX = Number.MIN_VALUE;
114
+ if (p.y < minY) minY = Number.MAX_VALUE;
115
+ if (p.y > maxY) maxY = Number.MIN_VALUE;
116
+ }
117
+
118
+ return {
119
+ minX: minX === Number.MAX_VALUE ? undefined : minX,
120
+ minY: minY === Number.MAX_VALUE ? undefined : minY,
121
+ maxX: maxX === Number.MIN_VALUE ? undefined : maxX,
122
+ maxY: maxY === Number.MIN_VALUE ? undefined : maxY,
123
+ title: title,
124
+ xAxisName: xAxisName,
125
+ yAxisName: yAxisName,
126
+ logX: logX,
127
+ logY: logY,
128
+ allowXZeroes: allowXZeroes,
129
+ };
130
+ }
131
+
132
+ export function mergeSeries(series: IFitSeries[]): IFitSeries | null {
133
+ if (series.length === 0)
134
+ return null;
135
+ const mergedSeries: IFitSeries = {
136
+ points: [],
137
+ name: series[0].name,
138
+ fitFunction: series[0].fitFunction,
139
+ markerType: series[0].markerType,
140
+ lineStyle: series[0].lineStyle,
141
+ pointColor: series[0].pointColor,
142
+ fitLineColor: series[0].fitLineColor,
143
+ confidenceIntervalColor: series[0].confidenceIntervalColor,
144
+ outlierColor: series[0].outlierColor,
145
+ connectDots: series[0].connectDots,
146
+ showFitLine: series[0].showFitLine,
147
+ showPoints: series[0].showPoints,
148
+ showOutliers: series[0].showOutliers,
149
+ showCurveConfidenceInterval: series[0].showCurveConfidenceInterval,
150
+ errorModel: series[0].errorModel,
151
+ clickToToggle: series[0].clickToToggle,
152
+ labels: series[0].labels,
153
+ droplines: series[0].droplines,
154
+ columnName: series[0].columnName,
155
+ };
156
+ for (const s of series)
157
+ mergedSeries.points = [...mergedSeries.points, ...s.points];
158
+ return mergedSeries;
159
+ }
160
+
161
+ function parsedChartDataKey(column: DG.Column, rowIdx: number): string {
162
+ return `tableId: ${column.dataFrame.id} || tableName: ${column.dataFrame.name} || colName: ${column.name} || colVersion: ${column.version} || rowIdx: ${rowIdx}`;
163
+ }
164
+
165
+ /** Returns either cached or constructed chart data for the specified table cell. */
166
+ export function getOrCreateParsedChartData(tableCell: DG.Cell, useCache = true): IFitChartData {
167
+ const column = tableCell?.column;
168
+ return (useCache && column && tableCell) ?
169
+ parsedCurves.getOrCreate(parsedChartDataKey(column, tableCell.rowIndex), () => getChartData(tableCell)) :
170
+ getChartData(tableCell);
171
+ }
172
+
173
+ /** The cascade applied without a cell, for the detached column the recalculation path hands us. */
174
+ export function mergeSourceChartOptions(cellChartData: IFitChartData, column: DG.Column,
175
+ df?: DG.DataFrame): IFitChartData {
176
+ const columnChartOptions = getColumnChartOptions(column);
177
+ const dfChartOptions = df ? getDataFrameChartOptions(df) : {};
178
+ cellChartData.series ??= [];
179
+ cellChartData.chartOptions ??= columnChartOptions.chartOptions;
180
+ mergeProperties(fitChartDataProperties, columnChartOptions.chartOptions, cellChartData.chartOptions);
181
+ mergeProperties(fitChartDataProperties, dfChartOptions.chartOptions, cellChartData.chartOptions);
182
+ mergeLabels(cellChartData.chartOptions, columnChartOptions.chartOptions, dfChartOptions.chartOptions);
183
+ applySourceExplicit(cellChartData, columnChartOptions, dfChartOptions, CHART_OPTIONS, cellChartData.chartOptions);
184
+ for (const series of cellChartData.series) {
185
+ mergeProperties(fitSeriesProperties, cellChartData.seriesOptions, series);
186
+ mergeProperties(fitSeriesProperties, columnChartOptions.seriesOptions, series);
187
+ mergeProperties(fitSeriesProperties, dfChartOptions.seriesOptions, series);
188
+ applySourceExplicit(cellChartData, columnChartOptions, dfChartOptions, SERIES_OPTIONS, series);
189
+ }
190
+ return cellChartData;
191
+ }
192
+
193
+ /** Strips the stray '|' some cell values carry. Both parse paths must agree. */
194
+ export function sanitizeCellValue(value: string): string {
195
+ return value.includes('|') ? value.replaceAll('|', '') : value;
196
+ }
197
+
198
+ /** Constructs {@link IFitChartData} for a cell, applying the column and dataframe levels. */
199
+ function getChartData(tableCell: DG.Cell): IFitChartData {
200
+ const cellValue = tableCell.value as string;
201
+ const column = tableCell.column;
202
+ let cellChartData: IFitChartData = column ? (column.type === DG.TYPE.STRING ?
203
+ parseCellValue(cellValue, column) :
204
+ createDefaultChartData()) : JSON.parse(sanitizeCellValue(cellValue) ?? '{}') ?? {};
205
+ if (column?.type === DG.TYPE.STRING && !cellChartData.series?.length)
206
+ cellChartData = parseCellValue(sanitizeCellValue(cellValue), column);
207
+
208
+ const columnChartOptions = tableCell.column ? getColumnChartOptions(tableCell.column) : {};
209
+ const dfChartOptions = tableCell.column ? getDataFrameChartOptions(tableCell.dataFrame) : {};
210
+
211
+ cellChartData.series ??= [];
212
+ cellChartData.chartOptions ??= columnChartOptions.chartOptions;
213
+
214
+ mergeProperties(fitChartDataProperties, columnChartOptions.chartOptions, cellChartData.chartOptions);
215
+ mergeProperties(fitChartDataProperties, dfChartOptions.chartOptions, cellChartData.chartOptions);
216
+ mergeLabels(cellChartData.chartOptions, columnChartOptions.chartOptions, dfChartOptions.chartOptions);
217
+ applySourceExplicit(cellChartData, columnChartOptions, dfChartOptions, CHART_OPTIONS, cellChartData.chartOptions);
218
+ for (const series of cellChartData.series) {
219
+ mergeProperties(fitSeriesProperties, cellChartData.seriesOptions, series);
220
+ mergeProperties(fitSeriesProperties, columnChartOptions.seriesOptions, series);
221
+ mergeProperties(fitSeriesProperties, dfChartOptions.seriesOptions, series);
222
+ applySourceExplicit(cellChartData, columnChartOptions, dfChartOptions, SERIES_OPTIONS, series);
223
+ }
224
+
225
+ return cellChartData;
226
+ }
227
+
228
+ /** Kept apart from [fittedCurves]: a viewer merges a cell's series and applies its own log options. */
229
+ export const viewerFits: DG.LruCache<string, FitCurve> = new DG.LruCache<string, FitCurve>(2000);
230
+ const chartDataIds: WeakMap<IFitChartData, number> = new WeakMap<IFitChartData, number>();
231
+ let nextChartDataId = 0;
232
+
233
+ /** A parsed cell's identity: re-parsing yields a new object, and so a new id, retiring its fits. */
234
+ export function chartDataId(data: IFitChartData): number {
235
+ let id = chartDataIds.get(data);
236
+ if (id === undefined)
237
+ chartDataIds.set(data, id = ++nextChartDataId);
238
+ return id;
239
+ }
240
+
241
+ /** The log options belong here with the cell: the same curve fits differently on a log axis. */
242
+ function cellCurveKey(column: DG.Column, tableCell: DG.Cell, idx: number, logOptions?: LogOptions): string {
243
+ return `tableId: ${column.dataFrame.id} || tableName: ${column.dataFrame.name} || colName: ${column.name} || ` +
244
+ `colVersion: ${column.version} || rowIdx: ${tableCell.rowIndex} || idx: ${idx} || ` +
245
+ `logX: ${logOptions?.logX} || logY: ${logOptions?.logY}`;
246
+ }
247
+
248
+ /** Returns existing, or fits curve for the specified grid cell and series. */
249
+ export function getOrCreateCachedFitCurve(series: IFitSeries, seriesIdx: number, fitFunc: FitFunction<Fit>,
250
+ chartLogOptions: LogOptions, tableCell?: DG.Cell, useCache = true, identity?: string): FitCurve {
251
+ const dataPoints = getOrCreateCachedCurvesDataPoints(series, seriesIdx, chartLogOptions, false, tableCell, useCache);
252
+ const column = tableCell?.column;
253
+ if (identity)
254
+ return viewerFits.getOrCreate(`${identity} || logX: ${chartLogOptions?.logX} || logY: ${chartLogOptions?.logY}`,
255
+ () => fitSeries(series, fitFunc, dataPoints, chartLogOptions));
256
+ return (useCache && column && tableCell) ?
257
+ fittedCurves.getOrCreate(cellCurveKey(column, tableCell, seriesIdx, chartLogOptions), () => {
258
+ return fitSeries(series, fitFunc, dataPoints, chartLogOptions);
259
+ }) : fitSeries(series, fitFunc, dataPoints, chartLogOptions);
260
+ }
261
+
262
+ /** Returns existing, or maps new data points for the specified series. */
263
+ export function getOrCreateCachedCurvesDataPoints(series: IFitSeries, idx: number, logOptions?: LogOptions,
264
+ userParamsFlag?: boolean, tableCell?: DG.Cell, useCache = true): {x: number[], y: number[]} {
265
+ const column = tableCell?.column;
266
+ return (useCache && column && tableCell) ?
267
+ curvesDataPoints.getOrCreate(`${cellCurveKey(column, tableCell, idx, logOptions)} || userParamsFlag: ${userParamsFlag}`, () => {
268
+ return getDataPoints(series, logOptions, userParamsFlag);
269
+ }) : getDataPoints(series, logOptions, userParamsFlag);
270
+ }
271
+
272
+ /** Reads a level's options, migrating a value stored under the pre-`.%` tag name so that only one of
273
+ * the two ever holds the options. */
274
+ function readChartOptions(tags: any): IFitChartData {
275
+ // an empty tag parsed to an exception on every cell of the column
276
+ const stored = tags[FitConstants.TAG_FIT];
277
+ if (stored)
278
+ return JSON.parse(stored);
279
+ const legacy = tags[FitConstants.TAG_FIT_LEGACY];
280
+ const migrated = !!legacy;
281
+ tags[FitConstants.TAG_FIT] = migrated ? legacy : JSON.stringify(createDefaultChartData());
282
+ if (migrated)
283
+ delete tags[FitConstants.TAG_FIT_LEGACY];
284
+ return JSON.parse(tags[FitConstants.TAG_FIT]);
285
+ }
286
+
287
+ /** Returns existing, or creates new dataframe default chart options. */
288
+ export function getDataFrameChartOptions(df: DG.DataFrame): IFitChartData {
289
+ return readChartOptions(df.tags);
290
+ }
291
+
292
+ /** Returns existing, or creates new column default chart options. */
293
+ export function getColumnChartOptions(column: DG.Column): IFitChartData {
294
+ return readChartOptions(column.tags);
295
+ }
296
+
297
+ /** Performs x zeroes substitution if log x */
298
+ export function substituteZeroes(data: IFitChartData): void {
299
+ for (let i = 0; i < data.series?.length!; i++) {
300
+ const series = data.series![i];
301
+ if (series.points.every((p) => p.x !== 0))
302
+ continue;
303
+ let minNonZeroX = Number.MAX_VALUE;
304
+ let maxNonZeroX = 0;
305
+ let countOfDistNonZeroX = 0;
306
+ const uniqueArr: number[] = [];
307
+ for (let j = 0; j < series.points.length; j++) {
308
+ if (series.points[j].x < minNonZeroX && series.points[j].x !== 0)
309
+ minNonZeroX = series.points[j].x;
310
+ if (series.points[j].x > maxNonZeroX && series.points[j].x !== 0)
311
+ maxNonZeroX = series.points[j].x;
312
+ if (!uniqueArr.includes(series.points[j].x)) {
313
+ uniqueArr[uniqueArr.length] = series.points[j].x;
314
+ countOfDistNonZeroX++;
315
+ }
316
+ }
317
+ const zeroSubstitute = Math.pow(10, Math.log10(minNonZeroX) - (Math.log10(maxNonZeroX) - Math.log10(minNonZeroX) / (countOfDistNonZeroX - 1)));
318
+ for (let j = 0; j < series.points.length; j++) {
319
+ if (series.points[j].x === 0)
320
+ series.points[j].x = zeroSubstitute;
321
+ }
322
+ }
323
+ }