@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
@@ -0,0 +1,82 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as ui from 'datagrok-api/ui';
3
+
4
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {FitChartCellRenderer} from '../fit/fit-renderer';
7
+ import {isTitleShown, layoutChart, shownAxesNames} from '../fit/fit-layout';
8
+ import {getOrCreateParsedChartData} from '../fit/fit-chart-data';
9
+
10
+ /** Renders a cell onto a canvas and returns every string the chart drew, with where it put it and
11
+ * the plot it was laid out in - which is what the legend hover is asked about. */
12
+ export function renderedRows(json: string, name: string, width: number = 400, height: number = 300):
13
+ {rows: {text: string, x: number, y: number}[], data: IFitChartData, dataBox: DG.Rect} {
14
+ const col = DG.Column.fromStrings('curve', [json]);
15
+ col.semType = FitConstants.FIT_SEM_TYPE;
16
+ const df = DG.DataFrame.fromColumns([col]);
17
+ df.name = name;
18
+
19
+ const rows: {text: string, x: number, y: number}[] = [];
20
+ const g = ui.canvas(width, height).getContext('2d')!;
21
+ const fillText = g.fillText.bind(g);
22
+ g.fillText = ((text: string, x: number, y: number) => {
23
+ rows.push({text: text, x: x, y: y});
24
+ fillText(text, x, y);
25
+ }) as any;
26
+
27
+ const rect = new DG.Rect(0, 0, width, height);
28
+ const data = getOrCreateParsedChartData(df.cell(0, 'curve'));
29
+ new FitChartCellRenderer().renderCurves(g, rect, data);
30
+ const axesNames = shownAxesNames(rect, data);
31
+ const dataBox = layoutChart(rect, axesNames.x, axesNames.y, isTitleShown(rect, data))[0];
32
+ return {rows: rows, data: data, dataBox: dataBox};
33
+ }
34
+
35
+ /** Every string the chart drew. */
36
+ export function renderedTexts(json: string, name: string, width: number = 400, height: number = 300): string[] {
37
+ return renderedRows(json, name, width, height).rows.map((row) => row.text);
38
+ }
39
+
40
+ export const CONCENTRATIONS = [1e-9, 3e-9, 1e-8, 3e-8, 1e-7, 3e-7, 1e-6, 3e-6, 1e-5, 3e-5, 1e-4];
41
+
42
+ /** Sigmoid dose-response points with the inflection point at 10^`logIC50`. */
43
+ export function sigmoidPoints(logIC50: number): {x: number, y: number}[] {
44
+ return CONCENTRATIONS.map((x) => ({x: x, y: 5 + 95 / (1 + Math.pow(10, Math.log10(x) - logIC50))}));
45
+ }
46
+
47
+ /** One sigmoid series in a cell, with logX baked into the cell's chart options. */
48
+ export function curveJson(logIC50: number): string {
49
+ return JSON.stringify({
50
+ chartOptions: {logX: true},
51
+ series: [{fitFunction: 'sigmoid', name: 'series', points: sigmoidPoints(logIC50)}],
52
+ } as IFitChartData);
53
+ }
54
+
55
+ /** One sigmoid series that declares a confidence interval, the way the demo data does. */
56
+ export function ciCurveJson(): string {
57
+ return JSON.stringify({
58
+ chartOptions: {logX: true},
59
+ series: [{fitFunction: 'sigmoid', name: 'series', showCurveConfidenceInterval: true, points: sigmoidPoints(-6.5)}],
60
+ } as IFitChartData);
61
+ }
62
+
63
+ /** One cell holding several sigmoid series, each with its own inflection point. */
64
+ export function multiSeriesCurveJson(logIC50s: number[]): string {
65
+ return JSON.stringify({
66
+ chartOptions: {logX: true},
67
+ series: logIC50s.map((logIC50, i) => ({
68
+ fitFunction: 'sigmoid', name: `series ${i}`, points: sigmoidPoints(logIC50),
69
+ })),
70
+ } as IFitChartData);
71
+ }
72
+
73
+ /** Two sigmoid series, one plot-level label and one per curve. */
74
+ export function labelledCurveJson(): string {
75
+ return JSON.stringify({
76
+ chartOptions: {logX: true, labels: {'Z prime': 0.72}, showLabels: ['Z prime', 'compound']},
77
+ series: [
78
+ {fitFunction: 'sigmoid', name: 's0', labels: {compound: 'GRK-1'}, points: sigmoidPoints(-6.5)},
79
+ {fitFunction: 'sigmoid', name: 's1', labels: {compound: 'GRK-2'}, points: sigmoidPoints(-5.5)},
80
+ ],
81
+ } as IFitChartData);
82
+ }
@@ -0,0 +1,128 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as ui from 'datagrok-api/ui';
3
+
4
+ import {category, test, expect} from '@datagrok-libraries/test/src/test';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
7
+ import {getSeriesFitFunction} from '@datagrok-libraries/statistics/src/fit/fit-data';
8
+ import {FitChartCellRenderer} from '../fit/fit-renderer';
9
+ import {chartDataId, getOrCreateCachedFitCurve, getOrCreateParsedChartData, viewerFits} from '../fit/fit-chart-data';
10
+
11
+ import {curveJson, multiSeriesCurveJson} from './curve-data';
12
+
13
+ /** A one-curve table, and the cell the caches are keyed on. */
14
+ function curveCell(name: string, logIC50: number = -6.5): DG.Cell {
15
+ const col = DG.Column.fromStrings('curve', [curveJson(logIC50)]);
16
+ col.semType = FitConstants.FIT_SEM_TYPE;
17
+ const df = DG.DataFrame.fromColumns([col]);
18
+ df.name = name;
19
+ return df.cell(0, 'curve');
20
+ }
21
+
22
+ category('fit cache', () => {
23
+ test('a curve fitted in log space is not handed to a linear plot', async () => {
24
+ // the grid, the property panel and a trellis can each show one cell in a different space at once
25
+ const cell = curveCell('fitCacheLogSpace');
26
+ const series = getOrCreateParsedChartData(cell).series![0];
27
+ const fitFunc = getSeriesFitFunction(series);
28
+
29
+ const inLog = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: true, logY: false}, cell);
30
+ const linear = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: false, logY: false}, cell);
31
+ expect(Array.from(inLog.parameters).toString() !== Array.from(linear.parameters).toString(), true,
32
+ `the two spaces should fit differently, both gave ${Array.from(inLog.parameters)}`);
33
+
34
+ const again = getOrCreateCachedFitCurve(series, 0, fitFunc, {logX: true, logY: false}, cell);
35
+ expect(again === inLog, true, 'asking twice in the same space should come from the cache');
36
+ });
37
+
38
+ test('a viewer fit is reused, and never confused with another cell', async () => {
39
+ // both at row 0, which with an unsaved table is most of what the grid's key looks at
40
+ const one = curveCell('fitCacheRowsOne', -7);
41
+ const other = curveCell('fitCacheRowsOther', -5);
42
+ const oneData = getOrCreateParsedChartData(one);
43
+ const otherData = getOrCreateParsedChartData(other);
44
+ expect(chartDataId(oneData) !== chartDataId(otherData), true, 'two cells should not share an identity');
45
+
46
+ const logOptions = {logX: true, logY: false};
47
+ const fitFunc = getSeriesFitFunction(oneData.series![0]);
48
+ const first = getOrCreateCachedFitCurve(oneData.series![0], 0, fitFunc, logOptions, undefined, false,
49
+ `${chartDataId(oneData)} || idx: 0`);
50
+ const second = getOrCreateCachedFitCurve(otherData.series![0], 0, fitFunc, logOptions, undefined, false,
51
+ `${chartDataId(otherData)} || idx: 0`);
52
+ expect(first === second, false, 'two different curves must not answer for each other');
53
+ expect(Array.from(first.parameters).toString() !== Array.from(second.parameters).toString(), true,
54
+ 'and they fit differently, so a collision would be visible');
55
+
56
+ const repeat = getOrCreateCachedFitCurve(oneData.series![0], 0, fitFunc, logOptions, undefined, false,
57
+ `${chartDataId(oneData)} || idx: 0`);
58
+ expect(repeat === first, true, 'the same curve should be fitted once');
59
+ });
60
+
61
+ test('the viewer cache is kept apart from the grid one, and agrees with it', async () => {
62
+ const cell = curveCell('fitCacheApart');
63
+ const data = getOrCreateParsedChartData(cell);
64
+ const series = data.series![0];
65
+ const fitFunc = getSeriesFitFunction(series);
66
+ const logOptions = {logX: true, logY: false};
67
+
68
+ const forGrid = getOrCreateCachedFitCurve(series, 0, fitFunc, logOptions, cell);
69
+ const forViewer = getOrCreateCachedFitCurve(series, 0, fitFunc, logOptions, cell, true,
70
+ `${chartDataId(data)} || idx: 0`);
71
+ expect(forGrid === forViewer, false, 'the two caches must not share storage');
72
+ expect(Array.from(forGrid.parameters).toString(), Array.from(forViewer.parameters).toString(),
73
+ 'but keeping them apart must not change the answer');
74
+ });
75
+
76
+ test('a render that names its curves fits them once', async () => {
77
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
78
+ const g = ui.canvas(300, 200).getContext('2d')!;
79
+ const bounds = new DG.Rect(0, 0, 300, 200);
80
+ const identities = ['probeCell || idx: 0', 'probeCell || idx: 1'];
81
+ new FitChartCellRenderer().renderCurves(g, bounds, data, undefined, identities);
82
+
83
+ const keys = (viewerFits as unknown as {K: string[]}).K.filter(Boolean);
84
+ expect(identities.every((id) => keys.some((k) => k.startsWith(id))), true,
85
+ `the render should have cached a fit per identity, holds ${keys.length}`);
86
+
87
+ let refitted = false;
88
+ const options = data.chartOptions;
89
+ viewerFits.getOrCreate(`${identities[0]} || logX: ${options?.logX} || logY: ${options?.logY}`, () => {
90
+ refitted = true;
91
+ return null as any;
92
+ });
93
+ expect(refitted, false, 'a second render of the same curve should not fit it again');
94
+ });
95
+
96
+ test('a pipe in a title survives, and one that breaks the value is still stripped', async () => {
97
+ const titled = JSON.parse(curveJson(-6.5)) as IFitChartData;
98
+ titled.chartOptions!.title = 'compound 10 | Collapse Assay | run 4';
99
+ // the second value is valid only once the stray pipe is gone
100
+ const col = DG.Column.fromStrings('curve', [JSON.stringify(titled), '{"series":|[{"points":[]}]}']);
101
+ col.semType = FitConstants.FIT_SEM_TYPE;
102
+ const df = DG.DataFrame.fromColumns([col]);
103
+ df.name = 'pipeTitles';
104
+
105
+ expect(getOrCreateParsedChartData(df.cell(0, 'curve')).chartOptions!.title,
106
+ 'compound 10 | Collapse Assay | run 4', 'a pipe inside a title is not part of the value');
107
+ // the rescue still applies to a value the pipes actually break
108
+ expect(getOrCreateParsedChartData(df.cell(1, 'curve')).series!.length, 1,
109
+ 'stripping should still rescue a value that does not parse as it stands');
110
+ });
111
+
112
+ test('editing a cell retires the fits made from it', async () => {
113
+ const cell = curveCell('fitCacheEdit', -7);
114
+ const before = getOrCreateParsedChartData(cell);
115
+ const fitFunc = getSeriesFitFunction(before.series![0]);
116
+ const logOptions = {logX: true, logY: false};
117
+ const beforeFit = getOrCreateCachedFitCurve(before.series![0], 0, fitFunc, logOptions, undefined, false,
118
+ `${chartDataId(before)} || idx: 0`);
119
+
120
+ cell.column.set(0, curveJson(-5));
121
+ const after = getOrCreateParsedChartData(cell);
122
+ expect(chartDataId(after) !== chartDataId(before), true, 'a re-parsed cell should get a new identity');
123
+ const afterFit = getOrCreateCachedFitCurve(after.series![0], 0, fitFunc, logOptions, undefined, false,
124
+ `${chartDataId(after)} || idx: 0`);
125
+ expect(Array.from(afterFit.parameters).toString() !== Array.from(beforeFit.parameters).toString(), true,
126
+ 'so the edited curve is fitted afresh');
127
+ });
128
+ });
@@ -2,19 +2,40 @@
2
2
  import {
3
3
  getSeriesFitFunction,
4
4
  getCurve,
5
- fitSeries,
6
5
  getSeriesConfidenceInterval,
7
6
  getSeriesStatistics,
8
7
  getPointsArrays,
8
+ getSeriesFit,
9
+ toDataSpace,
9
10
  } from '@datagrok-libraries/statistics/src/fit/fit-data';
