@datagrok/curves 1.12.2 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/CLAUDE.md +118 -15
  3. package/README.md +51 -4
  4. package/dist/package-test.js +8819 -5223
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3014 -1659
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +2 -2
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/data-to-curves.ts +11 -6
  12. package/src/fit/fit-chart-data.ts +330 -0
  13. package/src/fit/fit-grid-cell-handler.ts +102 -235
  14. package/src/fit/fit-inspection.ts +3 -3
  15. package/src/fit/fit-interaction.ts +181 -0
  16. package/src/fit/fit-layout.ts +64 -0
  17. package/src/fit/fit-legend.ts +292 -0
  18. package/src/fit/fit-options.ts +222 -0
  19. package/src/fit/fit-parser.ts +16 -5
  20. package/src/fit/fit-renderer.ts +180 -469
  21. package/src/fit/fit-statistics.ts +154 -0
  22. package/src/fit/multi-curve-viewer.ts +48 -22
  23. package/src/fit/render-utils.ts +208 -150
  24. package/src/package-api.ts +78 -0
  25. package/src/package-test.ts +7 -0
  26. package/src/package.g.ts +59 -11
  27. package/src/package.ts +97 -18
  28. package/src/tests/calculated-columns-tests.ts +299 -0
  29. package/src/tests/converter-tests.ts +23 -0
  30. package/src/tests/curve-data.ts +82 -0
  31. package/src/tests/fit-cache-tests.ts +128 -0
  32. package/src/tests/fit-tests.ts +344 -4
  33. package/src/tests/legend-tests.ts +243 -0
  34. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  35. package/src/tests/panel-renderer-tests.ts +502 -0
  36. package/src/tests/project-tests.ts +99 -0
  37. package/src/tests/statistics-tests.ts +127 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +410 -109
  40. package/test-record-1.mp4 +0 -0