11
+ import {getDataPoints} from '@datagrok-libraries/statistics/src/fit/fit-points';
12
+ import {
13
+ fitSeries,
14
+ fitFunctions,
15
+ DEFAULT_FIT_FUNCTION,
16
+ getFitFunction,
17
+ getStatistic,
18
+ getStatisticProperty,
19
+ isFit,
20
+ FitTypeMap,
21
+ FitSeries,
22
+ SigmoidFit,
23
+ LinearFit,
24
+ LogLinearFit,
25
+ ExponentialFit,
26
+ FourPLDoseResponseFit,
27
+ JSFunctionFit,
28
+ } from '@datagrok-libraries/statistics/src/fit/fit-engine';
10
29
  import {
11
30
  sigmoid,
12
31
  FIT_FUNCTION_SIGMOID,
13
32
  IFitSeries,
14
- FIT_FUNCTION_LINEAR, FIT_FUNCTION_LOG_LINEAR, FIT_FUNCTION_EXPONENTIAL, linear, logLinear, exponential
33
+ FIT_FUNCTION_LINEAR, FIT_FUNCTION_LOG_LINEAR, FIT_FUNCTION_EXPONENTIAL, FIT_FUNCTION_4PL_DOSE_RESPONSE,
34
+ FIT_FUNCTION_4PL_REGRESSION, linear, logLinear, exponential
15
35
  } from '@datagrok-libraries/statistics/src/fit/fit-curve';
16
36
  import {calculateBoxPlotStatistics} from '@datagrok-libraries/statistics/src/box-plot-statistics';
17
- import {category, test, expect, expectArray} from '@datagrok-libraries/test/src/test';
37
+ import {category, test, expect, expectArray, expectFloat} from '@datagrok-libraries/test/src/test';
38
+ import {droplineFraction} from '../fit/render-utils';
18
39
 
19
40
 
20
41
  const sigmoidSeries: IFitSeries = {'fitLineColor': '#1f77b4', 'pointColor': '#1f77b4', 'showCurveConfidenceInterval': false, 'points': [{'x': 0.10000000149011612, 'y': 1.7412786483764648}, {'x': 0.6000000238418579, 'y': 1.8561450242996216}, {'x': 1.100000023841858, 'y': 1.6065685749053955}, {'x': 1.600000023841858, 'y': 1.70476496219635}, {'x': 2.0999999046325684, 'y': 1.5737264156341553}, {'x': 2.5999999046325684, 'y': 1.6007002592086792}, {'x': 3.0999999046325684, 'y': 1.6796687841415405}, {'x': 3.5999999046325684, 'y': 1.656104326248169}, {'x': 4.099999904632568, 'y': 1.782997488975525}, {'x': 4.599999904632568, 'y': 1.530208945274353}, {'x': 5.099999904632568, 'y': 1.1572397947311401}, {'x': 5.599999904632568, 'y': 0.8691964745521545}, {'x': 6.099999904632568, 'y': 0.3228665590286255}, {'x': 6.599999904632568, 'y': 0.2990703880786896}, {'x': 7.099999904632568, 'y': 0.23361243307590485}], 'fitFunction': 'sigmoid', 'clickToToggle': false, 'showFitLine': true, 'showPoints': 'points', 'parameters': [1.6914372095641517, 1.1536998642628853, 5.410173358224149, 0.2089689354045083]};