package/src/package.g.ts CHANGED
@@ -45,13 +45,13 @@ export async function _initCurves() : Promise<void> {
45
45
  //name: Fit Dose-Response Curves
46
46
  //description: Group well-level assay data by compound, assay, target, and run, then fit a dose-response curve per group.
47
47
  //input: dataframe df
48
- //input: column concentrationCol { description: Concentration (dose) column }
49
- //input: column readoutCol { description: Readout (response) column }
50
- //input: column batchIDCol { description: Batch identifier column }
51
- //input: column assayCol { description: Assay name column }
52
- //input: column runIDCol { description: Run identifier column }
53
- //input: column compoundIDCol { description: Compound identifier column }
54
- //input: column targetEntityCol { description: Target entity column }
48
+ //input: column concentrationCol { type: numerical; nullable: false; description: Concentration (dose) column }
49
+ //input: column readoutCol { type: numerical; nullable: false; description: Readout (response) column }
50
+ //input: column batchIDCol { type: categorical; nullable: false; description: Batch identifier column }
51
+ //input: column assayCol { type: categorical; nullable: false; description: Assay name column }
52
+ //input: column runIDCol { type: categorical; nullable: false; description: Run identifier column }
53
+ //input: column compoundIDCol { type: categorical; nullable: false; description: Compound identifier column }
54
+ //input: column targetEntityCol { type: categorical; nullable: false; description: Target entity column }
55
55
  //input: column excludeOutliersCol { nullable: true; description: Boolean column marking points to exclude as outliers }
56
56
  //input: dataframe parentTable { nullable: true }
57
57
  //input: list<string> fitParamColumns { nullable: true }
@@ -74,12 +74,34 @@ export async function dataToCurvesTopMenu() {
74
74
  return await PackageFunctions.dataToCurvesTopMenu();
75
75
  }
76
76
 
77
+ //description: Extract a fit statistic (e.g. IC50, AUC, R²) from a curve series into a calculated column.
78
+ //input: dataframe table
79
+ //input: column curveColumn { semType: fit; nullable: false; description: Curve column to read }
80
+ //input: string propName { nullable: false; description: Fit statistic to extract (e.g. ic50, auc, rSquared) }
81
+ //input: int seriesNumber { nullable: false; description: Zero-based index of the curve series }
82
+ //output: column result { action: join(table) }
83
+ //meta.vectorFunc: true
84
+ export function curveStatistic(table: DG.DataFrame, curveColumn: DG.Column, propName: string, seriesNumber: number) : any {
85
+ return PackageFunctions.curveStatistic(table, curveColumn, propName, seriesNumber);
86
+ }
87
+
88
+ //description: Aggregate a fit statistic across all series of a curve into a calculated column.
89
+ //input: dataframe table
90
+ //input: column curveColumn { semType: fit; nullable: false; description: Curve column to read }
91
+ //input: string propName { nullable: false; description: Fit statistic to aggregate }
92
+ //input: string aggrType = 'med' { choices: ["avg","med","min","max","q1","q2","q3"]; nullable: false; description: Aggregation applied across the series of each curve }
93
+ //output: column result { action: join(table) }
94
+ //meta.vectorFunc: true
95
+ export function curveAggrStatistic(table: DG.DataFrame, curveColumn: DG.Column, propName: string, aggrType: string) : any {
96
+ return PackageFunctions.curveAggrStatistic(table, curveColumn, propName, aggrType);
97
+ }
98
+
77
99
  //name: Add Curve Statistic Column
78
100
  //description: Extract a fit statistic (e.g. IC50, AUC, R²) from a specific curve series into a new column.
79
101
  //input: dataframe table
80
102
  //input: string colName { description: Name of the curve column to read }
81
- //input: string propName { description: Fit statistic to extract (e.g. IC50, AUC, R²) }
82
- //input: int seriesNumber { description: Zero-based index of the curve series }
103
+ //input: string propName = 'interceptX' { choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]; description: Fit statistic to extract. interceptX is IC50, top and bottom are max/min Y }
104
+ //input: int seriesNumber = 0 { description: Zero-based index of the curve series }
83
105
  //output: column result
84
106
  //meta.vectorFunc: true
85
107
  //meta.role: transform
@@ -91,8 +113,8 @@ export function addStatisticsColumn(table: DG.DataFrame, colName: string, propNa
91
113
  //description: Aggregate a fit statistic across all series of a curve into a new column.
92
114
  //input: dataframe table
93
115
  //input: string colName { description: Name of the curve column to read }
94
- //input: string propName { description: Fit statistic to aggregate (e.g. IC50, AUC, R²) }
95
- //input: string aggrType { description: Aggregation type applied across series (e.g. avg, min, max) }
116
+ //input: string propName = 'interceptX' { choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]; description: Fit statistic to aggregate. interceptX is IC50, top and bottom are max/min Y }
117
+ //input: string aggrType = 'med' { choices: ["min","max","avg","med","q1","q2","q3"]; description: Aggregation applied across the series of each curve }
96
118
  //output: column result
97
119
  //meta.vectorFunc: true
98
120
  //meta.role: transform
@@ -100,6 +122,32 @@ export function addAggrStatisticsColumn(table: DG.DataFrame, colName: string, pr
100
122
  return PackageFunctions.addAggrStatisticsColumn(table, colName, propName, aggrType);
101
123
  }
102
124
 
125
+ //name: Add Curve Statistic
126
+ //description: Extracts a fit statistic from one series of a curve column into a new column.
127
+ //input: dataframe table { caption: Table; nullable: false }
128
+ //input: column curvesCol { semType: fit; caption: Curves; nullable: false; description: Column of fitted curves }
129
+ //input: string statistic = 'interceptX' { caption: Statistic; nullable: false; choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]; description: interceptX is IC50, top and bottom are max/min Y }
130
+ //input: int seriesNumber = 0 { caption: Series; nullable: false; description: Zero-based index of the curve series }
131
+ //output: column result
132
+ //meta.vectorFunc: true
133
+ //meta.role: transform
134
+ export function addCurveStatistic(table: DG.DataFrame, curvesCol: DG.Column, statistic: string, seriesNumber: number) : any {
135
+ return PackageFunctions.addCurveStatistic(table, curvesCol, statistic, seriesNumber);
136
+ }
137
+
138
+ //name: Add Aggregated Curve Statistic
139
+ //description: Aggregates a fit statistic across all series of a curve column into a new column.
140
+ //input: dataframe table { caption: Table; nullable: false }
141
+ //input: column curvesCol { semType: fit; caption: Curves; nullable: false; description: Column of fitted curves }
142
+ //input: string statistic = 'interceptX' { caption: Statistic; nullable: false; choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]; description: interceptX is IC50, top and bottom are max/min Y }
143
+ //input: string aggregation = 'med' { caption: Aggregation; nullable: false; choices: ["med","avg","min","max","q1","q2","q3"]; description: Applied across the series of each curve }
144
+ //output: column result
145
+ //meta.vectorFunc: true
146
+ //meta.role: transform
147
+ export function addAggrCurveStatistic(table: DG.DataFrame, curvesCol: DG.Column, statistic: string, aggregation: string) : any {
148
+ return PackageFunctions.addAggrCurveStatistic(table, curvesCol, statistic, aggregation);
149
+ }
150
+
103
151
  //description: Returns XML 3DX curve converter function
104
152
  //output: dynamic result
105
153
  //meta.role: curveConverter
package/src/package.ts CHANGED
@@ -7,15 +7,16 @@ import * as DG from 'datagrok-api/dg';
7
7
  import * as grok from 'datagrok-api/grok';
8
8
  import * as ui from 'datagrok-api/ui';
9
9
 
10
- import {FitGridCellHandler, calculateSeriesStats, getChartDataAggrStats} from './fit/fit-grid-cell-handler';
11
- import {getOrCreateParsedChartData, substituteZeroes} from './fit/fit-renderer';
10
+ import {FitGridCellHandler} from './fit/fit-grid-cell-handler';
11
+ import {calculateSeriesFit, getChartDataAggrStats, curveStatisticAt, curveAggrStatisticAt} from './fit/fit-statistics';
12
+ import {getOrCreateParsedChartData, substituteZeroes} from './fit/fit-chart-data';
12
13
  import {assayCurvesDemo, curveDemo} from './fit/fit-demo';
13
14
  import {convertXmlCurveToJson} from './fit/converters/xml-converter';
14
15
  import {convertCompactDrToJson} from './fit/converters/compact-dr-converter';
15
16
  import {convertPzfxToJson} from './fit/converters/pzfx-converter';
16
17
  import {registerCurveConverter, initExternalConverters} from './fit/curve-converter';
17
- import {LogOptions} from '@datagrok-libraries/statistics/src/fit/fit-data';
18
- import {FitStatistics} from '@datagrok-libraries/statistics/src/fit/fit-curve';
18
+ import {FitStatistics, LogOptions} from '@datagrok-libraries/statistics/src/fit/fit-curve';
19
+ import {getStatistic} from '@datagrok-libraries/statistics/src/fit/fit-engine';
19
20
 
20
21
  // import {PlateWidget} from './plate/plate-widget';
21
22
 
@@ -87,14 +88,22 @@ export class PackageFunctions {
87
88
  description: 'Group well-level assay data by compound, assay, target, and run, then fit a dose-response curve per group.',
88
89
  })
89
90
  static async dataToCurves(df: DG.DataFrame,
90
- @grok.decorators.param({options: {description: 'Concentration (dose) column'}}) concentrationCol: DG.Column,
91
- @grok.decorators.param({options: {description: 'Readout (response) column'}}) readoutCol: DG.Column,
92
- @grok.decorators.param({options: {description: 'Batch identifier column'}}) batchIDCol: DG.Column,
93
- @grok.decorators.param({options: {description: 'Assay name column'}}) assayCol: DG.Column,
94
- @grok.decorators.param({options: {description: 'Run identifier column'}}) runIDCol: DG.Column,
95
- @grok.decorators.param({options: {description: 'Compound identifier column'}}) compoundIDCol: DG.Column,
96
- @grok.decorators.param({options: {description: 'Target entity column'}}) targetEntityCol: DG.Column,
97
- @grok.decorators.param({options: {nullable: true, description: 'Boolean column marking points to exclude as outliers'}})excludeOutliersCol?: DG.Column,
91
+ /* The declared `type` must stay `column`: an `options.type` on its own
92
+ * becomes the parameter's OWN type in the generated annotation, turning the
93
+ * column slot into a plain numerical/categorical value. (And never spell an
94
+ * `input:` annotation out inside a comment — the server scans package.ts for
95
+ * those lines and would try to parse it as a real parameter.) */
96
+ // All seven are dereferenced unconditionally, so they are `nullable: false`
97
+ // — a column parameter defaults to nullable, which read as "optional" and
98
+ // let a half-configured node run.
99
+ @grok.decorators.param({type: 'column', options: {type: 'numerical', nullable: false, description: 'Concentration (dose) column'}}) concentrationCol: DG.Column,
100
+ @grok.decorators.param({type: 'column', options: {type: 'numerical', nullable: false, description: 'Readout (response) column'}}) readoutCol: DG.Column,
101
+ @grok.decorators.param({type: 'column', options: {type: 'categorical', nullable: false, description: 'Batch identifier column'}}) batchIDCol: DG.Column,
102
+ @grok.decorators.param({type: 'column', options: {type: 'categorical', nullable: false, description: 'Assay name column'}}) assayCol: DG.Column,
103
+ @grok.decorators.param({type: 'column', options: {type: 'categorical', nullable: false, description: 'Run identifier column'}}) runIDCol: DG.Column,
104
+ @grok.decorators.param({type: 'column', options: {type: 'categorical', nullable: false, description: 'Compound identifier column'}}) compoundIDCol: DG.Column,
105
+ @grok.decorators.param({type: 'column', options: {type: 'categorical', nullable: false, description: 'Target entity column'}}) targetEntityCol: DG.Column,
106
+ @grok.decorators.param({type: 'column', options: {nullable: true, description: 'Boolean column marking points to exclude as outliers'}})excludeOutliersCol?: DG.Column,
98
107
  // rest is parent level data
99
108
  @grok.decorators.param({options: {nullable: true}})parentTable?: DG.DataFrame, // these inputs need to be string and resolved here bellow, because this function is used in datasync, otherwise context is lost
100
109
  @grok.decorators.param({options: {nullable: true}})fitParamColumns?: string[],
@@ -131,6 +140,38 @@ export class PackageFunctions {
131
140
  dataToCurvesUI();
132
141
  }
133
142
 
143
+ @grok.decorators.func({
144
+ name: 'curveStatistic',
145
+ description: 'Extract a fit statistic (e.g. IC50, AUC, R²) from a curve series into a calculated column.',
146
+ meta: {vectorFunc: 'true'},
147
+ outputs: [{name: 'result', type: 'column', options: {action: 'join(table)'}}],
148
+ })
149
+ static curveStatistic(table: DG.DataFrame,
150
+ @grok.decorators.param({type: 'column', options: {semType: 'fit', nullable: false, description: 'Curve column to read'}}) curveColumn: DG.Column,
151
+ @grok.decorators.param({options: {nullable: false, description: 'Fit statistic to extract (e.g. ic50, auc, rSquared)'}}) propName: string,
152
+ @grok.decorators.param({type: 'int', options: {nullable: false, description: 'Zero-based index of the curve series'}}) seriesNumber: number): DG.Column {
153
+ // stable name: recalculation matches the result back by name, and AddNewColumn makes it unique on insert
154
+ const result = DG.Column.float(`${curveColumn.name} ${seriesNumber + 1} ${propName}`, curveColumn.length);
155
+ result.init((i) => curveStatisticAt(curveColumn, i, propName, seriesNumber, table));
156
+ return result;
157
+ }
158
+
159
+ @grok.decorators.func({
160
+ name: 'curveAggrStatistic',
161
+ description: 'Aggregate a fit statistic across all series of a curve into a calculated column.',
162
+ meta: {vectorFunc: 'true'},
163
+ outputs: [{name: 'result', type: 'column', options: {action: 'join(table)'}}],
164
+ })
165
+ static curveAggrStatistic(table: DG.DataFrame,
166
+ @grok.decorators.param({type: 'column', options: {semType: 'fit', nullable: false, description: 'Curve column to read'}}) curveColumn: DG.Column,
167
+ @grok.decorators.param({options: {nullable: false, description: 'Fit statistic to aggregate'}}) propName: string,
168
+ @grok.decorators.param({options: {choices: ['avg', 'med', 'min', 'max', 'q1', 'q2', 'q3'], initialValue: 'med', nullable: false, description: 'Aggregation applied across the series of each curve'}}) aggrType: string): DG.Column {
169
+ // stable name: recalculation matches the result back by name, and AddNewColumn makes it unique on insert
170
+ const result = DG.Column.float(`${curveColumn.name} ${aggrType} ${propName}`, curveColumn.length);
171
+ result.init((i) => curveAggrStatisticAt(curveColumn, i, propName, aggrType, table));
172
+ return result;
173
+ }
174
+
134
175
  @grok.decorators.func({
135
176
  name: 'Add Curve Statistic Column',
136
177
  description: 'Extract a fit statistic (e.g. IC50, AUC, R²) from a specific curve series into a new column.',
@@ -138,8 +179,10 @@ export class PackageFunctions {
138
179
  })
139
180
  static addStatisticsColumn(table: DG.DataFrame,
140
181
  @grok.decorators.param({options: {description: 'Name of the curve column to read'}}) colName: string,
141
- @grok.decorators.param({options: {description: 'Fit statistic to extract (e.g. IC50, AUC, R²)'}}) propName: string,
142
- @grok.decorators.param({type: 'int', options: {description: 'Zero-based index of the curve series'}}) seriesNumber: number): DG.Column {
182
+ // Literal strings, not `statisticsProperties.map(...)` — the func generator
183
+ // only reads literal arrays and emits nothing for a computed one.
184
+ @grok.decorators.param({options: {choices: ['rSquared', 'auc', 'interceptX', 'interceptY', 'slope', 'top', 'bottom'], initialValue: 'interceptX', description: 'Fit statistic to extract. interceptX is IC50, top and bottom are max/min Y'}}) propName: string,
185
+ @grok.decorators.param({type: 'int', options: {initialValue: '0', description: 'Zero-based index of the curve series'}}) seriesNumber: number): DG.Column {
143
186
  const df = table;
144
187
  const col = df.col(colName)!;
145
188
  const sourceColName = col.name;
@@ -165,8 +208,9 @@ export class PackageFunctions {
165
208
  chartData.series?.some((series) => series.points.some((p) => p.x === 0)))
166
209
  substituteZeroes(chartData);
167
210
  const chartLogOptions: LogOptions = {logX: chartData.chartOptions?.logX, logY: chartData.chartOptions?.logY};
168
- const fitResult = calculateSeriesStats(chartData.series![seriesNumber], seriesNumber, chartLogOptions, cell, true);
169
- return fitResult[propName as keyof FitStatistics];
211
+ // resolve by name so both current statistic names and legacy ones from saved projects work
212
+ const fitResult = calculateSeriesFit(chartData.series![seriesNumber], seriesNumber, chartLogOptions, cell, true);
213
+ return getStatistic(fitResult, propName) ?? null;
170
214
  });
171
215
 
172
216
  df.columns.insert(column, df.columns.names().indexOf(colName) + 1);
@@ -180,8 +224,8 @@ export class PackageFunctions {
180
224
  })
181
225
  static addAggrStatisticsColumn(table: DG.DataFrame,
182
226
  @grok.decorators.param({options: {description: 'Name of the curve column to read'}}) colName: string,
183
- @grok.decorators.param({options: {description: 'Fit statistic to aggregate (e.g. IC50, AUC, R²)'}}) propName: string,
184
- @grok.decorators.param({options: {description: 'Aggregation type applied across series (e.g. avg, min, max)'}}) aggrType: string): DG.Column {
227
+ @grok.decorators.param({options: {choices: ['rSquared', 'auc', 'interceptX', 'interceptY', 'slope', 'top', 'bottom'], initialValue: 'interceptX', description: 'Fit statistic to aggregate. interceptX is IC50, top and bottom are max/min Y'}}) propName: string,
228
+ @grok.decorators.param({options: {choices: ['min', 'max', 'avg', 'med', 'q1', 'q2', 'q3'], initialValue: 'med', description: 'Aggregation applied across the series of each curve'}}) aggrType: string): DG.Column {
185
229
  const df = table;
186
230
  const col = df.col(colName)!;
187
231
  const nName = `${colName} ${aggrType} ${propName}`;
@@ -208,6 +252,41 @@ export class PackageFunctions {
208
252
  return column;
209
253
  }
210
254
 
255
+ /* The two functions above address the curve column by NAME, because their
256
+ * `colName` string is what the "+" buttons in the Fit pane and the Data to
257
+ * Curves pipeline pass, and both are recorded as `role: transform` steps that
258
+ * must keep replaying. On a pipeline canvas a name string means no column
259
+ * picker and no `fit` filter, so these twins take a real column slot and
260
+ * delegate to the same implementation. */
261
+
262
+ @grok.decorators.func({
263
+ name: 'Add Curve Statistic',
264
+ description: 'Extracts a fit statistic from one series of a curve column into a new column.',
265
+ outputs: [{name: 'result', type: 'column'}],
266
+ meta: {vectorFunc: 'true', role: 'transform'},
267
+ })
268
+ static addCurveStatistic(
269
+ @grok.decorators.param({options: {caption: 'Table', nullable: false}}) table: DG.DataFrame,
270
+ @grok.decorators.param({type: 'column', options: {semType: 'fit', caption: 'Curves', nullable: false, description: 'Column of fitted curves'}}) curvesCol: DG.Column,
271
+ @grok.decorators.param({type: 'string', options: {caption: 'Statistic', nullable: false, choices: ['rSquared', 'auc', 'interceptX', 'interceptY', 'slope', 'top', 'bottom'], initialValue: 'interceptX', description: 'interceptX is IC50, top and bottom are max/min Y'}}) statistic: string = 'interceptX',
272
+ @grok.decorators.param({type: 'int', options: {caption: 'Series', nullable: false, initialValue: '0', description: 'Zero-based index of the curve series'}}) seriesNumber: number = 0): DG.Column {
273
+ return PackageFunctions.addStatisticsColumn(table, curvesCol.name, statistic, seriesNumber);
274
+ }
275
+
276
+ @grok.decorators.func({
277
+ name: 'Add Aggregated Curve Statistic',
278
+ description: 'Aggregates a fit statistic across all series of a curve column into a new column.',
279
+ outputs: [{name: 'result', type: 'column'}],
280
+ meta: {vectorFunc: 'true', role: 'transform'},
281
+ })
282
+ static addAggrCurveStatistic(
283
+ @grok.decorators.param({options: {caption: 'Table', nullable: false}}) table: DG.DataFrame,
284
+ @grok.decorators.param({type: 'column', options: {semType: 'fit', caption: 'Curves', nullable: false, description: 'Column of fitted curves'}}) curvesCol: DG.Column,
285
+ @grok.decorators.param({type: 'string', options: {caption: 'Statistic', nullable: false, choices: ['rSquared', 'auc', 'interceptX', 'interceptY', 'slope', 'top', 'bottom'], initialValue: 'interceptX', description: 'interceptX is IC50, top and bottom are max/min Y'}}) statistic: string = 'interceptX',
286
+ @grok.decorators.param({type: 'string', options: {caption: 'Aggregation', nullable: false, choices: ['med', 'avg', 'min', 'max', 'q1', 'q2', 'q3'], initialValue: 'med', description: 'Applied across the series of each curve'}}) aggregation: string = 'med'): DG.Column {
287
+ return PackageFunctions.addAggrStatisticsColumn(table, curvesCol.name, statistic, aggregation);
288
+ }
289
+
211
290
  @grok.decorators.func({description: 'Returns XML 3DX curve converter function', meta: {role: 'curveConverter', curveFormat: '3dx'}})
212
291
  static convertXmlCurveToJsonFunc(): (value: string) => string {
213
292
  return convertXmlCurveToJson;
@@ -0,0 +1,299 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ import {category, test, expect, expectArray, expectFloat, awaitCheck} 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 {getStatistic} from '@datagrok-libraries/statistics/src/fit/fit-engine';
8
+ import {getChartDataAggrStats, aggregatedStatisticsProperties, calculateSeriesFit, curveStatisticAt} from '../fit/fit-statistics';
9
+ import {setOutlier} from '../fit/fit-interaction';
10
+ import {getOrCreateParsedChartData} from '../fit/fit-chart-data';
11
+ import {CONCENTRATIONS, curveJson, multiSeriesCurveJson} from './curve-data';
12
+ import {addStatisticColumn as addStatisticColumnFromPanel} from '../fit/fit-grid-cell-handler';
13
+
14
+ /** Same curve, but with logX left to the column level rather than baked into the cell. */
15
+ function curveJsonNoChartOptions(logIC50: number): string {
16
+ const parsed = JSON.parse(curveJson(logIC50));
17
+ delete parsed.chartOptions;
18
+ return JSON.stringify(parsed);
19
+ }
20
+
21
+ function curveTable(name: string, logIC50s: number[]): DG.DataFrame {
22
+ const col = DG.Column.fromStrings('curve', logIC50s.map(curveJson));
23
+ col.semType = FitConstants.FIT_SEM_TYPE;
24
+ const df = DG.DataFrame.fromColumns([col]);
25
+ df.name = name;
26
+ return df;
27
+ }
28
+
29
+ /** Runs a curve statistic function the way the property panel's "+" button does. */
30
+ async function addStatisticColumn(df: DG.DataFrame, funcName: string,
31
+ params: {[key: string]: string | number}): Promise<void> {
32
+ await DG.Func.find({name: funcName})[0]
33
+ .prepare({table: df, curveColumn: df.col('curve')!, ...params})
34
+ .call(false, undefined, {processed: false});
35
+ }
36
+
37
+ /** Grid column names in grid order; index 0 is the row header, which has no name. */
38
+ function gridColumnNames(grid: DG.Grid): string[] {
39
+ const names: string[] = [];
40
+ for (let i = 0; i < grid.columns.length; i++) {
41
+ const name = grid.columns.byIndex(i)?.name;
42
+ if (name)
43
+ names.push(name);
44
+ }
45
+ return names;
46
+ }
47
+
48
+ category('calculated columns', () => {
49
+ test('the statistic column is added right after the curve column', async () => {
50
+ // `join(table)` appends, so the position the legacy addStatisticsColumn inserted at is restored
51
+ const df = curveTable('calcColPosition', [-6.5]);
52
+ df.columns.addNewString('trailing').set(0, 'x');
53
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
54
+
55
+ await addStatisticColumnFromPanel(gridCell, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
56
+
57
+ expectArray(df.columns.names(), ['curve', 'curve 1 ic50', 'trailing']);
58
+ // the grid only takes a position from the dataframe when it first builds a GridColumn
59
+ expectArray(gridColumnNames(gridCell.grid), ['curve', 'curve 1 ic50', 'trailing']);
60
+ });
61
+
62
+ test('placing the statistic column keeps a manually reordered grid', async () => {
63
+ // a dragged grid is no longer in dataframe order, and must not be snapped back to it
64
+ const df = curveTable('calcColGridOrder', [-6.5]);
65
+ df.columns.addNewString('a').set(0, 'x');
66
+ df.columns.addNewString('b').set(0, 'y');
67
+ const grid = DG.Viewer.grid(df);
68
+ grid.columns.setOrder(['b', 'curve', 'a']);
69
+
70
+ await addStatisticColumnFromPanel(grid.cell('curve', 0), 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
71
+
72
+ expectArray(gridColumnNames(grid), ['b', 'curve', 'curve 1 ic50', 'a']);
73
+ expectArray(df.columns.names(), ['curve', 'curve 1 ic50', 'a', 'b']);
74
+ });
75
+
76
+ test('plot-level labels combine across levels instead of the nearest one winning', async () => {
77
+ // labels are data rather than a setting: an assay name on the column and a plate statistic on the
78
+ // cell both belong on the plot, which a whole-property merge would not allow
79
+ const cell = JSON.stringify({
80
+ chartOptions: {logX: true, labels: {'Z prime': 0.72}},
81
+ series: [{fitFunction: 'sigmoid', name: 's', points: CONCENTRATIONS.map((x) => ({x: x, y: x}))}],
82
+ });
83
+ const col = DG.Column.fromStrings('curve', [cell]);
84
+ col.semType = FitConstants.FIT_SEM_TYPE;
85
+ const df = DG.DataFrame.fromColumns([col]);
86
+ df.name = 'calcColLabels';
87
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {labels: {'assay': 'GPCR', 'Z prime': 0.1}}}));
88
+
89
+ const labels = getOrCreateParsedChartData(df.cell(0, 'curve')).chartOptions!.labels!;
90
+ expect(labels['assay'], 'GPCR', 'the column-level label did not reach the plot');
91
+ expectFloat(labels['Z prime'] as number, 0.72, 0.001);
92
+ });
93
+
94
+ test('curveStatistic adds a calculated column', async () => {
95
+ const df = curveTable('calcColAdd', [-6.5, -6.5]);
96
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
97
+
98
+ const col = df.col('curve 1 ic50');
99
+ expect(col !== null);
100
+ expect(col!.type, DG.COLUMN_TYPE.FLOAT);
101
+ // the statistic must come back in data space, not as the log-space fitted parameter
102
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
103
+
104
+ // the platform owns the formula, and binds the curve column as a column rather than a per-row value
105
+ expect(col!.getTag(DG.TAGS.FORMULA).includes('Curves:curveStatistic'));
106
+ expect(col!.getTag(DG.TAGS.FORMULA).includes('${curve}'));
107
+ expect(col!.getTag('.%formula-column-is-vector-func'), 'true');
108
+ });
109
+
110
+ test('recalculates when the source curve changes', async () => {
111
+ const df = curveTable('calcColRecalc', [-6.5, -6.5]);
112
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
113
+ const before = df.col('curve 1 ic50')!.get(1);
114
+
115
+ // an unstable result name, or reading through column.dataFrame, leaves this silently stale
116
+ df.col('curve')!.set(1, curveJson(-5.0), true);
117
+ await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
118
+ 'statistic column did not recalculate after the source curve changed', 5000);
119
+
120
+ expectFloat(Math.log10(df.col('curve 1 ic50')!.get(1)), -5.0, 0.3);
121
+ expect(df.col('curve 1 ic50')!.get(0), before, 'untouched row must not be recalculated');
122
+ });
123
+
124
+ test('legacy statistic names still resolve', async () => {
125
+ const df = curveTable('calcColLegacy', [-6.5]);
126
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'interceptX', seriesNumber: 0});
127
+
128
+ // interceptX is the pre-refactor name for the sigmoid inflection point
129
+ const col = df.col('curve 1 interceptX');
130
+ expect(col !== null);
131
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
132
+ });
133
+
134
+ test('curveAggrStatistic aggregates across series', async () => {
135
+ const df = curveTable('calcColAggr', [-6.5, -5.5]);
136
+ await addStatisticColumn(df, 'curveAggrStatistic', {propName: 'ic50', aggrType: 'med'});
137
+
138
+ const col = df.col('curve med ic50');
139
+ expect(col !== null);
140
+ // single-series cells, so the median across series is that series' own IC50
141
+ expectFloat(Math.log10(col!.get(0)), -6.5, 0.15);
142
+ expectFloat(Math.log10(col!.get(1)), -5.5, 0.15);
143
+ });
144
+
145
+ test('averaging IC50 across series is a geometric mean', async () => {
146
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
147
+
148
+ // aggregated in log space, so 1e-7 and 1e-5 give 1e-6; per-series conversion would give 5.05e-6
149
+ expectFloat(Math.log10(getChartDataAggrStats(data, 'avg').ic50!), -6, 0.1);
150
+ });
151
+
152
+ test('mixed fit functions only aggregate statistics common to all series', async () => {
153
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
154
+ data.series![1].fitFunction = 'linear';
155
+
156
+ // ic50 belongs to the sigmoid only; rSquared is produced by both
157
+ const names = aggregatedStatisticsProperties(data).map((p) => p.name);
158
+ expect(names.includes('ic50'), false, 'ic50 is not viable across a sigmoid and a linear fit');
159
+ expect(names.includes('rSquared'), true);
160
+ expect(getChartDataAggrStats(data, 'avg').ic50 === undefined, true, 'ic50 must not be aggregated over a subset');
161
+ });
162
+
163
+ test('repeated calculation does not re-log stored parameters', async () => {
164
+ // an IC50 above 1 stays positive after one log, so an in-place conversion drifts: 100 -> 2 -> 0.301
165
+ const series = JSON.parse(curveJson(-6.5)).series[0];
166
+ series.parameters = [100, 1, 100, 5];
167
+ const logX = {logX: true, logY: false};
168
+
169
+ const first = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
170
+ const second = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
171
+ expect(first, second, 'stored parameters drifted between calls');
172
+ expectFloat(first!, 100, 1);
173
+ });
174
+
175
+ test('fitting a series does not write fit-space parameters back onto it', async () => {
176
+ // the first call fits; writing the log-space parameters back would make the second log them again
177
+ const data = JSON.parse(multiSeriesCurveJson([2])) as IFitChartData;
178
+ const series = data.series![0];
179
+ const logX = {logX: true, logY: false};
180
+
181
+ const first = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
182
+ expect(series.parameters === undefined, true, 'the series must keep its data-space contract');
183
+ const second = getStatistic(calculateSeriesFit(series, 0, logX, undefined, false), 'ic50');
184
+ expect(first, second, 'the reported IC50 drifted between calls');
185
+ });
186
+
187
+ test('recalculation applies column-level chart options', async () => {
188
+ const col = DG.Column.fromStrings('curve', [curveJsonNoChartOptions(-6.5), curveJsonNoChartOptions(-6.5)]);
189
+ col.semType = FitConstants.FIT_SEM_TYPE;
190
+ col.setTag(FitConstants.TAG_FIT, JSON.stringify({chartOptions: {logX: true}}));
191
+ const df = DG.DataFrame.fromColumns([col]);
192
+ df.name = 'calcColColumnOptions';
193
+ await addStatisticColumn(df, 'curveStatistic', {propName: 'ic50', seriesNumber: 0});
194
+ const before = df.col('curve 1 ic50')!.get(1);
195
+
196
+ df.col('curve')!.set(1, curveJsonNoChartOptions(-5.0), true);
197
+ await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
198
+ 'statistic column did not recalculate', 5000);
199
+
200
+ // the detached recalculation column has no dataframe, so it must read logX off its own tags
201
+ expectFloat(Math.log10(df.col('curve 1 ic50')!.get(1)), -5.0, 0.3);
202
+ });
203
+
204
+ test('log-space statistics are not offered for aggregations we do not convert', async () => {
205
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
206
+
207
+ // pIC50 is only derived during the conversion, so it is the one that cannot be produced
208
+ const counted = aggregatedStatisticsProperties(data, 'count').map((p) => p.name);
209
+ expect(counted.includes('pIC50'), false, 'pIC50 is only derived in data space');
210
+ expect(counted.includes('rSquared'), true, 'space-independent statistics stay');
211
+
212
+ // ic50 stays available and is reported in fit space, which is what a stdev of it should be, and
213
+ // what a saved project recorded before this refactor - it must not come back as a null column
214
+ expect(counted.includes('ic50'), true, 'ic50 must stay available for aggregations we do not convert');
215
+ expectFloat(getChartDataAggrStats(data, 'avg').ic50!, 1e-6, 1e-7);
216
+ expectFloat(getChartDataAggrStats(data, 'count').ic50!, 2, 0.001);
217
+ expectFloat(getChartDataAggrStats(data, 'count').interceptX!, 2, 0.001);
218
+ });
219
+
220
+ test('stored parameters round-trip through fit space on both axes', async () => {
221
+ // seriesInFitSpace and toDataSpace must be inverses, or a top of 100 comes back as 1e100
222
+ for (const logOptions of [{logX: false, logY: false}, {logX: true, logY: false},
223
+ {logX: false, logY: true}, {logX: true, logY: true}]) {
224
+ const series = JSON.parse(curveJson(-6.5)).series[0];
225
+ series.parameters = [100, 1, 1e-6, 5];
226
+ const fit = calculateSeriesFit(series, 0, logOptions, undefined, false);
227
+
228
+ expectFloat(getStatistic(fit, 'top')!, 100, 1e-6, `top under ${JSON.stringify(logOptions)}`);
229
+ expectFloat(getStatistic(fit, 'bottom')!, 5, 1e-6, `bottom under ${JSON.stringify(logOptions)}`);
230
+ expectFloat(getStatistic(fit, 'ic50')!, 1e-6, 1e-12, `ic50 under ${JSON.stringify(logOptions)}`);
231
+ }
232
+ });
233
+
234
+ test('a detached column strips the stray pipe like the initial parse does', async () => {
235
+ // recalculation hands the function a detached column, whose parse must sanitize the value too
236
+ const col = DG.Column.fromStrings('curve', [curveJson(-6.5).replace('{', '{|')]);
237
+ col.semType = FitConstants.FIT_SEM_TYPE;
238
+ expect(col.dataFrame === null || col.dataFrame === undefined, true, 'the column must be detached');
239
+
240
+ const value = curveStatisticAt(col, 0, 'ic50', 0);
241
+ expect(value !== null, true, 'a pipe in the cell value blanked the row');
242
+ expectFloat(Math.log10(value!), -6.5, 0.3);
243
+ });
244
+
245
+ test('a legacy statistic reads the same per series and aggregated', async () => {
246
+ // `top` on a linear fit resolves through the positional fallback, per series and aggregated alike
247
+ const data = JSON.parse(multiSeriesCurveJson([-6.5])) as IFitChartData;
248
+ data.series![0].fitFunction = 'linear';
249
+ const logX = {logX: true, logY: false};
250
+
251
+ const perSeries = getStatistic(calculateSeriesFit(data.series![0], 0, logX, undefined, false), 'top');
252
+ const aggregated = getChartDataAggrStats(data, 'med').top;
253
+ expect(perSeries !== undefined, true, 'the per-series path lost the fallback');
254
+ expect(aggregated !== undefined, true, 'the aggregated path drops a statistic the per-series one reports');
255
+ });
256
+
257
+ test('a legacy name and its canonical field agree after aggregation', async () => {
258
+ // interceptX aliases onto ic50, so collecting it before the conversion leaves it in fit space
259
+ const data = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
260
+ const stats = getChartDataAggrStats(data, 'avg');
261
+
262
+ expect(stats.interceptX, stats.ic50, 'interceptX must be reported in the same space as ic50');
263
+ expectFloat(Math.log10(stats.interceptX!), -6, 0.1);
264
+ });
265
+
266
+ test('mergeSeries does not change a statistic', async () => {
267
+ // it merges on a copy for the plot only, so it cannot change an extracted statistic
268
+ const plain = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
269
+ const merged = JSON.parse(multiSeriesCurveJson([-7, -5])) as IFitChartData;
270
+ merged.chartOptions!.mergeSeries = true;
271
+ const logX = {logX: true, logY: false};
272
+
273
+ for (const i of [0, 1]) {
274
+ const a = getStatistic(calculateSeriesFit(plain.series![i], i, logX, undefined, false), 'ic50');
275
+ const b = getStatistic(calculateSeriesFit(merged.series![i], i, logX, undefined, false), 'ic50');
276
+ expect(a, b, `series ${i} changed when mergeSeries was set`);
277
+ }
278
+ expect(getChartDataAggrStats(merged, 'med').ic50, getChartDataAggrStats(plain, 'med').ic50);
279
+ });
280
+
281
+ test('outlier toggle refreshes statistic columns named by the new API', async () => {
282
+ const df = curveTable('calcColOutlierToggle', [-6.5]);
283
+ const stat = DG.Column.float('ic50 col', df.rowCount);
284
+ // tags the legacy "+" writes; ic50 has no slot in the seven legacy keys
285
+ stat.tags['.sourceColumn'] = 'curve';
286
+ stat.tags['.seriesNumber'] = '0';
287
+ stat.tags['.statistics'] = 'ic50';
288
+ stat.init(() => 1e-6);
289
+ df.columns.add(stat);
290
+
291
+ const gridCell = DG.Viewer.grid(df).cell('curve', 0);
292
+ const data = getOrCreateParsedChartData(gridCell.cell, true);
293
+ setOutlier(gridCell, data.series![0].points[0], 0, 0, data);
294
+
295
+ const value = df.col('ic50 col')!.get(0);
296
+ expect(value != null && !isNaN(value), true, 'outlier toggle blanked the ic50 column');
297
+ expectFloat(Math.log10(value), -6.5, 0.3);
298
+ });
299
+ });
@@ -78,6 +78,29 @@ category('converters', () => {
78
78
  expect(chartData.chartOptions?.logX, true);
79
79
  });
80
80
 
81
+ test('xmlConverter.booleanAttributes', async () => {
82
+ // XML attributes are strings, so `!!getAttribute(...)` read "False" as true - real 3DX exports
83
+ // carry drawLine="False" on most series and would have drawn a fit line anyway
84
+ const off = SAMPLE_XML.replace('drawLine="True"', 'drawLine="False"').replace('logX="true"', 'logX="false"');
85
+ const chartData: IFitChartData = JSON.parse(convertXmlCurveToJson(off));
86
+ expect(chartData.series![0].showFitLine, false);
87
+ expect(chartData.chartOptions?.logX, false);
88
+
89
+ const on: IFitChartData = JSON.parse(convertXmlCurveToJson(SAMPLE_XML));
90
+ expect(on.series![0].showFitLine, true);
91
+ expect(on.chartOptions?.logX, true);
92
+ });
93
+
94
+ test('xmlConverter.logYNotInvented', async () => {
95
+ // an always-present key owns it, and mergeProperties only fills absent ones - so emitting
96
+ // logY: false would stop a Column or Dataframe level option cascading onto the cell
97
+ const chartData: IFitChartData = JSON.parse(convertXmlCurveToJson(SAMPLE_XML));
98
+ expect('logY' in chartData.chartOptions!, false, 'the cell must not own logY when the export omits it');
99
+
100
+ const declared = SAMPLE_XML.replace('logX="true"', 'logX="true" logY="true"');
101
+ expect(JSON.parse(convertXmlCurveToJson(declared)).chartOptions.logY, true);
102
+ });
103
+
81
104
  test('xmlConverter.parameterReordering', async () => {
82
105
  const result = convertXmlCurveToJson(SAMPLE_XML);
83
106
  const chartData: IFitChartData = JSON.parse(result);