@@ -61,6 +82,20 @@ category('fit', () => {
61
82
  expect(polynomialFitFunc.y(polynomialFitFunc.getInitialParameters(polynomialXs, polynomialYs), 1.1), 7.3231);
62
83
  });
63
84
 
85
+ test('a series that names no fit function is fitted with the default', async () => {
86
+ // clearing the option leaves the series without one, and the panel and the renderer both ask
87
+ // before anything fills the default in
88
+ const cleared = new FitSeries(sigmoidSeries.points);
89
+ expect(getSeriesFitFunction(cleared).name, DEFAULT_FIT_FUNCTION, 'naming none should name the default');
90
+ (cleared as any).fitFunction = null;
91
+ expect(getSeriesFitFunction(cleared).name, DEFAULT_FIT_FUNCTION, 'and so should clearing it');
92
+ (cleared as any).fitFunction = 'no such fit function';
93
+ expect(getSeriesFitFunction(cleared).name, DEFAULT_FIT_FUNCTION, 'as should naming one that is gone');
94
+ // what the property panel asks of every series before it offers droplines
95
+ expect(getSeriesFitFunction(cleared).hasAsymptotes !== undefined, true,
96
+ 'the fit it hands back should be usable, not undefined');
97
+ });
98
+
64
99
  test('getCurve', async () => {
65
100
  const sigmoidCurve = getCurve(sigmoidSeries, sigmoidFitFunc);
66
101
  const linearCurve = getCurve(linearSeries, linearFitFunc);
@@ -167,6 +202,221 @@ category('fit', () => {
167
202
  expect(polynomialSeriesStatistics.rSquared, 0.846055768956569);
168
203
  });
169
204
 
205
+ test('fillParams', async () => {
206
+ const sigmoidCurve = fitSeries(sigmoidSeries, sigmoidFitFunc);
207
+ const sigmoidFit = sigmoidFitFunc.fillParams(sigmoidCurve, sigmoidSeries) as SigmoidFit;
208
+ expect(sigmoidFit.name, FIT_FUNCTION_SIGMOID);
209
+ expect(sigmoidFit.top, sigmoidCurve.parameters[0]);
210
+ expect(sigmoidFit.slope, sigmoidCurve.parameters[1]);
211
+ expect(sigmoidFit.ic50, sigmoidCurve.parameters[2]);
212
+ expect(sigmoidFit.bottom, sigmoidCurve.parameters[3]);
213
+ expect(sigmoidFit.interceptY, sigmoidCurve.fittedCurve(sigmoidCurve.parameters[2]));
214
+
215
+ const linearCurve = fitSeries(linearSeries, linearFitFunc);
216
+ const linearFit = linearFitFunc.fillParams(linearCurve, linearSeries) as LinearFit;
217
+ expect(linearFit.slope, linearCurve.parameters[0]);
218
+ expect(linearFit.intercept, linearCurve.parameters[1]);
219
+
220
+ const logLinearCurve = fitSeries(logLinearSeries, logLinearFitFunc);
221
+ const logLinearFit = logLinearFitFunc.fillParams(logLinearCurve, logLinearSeries) as LogLinearFit;
222
+ expect(logLinearFit.name, FIT_FUNCTION_LOG_LINEAR);
223
+ expect(logLinearFit.slope, logLinearCurve.parameters[0]);
224
+ expect(logLinearFit.intercept, logLinearCurve.parameters[1]);
225
+
226
+ const exponentialCurve = fitSeries(exponentialSeries, exponentialFitFunc);
227
+ const exponentialFit = exponentialFitFunc.fillParams(exponentialCurve, exponentialSeries) as ExponentialFit;
228
+ expect(exponentialFit.mantissa, exponentialCurve.parameters[0]);
229
+ expect(exponentialFit.power, exponentialCurve.parameters[1]);
230
+ });
231
+
232
+ test('fillParams dose-response', async () => {
233
+ const fitFunc = fitFunctions[FIT_FUNCTION_4PL_DOSE_RESPONSE];
234
+ const curve = fitSeries(sigmoidSeries, fitFunc);
235
+ const fit = fitFunc.fillParams(curve, sigmoidSeries) as FourPLDoseResponseFit;
236
+
237
+ expect(fit.name, FIT_FUNCTION_4PL_DOSE_RESPONSE);
238
+ expect(fit.ic50, curve.parameters[2]);
239
+ expect(fit.ec50, curve.parameters[2]);
240
+ expect(fit.top, curve.parameters[0]);
241
+ expect(fit.bottom, curve.parameters[3]);
242
+ });
243
+
244
+ test('fillParams custom function', async () => {
245
+ const curve = fitSeries(polynomialSeries, polynomialFitFunc);
246
+ const fit = polynomialFitFunc.fillParams(curve, polynomialSeries) as JSFunctionFit;
247
+
248
+ expectArray(fit.parameters, curve.parameters);
249
+ for (let i = 0; i < polynomialFitFunc.parameterNames.length; i++)
250
+ expect(fit[polynomialFitFunc.parameterNames[i]], curve.parameters[i]);
251
+ });
252
+
253
+ test('fillParams data points', async () => {
254
+ const curve = fitSeries(sigmoidSeries, sigmoidFitFunc);
255
+ const defaultFit = sigmoidFitFunc.fillParams(curve, sigmoidSeries);
256
+ const explicitFit = sigmoidFitFunc.fillParams(curve, sigmoidSeries,
257
+ getDataPoints(sigmoidSeries, undefined, false));
258
+ const logFit = sigmoidFitFunc.fillParams(curve, sigmoidSeries, undefined, {logX: true, logY: false});
259
+
260
+ expect(explicitFit.rSquared, defaultFit.rSquared);
261
+ expect(explicitFit.auc, defaultFit.auc);
262
+ expect(logFit.rSquared === defaultFit.rSquared, false);
263
+ });
264
+
265
+ test('statisticsProperties', async () => {
266
+ expectArray(sigmoidFitFunc.statisticsProperties.map((p) => p.name),
267
+ ['rSquared', 'auc', 'top', 'slope', 'ic50', 'bottom', 'interceptY', 'maxY', 'minY', 'pIC50']);
268
+ expectArray(linearFitFunc.statisticsProperties.map((p) => p.name),
269
+ ['rSquared', 'auc', 'slope', 'intercept']);
270
+ expectArray(logLinearFitFunc.statisticsProperties.map((p) => p.name),
271
+ ['rSquared', 'auc', 'slope', 'intercept']);
272
+ expectArray(exponentialFitFunc.statisticsProperties.map((p) => p.name),
273
+ ['rSquared', 'auc', 'mantissa', 'power']);
274
+ expectArray(fitFunctions[FIT_FUNCTION_4PL_DOSE_RESPONSE].statisticsProperties.map((p) => p.name),
275
+ ['rSquared', 'auc', 'top', 'slope', 'ic50', 'bottom', 'interceptY', 'maxY', 'minY', 'pIC50']);
276
+ expectArray(polynomialFitFunc.statisticsProperties.map((p) => p.name),
277
+ ['rSquared', 'auc', 'Slope', 'Intercept', 'Parameter3', 'Parameter4']);
278
+ });
279
+
280
+ test('statisticsProperties friendly names', async () => {
281
+ // parameter labels come from the fit function's own parameterNames, so the two cannot drift
282
+ expectArray(sigmoidFitFunc.statisticsProperties.map((p) => p.friendlyName),
283
+ ['R²', 'AUC', 'Top', 'Slope', 'IC50', 'Bottom', 'Y at IC50', 'Max Y', 'Min Y', 'pIC50']);
284
+ expectArray(fitFunctions[FIT_FUNCTION_4PL_REGRESSION].statisticsProperties.map((p) => p.friendlyName),
285
+ ['R²', 'AUC', 'Top', 'Slope', 'EC50', 'Bottom', 'Y at EC50', 'Max Y', 'Min Y']);
286
+ expectArray(fitFunctions[FIT_FUNCTION_4PL_DOSE_RESPONSE].statisticsProperties.map((p) => p.friendlyName),
287
+ ['R²', 'AUC', 'Max', 'Hill', 'IC50', 'Min', 'Y at IC50', 'Max Y', 'Min Y', 'pIC50']);
288
+ expectArray(linearFitFunc.statisticsProperties.map((p) => p.friendlyName),
289
+ ['R²', 'AUC', 'Slope', 'Intercept']);
290
+ });
291
+
292
+ test('getStatistic legacy names', async () => {
293
+ // getFitFunction is typed, so these need no casts - the fit type is known at compile time
294
+ const sigmoidFit = getSeriesFit(sigmoidSeries, getFitFunction('sigmoid'));
295
+ expect(getStatistic(sigmoidFit, 'interceptX'), sigmoidFit.ic50);
296
+ // the property panel's "+" button passes the current names, extracted columns from saved projects
297
+ // pass the legacy ones - both have to resolve off the same fit
298
+ expect(getStatistic(sigmoidFit, 'ic50'), sigmoidFit.ic50);
299
+ expect(getStatistic(sigmoidFit, 'maxY'), sigmoidFit.maxY);
300
+ expect(getStatistic(sigmoidFit, 'minY'), sigmoidFit.minY);
301
+ expect(getStatistic(sigmoidFit, 'top'), sigmoidFit.top);
302
+ expect(getStatistic(sigmoidFit, 'bottom'), sigmoidFit.bottom);
303
+ expect(getStatistic(sigmoidFit, 'slope'), sigmoidFit.slope);
304
+
305
+ const regressionFit = getSeriesFit({...sigmoidSeries, parameters: undefined}, getFitFunction('4pl-regression'));
306
+ expect(getStatistic(regressionFit, 'interceptX'), regressionFit.ec50);
307
+
308
+ const doseResponseFit = getSeriesFit({...sigmoidSeries, parameters: undefined},
309
+ getFitFunction('4pl-dose-response'));
310
+ expect(getStatistic(doseResponseFit, 'interceptX'), doseResponseFit.ic50);
311
+
312
+ // legacy names a 2-parameter fit lacks fall back to the slot the pre-typed API read positionally,
313
+ // and the descriptor has to agree - a value with no descriptor renders nothing on the plot
314
+ const linearFit = getSeriesFit(linearSeries, getFitFunction('linear'));
315
+ expect(getStatistic(linearFit, 'top'), linearFit.parameters[0]);
316
+ expect(getStatisticProperty(getFitFunction('linear'), 'top') !== undefined, true);
317
+ expect(getStatisticProperty(getFitFunction('linear'), 'interceptX') === undefined, true);
318
+ expect(getStatistic(linearFit, 'interceptX') === undefined);
319
+ expect(getStatistic(linearFit, 'interceptY') === undefined);
320
+ expect(getStatistic(linearFit, 'bottom') === undefined);
321
+ expect(getStatistic(linearFit, 'slope'), linearFit.slope);
322
+
323
+ // the pre-typed API reported interceptY for every fit function, custom ones included
324
+ const jsFit = getSeriesFit(polynomialSeries, getSeriesFitFunction(polynomialSeries));
325
+ expect(typeof getStatistic(jsFit, 'interceptY'), 'number');
326
+ // and a value with no descriptor is skipped by the plot, so both have to resolve
327
+ expect(getStatisticProperty(getSeriesFitFunction(polynomialSeries), 'interceptY') !== undefined, true);
328
+
329
+ // never resolves to a non-numeric field of the fit
330
+ expect(getStatistic(sigmoidFit, 'series') === undefined);
331
+ expect(getStatistic(sigmoidFit, 'parameters') === undefined);
332
+ expect(getStatistic(sigmoidFit, 'name') === undefined);
333
+ });
334
+
335
+ test('FitSeries options', async () => {
336
+ // this only compiles if FitSeries still exposes every IFitSeriesOptions member
337
+ const series = new FitSeries([{x: 1, y: 2}]);
338
+ series.name = 'a';
339
+ series.fitFunction = FIT_FUNCTION_SIGMOID;
340
+ series.parameters = [1, 2, 3, 4];
341
+ series.parameterBounds = [{min: 0, max: 1}];
342
+ series.markerType = 'circle';
343
+ series.outlierMarkerType = 'outlier';
344
+ series.lineStyle = 'dashed';
345
+ series.pointColor = '#111111';
346
+ series.fitLineColor = '#222222';
347
+ series.confidenceIntervalColor = '#333333';
348
+ series.outlierColor = '#444444';
349
+ series.connectDots = false;
350
+ series.showFitLine = true;
351
+ series.showPoints = 'points';
352
+ series.showOutliers = true;
353
+ series.showCurveConfidenceInterval = false;
354
+ series.errorModel = 'constant';
355
+ series.clickToToggle = true;
356
+ series.labels = {batch: 'A1'};
357
+ series.droplines = ['IC50'];
358
+ series.columnName = 'curve';
359
+ series.auxLegendName = 'aux';
360
+
361
+ expect(series.name, 'a');
362
+ expect(series.showPoints, 'points');
363
+ expect(series.droplines![0], 'IC50');
364
+ expect(series.auxLegendName, 'aux');
365
+
366
+ // a series stays JSON-serializable - an own `fit` property used to make this circular
367
+ const json = JSON.parse(JSON.stringify(series));
368
+ expect(json.name, 'a');
369
+ expect(json.columnName, 'curve');
370
+ });
371
+
372
+ test('maxY and minY', async () => {
373
+ const sigmoidFit = getSeriesFit(sigmoidSeries, getFitFunction('sigmoid'));
374
+ expect(sigmoidFit.maxY, Math.max(sigmoidFit.top, sigmoidFit.bottom));
375
+ expect(sigmoidFit.minY, Math.min(sigmoidFit.top, sigmoidFit.bottom));
376
+ expect(sigmoidFit.maxY >= sigmoidFit.minY, true);
377
+ });
378
+
379
+ test('toDataSpace', async () => {
380
+ const logX = {logX: true, logY: false};
381
+ const fitSpace = getSeriesFit(sigmoidSeries, getFitFunction('sigmoid'), undefined, logX);
382
+ const rawIc50 = fitSpace.ic50;
383
+ // toDataSpace mutates in place, so capture before converting
384
+ const untouchedTop = fitSpace.top;
385
+ const dataSpace = toDataSpace(fitSpace, logX);
386
+
387
+ // the inflection point is fitted in log space and must be reported as a concentration
388
+ expect(dataSpace.ic50, Math.pow(10, rawIc50));
389
+ // pIC50 is derived from the concentration, so only after the conversion
390
+ expect(dataSpace.pIC50, -Math.log10(Math.pow(10, rawIc50)));
391
+ expect(dataSpace.top, untouchedTop);
392
+
393
+ // the y asymptotes are reported in the space they were fitted in. A stored bottom of 0 has no
394
+ // finite logarithm, so the forward map has to skip it while the inverse would still return 1 -
395
+ // the two could never be exact inverses, so neither converts
396
+ const logY = {logX: false, logY: true};
397
+ const yFit = getSeriesFit(sigmoidSeries, getFitFunction('sigmoid'), undefined, logY);
398
+ const rawTop = yFit.top;
399
+ const rawIc50Y = yFit.ic50;
400
+ toDataSpace(yFit, logY);
401
+ expect(yFit.top, rawTop);
402
+ expect(yFit.ic50, rawIc50Y); // x untouched when logX is off
403
+
404
+ // no log axes means no conversion at all
405
+ const plain = getSeriesFit(sigmoidSeries, getFitFunction('sigmoid'));
406
+ const plainIc50 = plain.ic50;
407
+ toDataSpace(plain, {logX: false, logY: false});
408
+ expect(plain.ic50, plainIc50);
409
+ });
410
+
411
+ test('isFit narrowing', async () => {
412
+ // a runtime-dispatched fit function yields a plain Fit; isFit narrows it to the concrete type
413
+ const fit = getSeriesFit(sigmoidSeries, getSeriesFitFunction(sigmoidSeries));
414
+ expect(isFit(fit, 'sigmoid'));
415
+ expect(isFit(fit, 'linear') === false);
416
+ if (isFit(fit, 'sigmoid'))
417
+ expect(fit.ic50, getStatistic(fit, 'interceptX'));
418
+ });
419
+
170
420
  test('calculateBoxPlotStatistics', async () => {
171
421
  const values = [0.7654603719711304, 0.8199243545532227, 0.8257747292518616, 0.9558155536651611, 0.9596694707870483];
172
422
  const boxPlotStats = calculateBoxPlotStatistics(values);
@@ -178,6 +428,52 @@ category('fit', () => {
178
428
  expect(boxPlotStats.upperAdjacentValue, 0.9558155536651611);
179
429
  });
180
430
 
431
+ test('ICxx is the x at that fraction of the curve', async () => {
432
+ // travelled fraction, measured from the low-x asymptote - so the same call means IC90 on a
433
+ // descending curve and EC90 on an ascending one
434
+ const at = (fitFunc: keyof FitTypeMap, params: number[], fraction: number,
435
+ lowX: number, highX: number): number => {
436
+ const f = getFitFunction(fitFunc)!;
437
+ const array = Float32Array.from(params);
438
+ const start = f.y(array, lowX);
439
+ const end = f.y(array, highX);
440
+ return (f.y(array, f.inverse(array, fraction)!) - start) / (end - start);
441
+ };
442
+
443
+ for (const fitFunc of ['sigmoid', '4pl-dose-response'] as (keyof FitTypeMap)[]) {
444
+ for (const slope of [1.2, -1.2]) {
445
+ for (const fraction of [0.1, 0.5, 0.9]) {
446
+ expectFloat(at(fitFunc, [100, slope, -6.5, 5], fraction, -1e6, 1e6), fraction, 0.001,
447
+ `${fitFunc}, slope ${slope}, IC${fraction * 100}`);
448
+ }
449
+ }
450
+ }
451
+ // the power parameterization, where x is a concentration rather than its logarithm
452
+ for (const slope of [1.2, -1.2]) {
453
+ for (const fraction of [0.1, 0.5, 0.9])
454
+ expectFloat(at('4pl-regression', [100, slope, 3e-7, 5], fraction, 1e-30, 1e30), fraction, 0.001);
455
+ }
456
+
457
+ // IC50 is the inflection point, which is what the droplines drew before there was a family
458
+ const sigmoidFunc = getFitFunction('sigmoid')!;
459
+ expect(sigmoidFunc.inverse(Float32Array.from([100, 1.2, -6.5, 5]), 0.5), -6.5);
460
+
461
+ // nothing to travel between, so nothing to name
462
+ for (const fitFunc of ['linear', 'log-linear', 'exponential'] as (keyof FitTypeMap)[])
463
+ expect(getFitFunction(fitFunc)!.inverse(Float32Array.from([1, 2]), 0.9) === undefined, true, fitFunc);
464
+ });
465
+
466
+ test('a dropline name asks for a fraction', async () => {
467
+ expect(droplineFraction('IC50'), 0.5);
468
+ expect(droplineFraction('IC90'), 0.9);
469
+ expect(droplineFraction('EC50'), 0.5);
470
+ expect(droplineFraction('ic55'), 0.55);
471
+ expect(droplineFraction('IC12.5'), 0.125);
472
+ // the asymptotes themselves are never reached, and these are not concentrations at all
473
+ for (const name of ['IC0', 'IC100', 'AUC', ''])
474
+ expect(droplineFraction(name) === undefined, true, name);
475
+ });
476
+
181
477
  test('sigmoid', async () => {
182
478
  const parameters = [2.612687371569039, -1.421800778574126, 5.16688669906018, 0.341788492203575];
183
479
  const params = new Float32Array(4);
@@ -213,4 +509,15 @@ category('fit', () => {
213
509
  expect(exponential(params, 0.5), 0.2957925783034655);
214
510
  expect(exponential(params, 0.98746), 0.0010630898492656174);
215
511
  });
512
+
513
+ test('the combined error model fits to fixed values', async () => {
514
+ // noisy on purpose: a perfect fit leaves no residuals for the error model to weigh
515
+ const series = {fitFunction: 'sigmoid', errorModel: 'combined',
516
+ points: [1e-9, 3e-9, 1e-8, 3e-8, 1e-7, 3e-7, 1e-6, 3e-6, 1e-5, 3e-5, 1e-4]
517
+ .map((x, i) => ({x: x, y: (5 + 95 / (1 + Math.pow(10, Math.log10(x) + 6.5))) * (1 + 0.08 * Math.sin(i * 2.4))}))};
518
+ const logOptions = {logX: true, logY: false};
519
+ const fit = fitSeries(series as any, getSeriesFitFunction(series as any), undefined, logOptions);
520
+ expectArray(Array.from(fit.parameters).map((p) => Number(p.toFixed(6))),
521
+ [100.771515, 0.984725, -6.517356, 5.065719]);
522
+ });
216
523
  });