@datagrok/curves 1.9.0 → 1.10.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.
@@ -1,220 +1,592 @@
1
1
  /* eslint-disable max-len */
2
2
 
3
- import {FIT_FUNCTION_4PL_REGRESSION, FitChartData, FitMarkerType, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
3
+ import {FIT_FUNCTION_4PL_DOSE_RESPONSE, FIT_FUNCTION_4PL_REGRESSION, FitChartData, FitMarkerType, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
4
4
  import * as DG from 'datagrok-api/dg';
5
5
  import * as grok from 'datagrok-api/grok';
6
6
  import * as ui from 'datagrok-api/ui';
7
+ import * as api from '../package-api';
7
8
  import wu from 'wu';
9
+ import {FitFunctionType, FitFunctionTypes} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
8
10
 
9
- export function dataToCurvesUI() {
10
- const tv = grok.shell.tv;
11
- if (!tv || !tv.dataFrame) {
12
- grok.shell.warning('No open tableview');
13
- return;
11
+ const groupColumnName = 'Compound|Assay|Target';
12
+
13
+ function setColumnDefaultValue(table: DG.DataFrame, input: DG.InputBase<DG.Column | null>, check: (col: DG.Column) => boolean, values: string[]) {
14
+ 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
+ if (col)
16
+ input.value = col;
17
+ }
18
+
19
+ function createFitParamsEditor(table: DG.DataFrame, type: FitFunctionType) {
20
+ const inputs: DG.InputBase<DG.Column | null>[] = [];
21
+ //['Top', 'Slope', 'EC50', 'Bottom'];
22
+ switch (type) {
23
+ case FitFunctionTypes.FOUR_PL_REGRESSION:
24
+ case FitFunctionTypes.FOUR_PL_DOSE_RESPONSE:
25
+ default:
26
+ inputs.push(ui.input.column('Max', {table: table, nullable: false, tooltipText: 'Maximum value for the curve'}));
27
+ inputs.push(ui.input.column('Hill', {table: table, nullable: false, tooltipText: 'Hill coefficient for the curve'}));
28
+ inputs.push(ui.input.column('Inflection', {table: table, nullable: false, tooltipText: 'Inflection value for the curve'}));
29
+ inputs.push(ui.input.column('Min', {table: table, nullable: false, tooltipText: 'Minimum value for the curve'}));
30
+ setColumnDefaultValue(table, inputs[0], (c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['max']);
31
+ setColumnDefaultValue(table, inputs[1], (c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['hill']);
32
+ setColumnDefaultValue(table, inputs[2], (c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['inflection']);
33
+ setColumnDefaultValue(table, inputs[3], (c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['min']);
34
+ break;
14
35
  }
36
+ return inputs;
37
+ }
15
38
 
16
- const df = tv.dataFrame;
17
-
18
- const assayColInput = ui.input.column('Assay Column', {table: df, nullable: true, filter: (c) => c.isCategorical, tooltipText: 'Column with assay names'});
19
- const concentrationColInput = ui.input.column('Concentration Column', {table: df, nullable: false, filter: (c) => c.isNumerical, tooltipText: 'Column with concentration values'});
20
- const readoutColInput = ui.input.column('Readout Column', {table: df, nullable: false, filter: (c) => c.isNumerical, tooltipText: 'Column with readout values'});
21
- const excludeOutliersInput = ui.input.column('Outliers Column', {table: df, nullable: true, filter: (c) => (c.isCategorical || c.type === DG.TYPE.BOOL) && c.categories.length === 2, tooltipText: 'Column with outliers to exclude from the analysis'});
22
- const compoundIDColInput = ui.input.column('Compound ID Column', {table: df, nullable: true, tooltipText: 'Column with compound IDs'});
23
- const batchIDColInput = ui.input.column('Batch ID Column', {table: df, nullable: false, tooltipText: 'Column with batch IDs. this column along with the Assay column will be used to group the data into curves'});
24
- const runIDColInput = ui.input.column('Run ID Column', {table: df, nullable: true, tooltipText: 'Column with run IDs. this column along with the Assay column will be used to group the data into curves'});
25
-
26
- assayColInput.value = wu(df.columns.categorical).find((c) => c.name.toLowerCase().includes('assay')) ?? null;
27
- concentrationColInput.value = df.columns.firstWhere((c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME && c.name.toLowerCase().includes('concentration')) ?? null;
28
- readoutColInput.value = df.columns.firstWhere((c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME && (c.name.toLowerCase().includes('inhibition'))) ?? null;
29
- excludeOutliersInput.value = df.columns.firstWhere((c) => (c.isCategorical || c.type === DG.TYPE.BOOL) && c.categories.length === 2 && (c.name.toLowerCase().includes('outlier') || (c.name.toLowerCase().includes('include') && c.name.toLowerCase().includes('exclude')))) ?? null;
30
- compoundIDColInput.value = df.columns.firstWhere((c) => c.isCategorical && c.name.toLowerCase().includes('compound') && c.name.toLowerCase().includes('id')) ?? null;
31
- batchIDColInput.value = df.columns.firstWhere((c) => c.name.toLowerCase().includes('batch') && c.name.toLowerCase().includes('id')) ?? null;
32
- runIDColInput.value = df.columns.firstWhere((c) => (c.name.toLowerCase().includes('run') || c.name.toLowerCase().includes('set')) && c.name.toLowerCase().includes('id')) ?? null;
33
-
34
- const onOK = async () => {
35
- if (!concentrationColInput.value || !readoutColInput.value || !batchIDColInput.value) {
36
- grok.shell.warning('Please fill all required fields');
37
- return;
38
- }
39
+ export type FitFunctionEditorHistory = {
40
+ fitParamCols: string[],
41
+ fitFunction: FitFunctionType,
42
+ useFitParamCols: boolean
43
+ }
39
44
 
40
- const resultObj: {[assay: string]: {[batchID: string]: {[runID: string]: {x: number[], y: number[], outliers: boolean[], compoundId: any}}}} = {};
41
-
42
- const assayCol = assayColInput.value;
43
- const concentrationCol = concentrationColInput.value!;
44
- const readoutCol = readoutColInput.value!;
45
- const excludeOutliersCol = excludeOutliersInput.value;
46
- const compoundIDCol = compoundIDColInput.value;
47
- const batchIDCol = batchIDColInput.value!;
48
- const runIDCol = runIDColInput.value;
49
-
50
- const getAssay = assayCol ? (row: number) => assayCol.get(row) : () => 'All';
51
- const otlierIndexes = excludeOutliersCol ? excludeOutliersCol.getRawData() : null;
52
- const isOutlier = excludeOutliersCol ? (excludeOutliersCol.type == DG.COLUMN_TYPE.BOOL ? (row: number) => !!otlierIndexes![row] : (row: number) => !otlierIndexes![row] ) : (_row: number) => false;
53
- const getConcentration = (row: number) => concentrationCol.get(row);
54
- const getReadout = (row: number) => readoutCol.get(row);
55
- const getBatchID = (row: number) => batchIDCol.get(row);
56
- const getCompoundID = compoundIDCol ? (row: number) => compoundIDCol.get(row) : () => null;
57
- const getRunID = runIDCol ? (row: number) => runIDCol.get(row) : () => null;
58
- const markerTypes: FitMarkerType[] = ['circle', 'triangle bottom', 'star', 'cross border', 'diamond', 'square', 'triangle left', 'triangle right', 'triangle top', 'asterisk'];
59
- let markerTypeIndex = 0; // will keep track of the markers
60
- const runIdToMarkerType: {[runID: string]: FitMarkerType} = {};
61
- const getMarkerType = (runID: string) => {
62
- if (runID in runIdToMarkerType) { return runIdToMarkerType[runID]; } else {
63
- const markerType = markerTypes[markerTypeIndex];
64
- runIdToMarkerType[runID] = markerType;
65
- markerTypeIndex = (markerTypeIndex + 1) % markerTypes.length;
66
- return markerType;
45
+ function createFitFunctionEditor(table: DG.DataFrame) {
46
+ const fitFunctions = [FitFunctionTypes.FOUR_PL_DOSE_RESPONSE, FitFunctionTypes.FOUR_PL_REGRESSION];
47
+ const fitFunctionInput = ui.input.choice('Fit Function', {value: FitFunctionTypes.FOUR_PL_DOSE_RESPONSE, items: fitFunctions, nullable: false, tooltipText: 'Select the fit function to use for the curve fitting'});
48
+ const form = ui.form([]);
49
+ let fitParamInputs: DG.InputBase<DG.Column>[] = [];
50
+ const useFitParamsInput = ui.input.bool('Use Prefit Parameters', {value: true, tooltipText: 'Use selected fit curve parameters instead of fitting the curve from scratch'});
51
+ useFitParamsInput.onChanged.subscribe(() => {
52
+ fitParamInputs.forEach((i) => i.enabled = useFitParamsInput.value);
53
+ });
54
+ // const checkContainer: HTMLDivElement | null = useFitParamsInput.root.querySelector('div.ui-input-editor');
55
+ // if (checkContainer)
56
+ // checkContainer.style.setProperty('padding', '0px', 'important');
57
+ fitFunctionInput.addOptions(useFitParamsInput.captionLabel);
58
+ fitFunctionInput.addOptions(useFitParamsInput.input);
59
+ useFitParamsInput.captionLabel.style.color = 'var(--grey-6)';
60
+ const onChanged = () => {
61
+ ui.empty(form);
62
+ const inputs = createFitParamsEditor(table, fitFunctionInput.value!);
63
+ fitParamInputs = inputs as DG.InputBase<DG.Column>[];
64
+ ui.appendAll(form, [fitFunctionInput.root, ...inputs.map((i) => i.root)]);
65
+ useFitParamsInput.fireChanged();
66
+ };
67
+ onChanged();
68
+ fitFunctionInput.onChanged.subscribe(() => onChanged());
69
+ return {
70
+ form,
71
+ getValues: () => useFitParamsInput.value ? fitParamInputs.map((i) => i.value) : [],
72
+ getFitFunction: () => fitFunctionInput.value!,
73
+ getHystory: (): FitFunctionEditorHistory => ({
74
+ fitParamCols: fitParamInputs.map((i) => i.value?.name ?? ''),
75
+ fitFunction: fitFunctionInput.value!,
76
+ useFitParamCols: useFitParamsInput.value,
77
+ }),
78
+ applyHistory: (history: FitFunctionEditorHistory) => {
79
+ // first, set the fit function
80
+ fitFunctionInput.value = history.fitFunction as typeof fitFunctionInput.items[number];
81
+ // then, set the fit parameters
82
+ useFitParamsInput.value = history.useFitParamCols;
83
+ if (history.fitParamCols?.length === fitParamInputs?.length) {
84
+ for (let i = 0; i < fitParamInputs.length; i++) {
85
+ const col = table.col(history.fitParamCols[i]);
86
+ if (col)
87
+ fitParamInputs[i].value = col;
88
+ }
67
89
  }
68
- };
90
+ }
91
+ };
92
+ }
69
93
 
70
- for (let i = 0; i < df.rowCount; i++) {
71
- const assay = getAssay(i);
72
- const batchID = getBatchID(i);
73
-
74
- const concentration = getConcentration(i);
75
- const readout = getReadout(i);
76
- const outlier = isOutlier(i);
77
- if (!resultObj[assay])
78
- resultObj[assay] = {};
79
-
80
- const assayObj = resultObj[assay];
81
- if (!assayObj[batchID])
82
- assayObj[batchID] = {};
83
-
84
- const assayBatchObj = assayObj[batchID];
85
- // {x: [], y: [], outliers: [], compoundId: compoundID};
86
- // use batchID as a key if runID is not provided
87
- const runID = getRunID(i) ?? batchID;
88
- if (!assayBatchObj[runID]) {
89
- const compoundID = getCompoundID(i);
90
- assayBatchObj[runID] = {x: [], y: [], outliers: [], compoundId: compoundID};
91
- }
92
- const assayBatchRunObj = assayBatchObj[runID];
93
- assayBatchRunObj.x.push(concentration);
94
- assayBatchRunObj.y.push(readout);
95
- assayBatchRunObj.outliers.push(outlier);
94
+ export type ParentTableFormHistory = {
95
+ tableName: string | null,
96
+ reportedIC50Col: string | null,
97
+ reportedQualifiedIC50Col: string | null,
98
+ experimentIDCol: string | null,
99
+ qualifierCol: string | null,
100
+ additionalColumns: string[],
101
+ fitParams: FitFunctionEditorHistory | null,
102
+ }
103
+
104
+ function createParentTableForm() {
105
+ const tableInput = ui.input.table('Parent Table', {value: undefined, nullable: true, tooltipText: 'Table with parent data'});
106
+ const form = ui.form([]);
107
+ let fitFunctionEditor: ReturnType<typeof createFitFunctionEditor> | null = null;
108
+ let reportedIC50Col: DG.InputBase<DG.Column | null>;
109
+ let reportedQualifiedIC50Col: DG.InputBase<DG.Column | null>;
110
+ let experimentIDCol: DG.InputBase<DG.Column | null>;
111
+ let qualifierCol: DG.InputBase<DG.Column | null>;
112
+ let additionalColumnsInput: DG.InputBase<DG.Column[] | null>;
113
+ const onChanged = () => {
114
+ ui.empty(form);
115
+ form.appendChild(tableInput.root);
116
+ if (!tableInput.value) {
117
+ fitFunctionEditor = null;
118
+ return;
96
119
  }
120
+ reportedIC50Col = ui.input.column('Reported IC50', {table: tableInput.value!, nullable: true, tooltipText: 'Column with reported IC50 values'});
121
+ reportedQualifiedIC50Col = ui.input.column('Reported Qualified IC50', {table: tableInput.value!, nullable: true, tooltipText: 'Column with reported qualified IC50 values'});
122
+ experimentIDCol = ui.input.column('Experiment ID', {table: tableInput.value!, nullable: true, tooltipText: 'Column with experiment IDs'});
123
+ qualifierCol = ui.input.column('Qualifier', {table: tableInput.value!, nullable: true, tooltipText: 'Column with qualifier values'});
124
+ additionalColumnsInput = ui.input.columns('Additional Columns', {table: tableInput.value!, nullable: true, tooltipText: 'Additional columns to include in the curves data'});
125
+ // the first two are sort of sketchy, because their columns (while expected to be numerical), can contain stuff like inconclusive, not applicable, etc.
126
+ setColumnDefaultValue(tableInput.value!, reportedIC50Col, (c) => true && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['reported ic50', 'reported_ic50', 'reported-ic50']);
127
+ setColumnDefaultValue(tableInput.value!, reportedQualifiedIC50Col, (c) => true && c.type !== DG.COLUMN_TYPE.DATE_TIME, ['qualified_reported_ic50', 'qualified reported ic50', 'qualified-reported-ic50']);
128
+ setColumnDefaultValue(tableInput.value!, experimentIDCol, (c) => c.isCategorical, ['experiment id', 'experiment_id', 'experiment-id']);
129
+ setColumnDefaultValue(tableInput.value!, qualifierCol, (c) => c.isCategorical, ['qualifier']);
130
+ const columnsForm = ui.form([reportedIC50Col, reportedQualifiedIC50Col, experimentIDCol, qualifierCol, additionalColumnsInput]);
97
131
 
98
- // create fit series
99
-
100
- const assays: string[] = [];
101
- const batchIDs: string[] = [];
102
- const compoundIDs: string[] = [];
103
- const seriesData: Omit<FitChartData, 'seriesOptions'>[] = [];
104
-
105
- for (const assay in resultObj) {
106
- for (const batchID in resultObj[assay]) {
107
- const assayBatchObj = resultObj[assay][batchID];
108
- for (const runID in assayBatchObj) {
109
- assays.push(assay);
110
- batchIDs.push(batchID);
111
- const compoundID = Object.values(assayBatchObj)[0]?.compoundId;
112
- compoundIDs.push(compoundID);
113
- const x = assayBatchObj[runID].x;
114
- const y = assayBatchObj[runID].y;
115
- const outliers = assayBatchObj[runID].outliers;
116
- const markerType = getMarkerType(runID);
117
- const s: IFitSeries = {
118
- fit: undefined, fitFunction: FIT_FUNCTION_4PL_REGRESSION, clickToToggle: true, droplines: ['IC50'], name: `${runID}`,
119
- points: x.map((xv, i) => ({x: xv, y: y[i], outlier: outliers[i], marker: markerType, size: 6})).sort((a, b) => a.x - b.x),
120
- };
121
- const fitData: Omit<FitChartData, 'seriesOptions'> = {
122
- chartOptions: {
123
- xAxisName: concentrationCol.name,
124
- yAxisName: readoutCol.name,
125
- logX: true,
126
- title: `${assay} - ${batchID} - ${runID}`,
127
- },
128
- series: [s],
129
- };
130
- seriesData.push(fitData);
131
- }
132
+ fitFunctionEditor = createFitFunctionEditor(tableInput.value!);
133
+ ui.appendAll(form, [columnsForm, fitFunctionEditor.form]);
134
+ };
135
+ onChanged();
136
+ tableInput.onChanged.subscribe(() => onChanged());
137
+
138
+ return {
139
+ getValue: () => ({
140
+ fitParamCols: fitFunctionEditor?.getValues ? fitFunctionEditor.getValues() : null,
141
+ reportedIC50Col: reportedIC50Col?.value,
142
+ reportedQualifiedIC50Col: reportedQualifiedIC50Col?.value,
143
+ experimentIDCol: experimentIDCol?.value,
144
+ qualifierCol: qualifierCol?.value,
145
+ additionalColumns: additionalColumnsInput?.value,
146
+ fitFunction: fitFunctionEditor?.getFitFunction ? fitFunctionEditor.getFitFunction() : null,
147
+ }),
148
+ form,
149
+ getTable: () => tableInput.value,
150
+ getHistory: (): ParentTableFormHistory => ({
151
+ tableName: tableInput.value?.name ?? null,
152
+ reportedIC50Col: reportedIC50Col?.value?.name ?? null,
153
+ reportedQualifiedIC50Col: reportedQualifiedIC50Col?.value?.name ?? null,
154
+ experimentIDCol: experimentIDCol?.value?.name ?? null,
155
+ qualifierCol: qualifierCol?.value?.name ?? null,
156
+ additionalColumns: additionalColumnsInput?.value?.map((c) => c.name) ?? [],
157
+ fitParams: fitFunctionEditor?.getHystory ? fitFunctionEditor.getHystory() : null,
158
+ }),
159
+ applyHistory: (history: ParentTableFormHistory) => {
160
+ if (history.tableName) {
161
+ const df = grok.shell.table(history.tableName);
162
+ if (df)
163
+ tableInput.value = df;
132
164
  }
165
+ if (!tableInput.value)
166
+ return;
167
+
168
+ history.reportedIC50Col && tableInput.value.col(history.reportedIC50Col) && (reportedIC50Col.value = tableInput.value.col(history.reportedIC50Col));
169
+ history.reportedQualifiedIC50Col && tableInput.value.col(history.reportedQualifiedIC50Col) && (reportedQualifiedIC50Col.value = tableInput.value.col(history.reportedQualifiedIC50Col));
170
+ history.additionalColumns && (additionalColumnsInput.value = history.additionalColumns.map((c) => tableInput.value!.col(c)).filter((c) => c != null) as DG.Column[]);
171
+ history.experimentIDCol && tableInput.value.col(history.experimentIDCol) && (experimentIDCol.value = tableInput.value.col(history.experimentIDCol));
172
+ history.qualifierCol && tableInput.value.col(history.qualifierCol) && (qualifierCol.value = tableInput.value.col(history.qualifierCol));
173
+ if (fitFunctionEditor && history.fitParams)
174
+ fitFunctionEditor.applyHistory(history.fitParams);
133
175
  }
176
+ };
177
+ }
134
178
 
135
- const assaysColumn = DG.Column.fromStrings('Assay', assays);
136
- const batchIDsColumn = DG.Column.fromStrings('Batch ID', batchIDs);
137
- const compoundIDsColumn = DG.Column.fromStrings('Compound ID', compoundIDs);
138
- const seriesColumn = DG.Column.fromStrings('Series', seriesData.map((s) => JSON.stringify(s)));
139
- const allResultsColumn = DG.Column.fromStrings('All Results', seriesData.map((s) => s.series[0]?.points.map((p) => `(${p.x}, ${p.y})`).join(', ')));
140
- const runIdColumn = DG.Column.fromStrings('Run ID', seriesData.map((s) => s.series[0]!.name ?? ''));
141
- seriesColumn.semType = 'fit';
142
- seriesColumn.setTag('cell.renderer', 'fit');
143
179
 
144
- const resDF = DG.DataFrame.fromColumns([seriesColumn, assaysColumn, batchIDsColumn, compoundIDsColumn, runIdColumn, allResultsColumn]);
145
- resDF.name = 'Fitted Curves';
180
+ function createWellTableForm() {
181
+ const tableInput = ui.input.table('Well Table', {value: grok.shell.tv.dataFrame, nullable: false, tooltipText: 'Table with well level data'});
182
+ let assayColInput: DG.InputBase<DG.Column | null>;
183
+ let concentrationColInput: DG.InputBase<DG.Column | null>;
184
+ let readoutColInput: DG.InputBase<DG.Column | null>;
185
+ let excludeOutliersInput: DG.InputBase<DG.Column | null>;
186
+ let compoundIDColInput: DG.InputBase<DG.Column | null>;
187
+ let batchIDColInput: DG.InputBase<DG.Column | null>;
188
+ let runIDColInput: DG.InputBase<DG.Column | null>;
189
+ let targetEntityColInput: DG.InputBase<DG.Column | null>;
190
+ const form = ui.form([]);
146
191
 
147
- const actualStatNames = {
148
- 'interceptX': 'IC50',
149
- 'top': 'Max',
150
- 'bottom': 'Min',
151
- 'slope': 'Hill',
152
- 'auc': 'AUC',
153
- };
192
+ const onTableInputChange = () => {
193
+ const df = tableInput.value!;
194
+ ui.empty(form);
195
+ assayColInput = ui.input.column('Assay Name', {table: df, nullable: true, filter: (c) => c.isCategorical, tooltipText: 'Column with assay names'});
196
+ concentrationColInput = ui.input.column('Concentration', {table: df, nullable: false, filter: (c) => c.isNumerical, tooltipText: 'Column with concentration values'});
197
+ readoutColInput = ui.input.column('Readout', {table: df, nullable: false, filter: (c) => c.isNumerical, tooltipText: 'Column with readout values'});
198
+ excludeOutliersInput = ui.input.column('Outliers', {table: df, nullable: true, filter: (c) => (c.isCategorical || c.type === DG.TYPE.BOOL) && c.categories.length === 2, tooltipText: 'Column with outliers to exclude from the analysis'});
199
+ compoundIDColInput = ui.input.column('Compound ID', {table: df, nullable: true, tooltipText: 'Column with compound IDs'});
200
+ batchIDColInput = ui.input.column('Batch ID', {table: df, nullable: false, tooltipText: 'Column with batch IDs. this column along with the Assay column will be used to group the data into curves'});
201
+ runIDColInput = ui.input.column('Run ID', {table: df, nullable: true, tooltipText: 'Column with run IDs. this column along with the Assay column will be used to group the data into curves'});
202
+ targetEntityColInput = ui.input.column('Target Entity', {table: df, nullable: false, filter: (c) => c.isCategorical, tooltipText: 'Column with target entity names. This column will be used to group the data into curves'});
154
203
 
155
- Object.entries(actualStatNames).forEach(([statName, alias]) => {
156
- const params = {table: resDF, colName: seriesColumn.name, propName: statName, seriesNumber: 0};
157
- DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(params).callSync({processed: false}).getOutputParamValue().name = alias;
158
- });
159
- if (actualStatNames['interceptX'])
160
- resDF.col(actualStatNames['interceptX']) && (resDF.col(actualStatNames['interceptX'])!.meta.format = 'scientific');
161
-
162
- return resDF;
204
+ assayColInput.value = wu(df.columns.categorical).find((c) => c.name.toLowerCase().includes('assay') && c.name.toLowerCase().includes('name')) ?? null;
205
+ concentrationColInput.value = df.columns.firstWhere((c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME && c.name.toLowerCase().includes('concentration')) ?? null;
206
+ readoutColInput.value = df.columns.firstWhere((c) => c.isNumerical && c.type !== DG.COLUMN_TYPE.DATE_TIME && (c.name.toLowerCase().includes('inhibition'))) ?? null;
207
+ excludeOutliersInput.value = df.columns.firstWhere((c) => (c.isCategorical || c.type === DG.TYPE.BOOL) && c.categories.length === 2 && (c.name.toLowerCase().includes('outlier') || (c.name.toLowerCase().includes('include') && c.name.toLowerCase().includes('exclude')))) ?? null;
208
+ compoundIDColInput.value = df.columns.firstWhere((c) => c.isCategorical && c.name.toLowerCase().includes('compound_id') || c.name.toLowerCase().includes('compoundid') || c.name.toLowerCase().includes('compound id')) ?? null;
209
+ batchIDColInput.value = df.columns.firstWhere((c) => c.name.toLowerCase().includes('batch') && c.name.toLowerCase().includes('id')) ?? null;
210
+ runIDColInput.value = df.columns.firstWhere((c) => (c.name.toLowerCase().includes('run') || c.name.toLowerCase().includes('set')) && c.name.toLowerCase().includes('id')) ?? null;
211
+ targetEntityColInput.value = df.columns.firstWhere((c) => c.isCategorical && (c.name.toLowerCase().includes('target') && c.name.toLowerCase().includes('entity'))) ?? null;
212
+ ui.appendAll(form, [tableInput.root, assayColInput.root, batchIDColInput.root, runIDColInput.root, concentrationColInput.root, readoutColInput.root, compoundIDColInput.root, targetEntityColInput.root, excludeOutliersInput.root]);
163
213
  };
214
+ onTableInputChange();
215
+ tableInput.onChanged.subscribe(() => onTableInputChange());
216
+ return {form, getValues: () => ({
217
+ table: tableInput.value!,
218
+ assayCol: assayColInput.value,
219
+ batchIDCol: batchIDColInput.value,
220
+ concentrationCol: concentrationColInput.value,
221
+ readoutCol: readoutColInput.value,
222
+ compoundIDCol: compoundIDColInput.value,
223
+ excludeOutliersCol: excludeOutliersInput.value,
224
+ targetEntityCol: targetEntityColInput.value,
225
+ runIDCol: runIDColInput.value,
226
+ }), applyHistory: (v: {[key in 'assayCol' | 'batchIDCol' | 'concentrationCol' | 'readoutCol' | 'compoundIDCol' | 'excludeOutliersCol' | 'runIDCol' | 'targetEntityCol'
227
+ ]: string | null}
228
+ ) => {
229
+ const df = tableInput.value!;
230
+ assayColInput.value = v.assayCol ? df.col(v.assayCol) : null;
231
+ batchIDColInput.value = v.batchIDCol ? df.col(v.batchIDCol) : null;
232
+ concentrationColInput.value = v.concentrationCol ? df.col(v.concentrationCol) : null;
233
+ readoutColInput.value = v.readoutCol ? df.col(v.readoutCol) : null;
234
+ compoundIDColInput.value = v.compoundIDCol ? df.col(v.compoundIDCol) : null;
235
+ excludeOutliersInput.value = v.excludeOutliersCol ? df.col(v.excludeOutliersCol) : null;
236
+ runIDColInput.value = v.runIDCol ? df.col(v.runIDCol) : null;
237
+ targetEntityColInput.value = v.targetEntityCol ? df.col(v.targetEntityCol) : null;
238
+ }
239
+ };
240
+ }
241
+
242
+
243
+ export function dataToCurvesUI() {
244
+ const tv = grok.shell.tv;
245
+ if (!tv || !tv.dataFrame) {
246
+ grok.shell.warning('No open tableview');
247
+ return;
248
+ }
249
+ const wellLevelForm = createWellTableForm();
250
+ const parentTableForm = createParentTableForm();
251
+ const horzForm = ui.divH([wellLevelForm.form, parentTableForm.form], {style: {minWidth: '400px', gap: '20px'}});
164
252
 
165
253
  ui.dialog('Data to Curves')
166
- .add(assayColInput)
167
- .add(batchIDColInput)
168
- .add(runIDColInput)
169
- .add(concentrationColInput)
170
- .add(readoutColInput)
171
- .add(compoundIDColInput)
172
- .add(excludeOutliersInput)
254
+ .add(horzForm)
173
255
  .onOK(async () => {
174
- const df = await onOK();
175
- if (df) {
176
- const tv = grok.shell.addTableView(df);
177
- const trellis = tv.trellisPlot({yColumnNames: ['Batch ID'], xColumnNames: [], viewerType: 'MultiCurveViewer',
256
+ const formRes = wellLevelForm.getValues();
257
+ let parentLevelData: WellTableParentData | undefined = undefined;
258
+ const parentTable = parentTableForm.getTable();
259
+ const parentFormValues = parentTableForm.getValue();
260
+ const fitParamValues = parentFormValues.fitParamCols;
261
+ if (parentTable && fitParamValues && fitParamValues.length > 0) {
262
+ parentLevelData = {
263
+ table: parentTable,
264
+ fitParamColumns: fitParamValues,
265
+ fitFunction: parentFormValues.fitFunction!,
266
+ reportedIC50Column: parentFormValues.reportedIC50Col!,
267
+ reportedQualifiedIC50Column: parentFormValues.reportedQualifiedIC50Col!,
268
+ experimentIDColumn: parentFormValues.experimentIDCol!,
269
+ qualifierColumn: parentFormValues.qualifierCol!,
270
+ additionalColumns: parentFormValues.additionalColumns ?? [],
271
+ };
272
+ }
273
+
274
+ const {table, assayCol, batchIDCol, concentrationCol, readoutCol, compoundIDCol, excludeOutliersCol, runIDCol, targetEntityCol} = formRes;
275
+ const func = DG.Func.find({name: 'dataToCurves'})[0];
276
+ if (!func) {
277
+ grok.shell.error('Function dataToCurves not found');
278
+ return;
279
+ }
280
+ //parentTable?: DG.DataFrame, fitParamColumns?: DG.Column[], reportedIC50Column?: DG.Column, reportedQualifiedIC50Column?: DG.Column,
281
+ // experimentIDColumn?: DG.Column, qualifierColumn?: DG.Column, additionalColumns?: DG.Column[]
282
+ const fc = func.prepare({
283
+ df: table,
284
+ concentrationCol: concentrationCol,
285
+ readoutCol: readoutCol,
286
+ batchIDCol: batchIDCol,
287
+ assayCol: assayCol,
288
+ runIDCol: runIDCol,
289
+ compoundIDCol: compoundIDCol,
290
+ targetEntityCol: targetEntityCol,
291
+ excludeOutliersCol: excludeOutliersCol,
292
+ // parentData:
293
+ parentTable: parentLevelData?.table,
294
+ fitParamColumns: parentLevelData?.fitParamColumns?.map((c) => c.name) ?? [],
295
+ reportedIC50Column: parentLevelData?.reportedIC50Column?.name,
296
+ reportedQualifiedIC50Column: parentLevelData?.reportedQualifiedIC50Column?.name,
297
+ experimentIDColumn: parentLevelData?.experimentIDColumn?.name,
298
+ qualifierColumn: parentLevelData?.qualifierColumn?.name,
299
+ additionalColumns: parentLevelData?.additionalColumns?.map((c) => c.name) ?? [],
300
+ });
301
+ console.log(fc.toString());
302
+ const needsCreationScript = table.tags[DG.Tags.CreationScript] && (!parentLevelData?.table || parentLevelData.table.tags[DG.Tags.CreationScript]);
303
+ await fc.call(undefined, undefined, {processed: !needsCreationScript});
304
+ //console.log(fc.getResultViews());
305
+ //const resDf: DG.DataFrame | null = fc.getOutputParamValue();
306
+ const tv = fc.getResultViews()[0];
307
+ if (tv && tv instanceof DG.TableView && tv.dataFrame) {
308
+ if (!needsCreationScript)
309
+ grok.shell.addView(tv);
310
+
311
+ tv.filters();
312
+ const trellis = tv.trellisPlot({yColumnNames: [groupColumnName], xColumnNames: [], viewerType: 'MultiCurveViewer',
178
313
  showControlPanel: false, showXLabels: false, showYLabels: false, showXSelectors: false, showYSelectors: true, packCategories: true,
179
314
  onClick: 'Select'
180
315
  });
181
- tv.dockManager.dock(trellis, DG.DOCK_TYPE.TOP, null, 'Fitted Curves', 0.5);
316
+ tv.dockManager.dock(trellis, DG.DOCK_TYPE.TOP, tv.dockManager.findNode(tv.grid.root), 'Fitted Curves', 0.5);
182
317
  const selectionGrid = tv.addViewer(DG.VIEWER.GRID, {rowSource: 'Selected', selectedRowsColor: DG.Color.white});
183
318
  tv.dockManager.dock(selectionGrid, DG.DOCK_TYPE.FILL, tv.dockManager.findNode(tv.grid.root), 'Selected Curves');
184
319
  selectionGrid.props.title = 'Selected Curves';
185
- tv.dockManager.dock(tv.grid, DG.DOCK_TYPE.FILL, tv.dockManager.findNode(selectionGrid.root));
186
- tv.grid.props.title = 'Fitted Curves';
187
-
188
- // add the pivot table
189
320
 
190
- const pivot = tv.addViewer(DG.VIEWER.PIVOT_TABLE, {
191
- rowSource: 'Selected', pivotColumnNames: [],
192
- groupByColumnNames: ['Assay'], aggregateColumnNames: ['IC50', 'AUC', 'Hill', 'Min', 'Max'],
193
- aggregateAggTypes: ['geomean', 'avg', 'geomean', 'avg', 'avg'], showHeader: false
194
- });
195
- pivot.props.title = 'Selected Statistics';
196
- tv.dockManager.dock(pivot, DG.DOCK_TYPE.TOP, tv.dockManager.findNode(trellis.root), 'Selected Statistics', 0.1);
321
+ const multiCurveViewer = tv.addViewer('MultiCurveViewer', {showCurrentRowCurve: false, showMouseOverRowCurve: false, showSelectedRowsCurves: true});
322
+ const md = tv.dockManager.dock(multiCurveViewer, DG.DOCK_TYPE.FILL, tv.dockManager.findNode(selectionGrid.root));
323
+ tv.dockManager.dock(tv.grid, DG.DOCK_TYPE.FILL, md);
324
+ tv.grid.props.title = 'Fitted Curves';
197
325
  }
198
326
  })
199
327
  .show()
200
328
  .history(() => {
329
+ const formRes = wellLevelForm.getValues();
330
+ const {assayCol, batchIDCol, concentrationCol, readoutCol, compoundIDCol, excludeOutliersCol, runIDCol, targetEntityCol} = formRes;
201
331
  const obj = {
202
- assayCol: assayColInput.value?.name,
203
- batchIDCol: batchIDColInput.value?.name,
204
- concentrationCol: concentrationColInput.value?.name,
205
- readoutCol: readoutColInput.value?.name,
206
- compoundIDCol: compoundIDColInput.value?.name,
207
- excludeOutliersCol: excludeOutliersInput.value?.name,
208
- runIDCol: runIDColInput.value?.name,
332
+ assayCol: assayCol?.name,
333
+ batchIDCol: batchIDCol?.name,
334
+ concentrationCol: concentrationCol?.name,
335
+ readoutCol: readoutCol?.name,
336
+ compoundIDCol: compoundIDCol?.name,
337
+ excludeOutliersCol: excludeOutliersCol?.name,
338
+ runIDCol: runIDCol?.name,
339
+ targetEntityCol: targetEntityCol?.name,
209
340
  };
210
- return Object.fromEntries(Object.entries(obj).filter(([_, v]) => !!v));
341
+ return {wells: JSON.stringify(Object.fromEntries(Object.entries(obj).filter(([_, v]) => !!v)) ?? {}), parent: JSON.stringify(parentTableForm.getHistory() ?? {})};
211
342
  }, (v) => {
212
- assayColInput.value = v.assayCol ? df.columns.byName(v.assayCol) : null;
213
- batchIDColInput.value = v.batchIDCol ? df.columns.byName(v.batchIDCol) : null;
214
- concentrationColInput.value = df.columns.byName(v.concentrationCol);
215
- readoutColInput.value = df.columns.byName(v.readoutCol);
216
- compoundIDColInput.value = v.compoundIDCol ? df.columns.byName(v.compoundIDCol) : null;
217
- excludeOutliersInput.value = v.excludeOutliersCol ? df.columns.byName(v.excludeOutliersCol) : null;
218
- runIDColInput.value = v.runIDCol ? df.columns.byName(v.runIDCol) : null;
343
+ const wells = JSON.parse(v?.wells ?? '{}');
344
+ const parent = JSON.parse(v?.parent ?? '{}');
345
+ wellLevelForm.applyHistory(wells);
346
+ parentTableForm.applyHistory(parent);
219
347
  });
220
348
  }
349
+ export type WellTableParentData = {
350
+ table?: DG.DataFrame, fitParamColumns?: DG.Column[], fitFunction?: FitFunctionType, reportedIC50Column?: DG.Column, reportedQualifiedIC50Column?: DG.Column,
351
+ experimentIDColumn?: DG.Column, qualifierColumn?: DG.Column, additionalColumns?: DG.Column[],
352
+ }
353
+
354
+ export async function convertDataToCurves(df: DG.DataFrame,
355
+ concentrationCol: DG.Column, readoutCol: DG.Column, batchIDCol: DG.Column,
356
+ assayCol: DG.Column, runIDCol: DG.Column, compoundIDCol: DG.Column, targetEntityCol: DG.Column, excludeOutliersCol?: DG.Column, parentData?: WellTableParentData
357
+ ): Promise<DG.DataFrame> {
358
+ if (!concentrationCol || !readoutCol || !batchIDCol) {
359
+ grok.shell.warning('Please fill all required fields');
360
+ throw new Error('Please fill all required fields');
361
+ }
362
+
363
+ const curvesObj: {[curveKey: string]: {x: number[], y: number[], outliers: boolean[], groupKey: string, runID: string, info: {[key: string]: any}}} = {};
364
+ const assayColCats = assayCol?.categories;
365
+ const assayColIndexes = assayCol?.getRawData();
366
+ const consentrationRawData = concentrationCol.getRawData();
367
+ const readoutRawData = readoutCol.getRawData();
368
+ const batchIDCategories = batchIDCol?.categories;
369
+ const batchIDRawData = batchIDCol?.getRawData();
370
+ const compoundIDCategories = compoundIDCol?.categories;
371
+ const compoundIDRawData = compoundIDCol?.getRawData();
372
+ const runIDCategories = runIDCol?.categories;
373
+ const runIDRawData = runIDCol?.getRawData();
374
+ const targetEntityCategories = targetEntityCol?.categories;
375
+ const targetEntityRawData = targetEntityCol?.getRawData();
376
+
377
+
378
+ const getAssay = assayCol ? (row: number) => assayColCats![assayColIndexes![row]] : () => 'All';
379
+ const otlierIndexes = excludeOutliersCol ? excludeOutliersCol.getRawData() : null;
380
+ const isOutlier = excludeOutliersCol ? (excludeOutliersCol.type == DG.COLUMN_TYPE.BOOL ? (row: number) => !!otlierIndexes![row] : (row: number) => !otlierIndexes![row] ) : (_row: number) => false;
381
+ const getConcentration = (row: number) => consentrationRawData[row];
382
+ const getReadout = (row: number) => readoutRawData[row];
383
+ const getBatchID = (row: number) => batchIDCategories[batchIDRawData[row]];
384
+ const getCompoundID = compoundIDCol ? (row: number) => compoundIDCategories![compoundIDRawData![row]] : () => null;
385
+ const getRunID = runIDCol ? (row: number) => runIDCategories![runIDRawData![row]] : () => null;
386
+ const getTargetEntity = targetEntityCol ? (row: number) => targetEntityCategories![targetEntityRawData![row]] : () => null;
387
+ const markerTypes: FitMarkerType[] = ['circle', 'triangle bottom', 'star', 'cross border', 'diamond', 'square', 'triangle left', 'triangle right', 'triangle top', 'asterisk'];
388
+ let markerTypeIndex = 0; // will keep track of the markers
389
+ const runIdToMarkerType: {[runID: string]: FitMarkerType} = {};
390
+ const getMarkerType = (runID: string) => {
391
+ if (runID in runIdToMarkerType) { return runIdToMarkerType[runID]; } else {
392
+ const markerType = markerTypes[markerTypeIndex];
393
+ runIdToMarkerType[runID] = markerType;
394
+ markerTypeIndex = (markerTypeIndex + 1) % markerTypes.length;
395
+ return markerType;
396
+ }
397
+ };
398
+
399
+ const getGroupKey = (row: number) => `${getCompoundID(row)}||${getAssay(row)}||${getTargetEntity(row)}`;
400
+ const getCurveKey = (row: number) => `${getGroupKey(row)}||${getRunID(row)}`;
401
+ const getParentDataCurveKey = parentData && parentData.table?.col(compoundIDCol.name) && parentData.table.col(assayCol.name) && parentData.table.col(targetEntityCol.name) &&
402
+ parentData.table.col(runIDCol.name) ? (row: number) =>
403
+ `${parentData.table?.col(compoundIDCol.name)!.get(row)}||${parentData.table?.col(assayCol.name)!.get(row)}||${parentData.table?.col(targetEntityCol.name)!.get(row)}||${parentData.table?.col(runIDCol.name)!.get(row)}` :
404
+ (_row: number) => null;
405
+ // put the parent data into the parentObj
406
+ const parentObj: {[curveKey: string]: {groupKey?: string, fitParams: number[], fitFunction: FitFunctionType, reportedIC50?: number, reportedQualifiedIC50?: number | string, experimentID?: string, qualifier?: string, additionalColumns?: {[colName: string]: any}}} = {};
407
+ if (parentData) {
408
+ for (let i = 0; i < (parentData.table?.rowCount ?? 0); i++) {
409
+ const curveKey = getParentDataCurveKey ? getParentDataCurveKey(i) : null;
410
+ if (!curveKey || parentObj[curveKey]) continue;
411
+ parentObj[curveKey] = {
412
+ fitParams: parentData.fitParamColumns?.map((c) => c.get(i)) ?? [],
413
+ fitFunction: parentData.fitFunction ?? FIT_FUNCTION_4PL_DOSE_RESPONSE,
414
+ reportedIC50: parentData.reportedIC50Column ? parentData.reportedIC50Column.get(i) : undefined,
415
+ reportedQualifiedIC50: parentData.reportedQualifiedIC50Column ? parentData.reportedQualifiedIC50Column.get(i) : undefined,
416
+ experimentID: parentData.experimentIDColumn ? parentData.experimentIDColumn.get(i) : undefined,
417
+ qualifier: parentData.qualifierColumn ? parentData.qualifierColumn.get(i) : undefined,
418
+ additionalColumns: parentData.additionalColumns ? Object.fromEntries(parentData.additionalColumns.map((c) => [c.name, c.get(i)])) : undefined,
419
+ };
420
+ }
421
+ }
422
+
423
+ for (let i = 0; i < df.rowCount; i++) {
424
+ const assay = getAssay(i);
425
+ const batchID = getBatchID(i);
426
+ const concentration = getConcentration(i);
427
+ const readout = getReadout(i);
428
+ const outlier = isOutlier(i);
429
+ const compoundID = getCompoundID(i);
430
+ const targetEntity = getTargetEntity(i);
431
+ const runID = getRunID(i) ?? '';
432
+
433
+ const groupKey = getGroupKey(i);
434
+ const curveKey = getCurveKey(i);
435
+
436
+ if (!curvesObj[curveKey]) {
437
+ curvesObj[curveKey] = {x: [], y: [], outliers: [], groupKey, runID: runID, info: {
438
+ 'Assay Name': assay,
439
+ 'Batch ID': batchID,
440
+ 'Compound ID': compoundID,
441
+ 'Target Entity': targetEntity,
442
+ 'Run ID': runID,
443
+ }};
444
+ if (parentData && parentObj[curveKey]) {
445
+ curvesObj[curveKey].info['Reported IC50'] = parentObj[curveKey].reportedIC50;
446
+ curvesObj[curveKey].info['Qualified Reported IC50'] = parentObj[curveKey].reportedQualifiedIC50;
447
+ curvesObj[curveKey].info['Experiment ID'] = parentObj[curveKey].experimentID;
448
+ curvesObj[curveKey].info['Qualifier'] = parentObj[curveKey].qualifier;
449
+ if (parentObj[curveKey].additionalColumns)
450
+ Object.assign(curvesObj[curveKey].info, parentObj[curveKey].additionalColumns);
451
+ if (parentObj[curveKey].fitParams && parentObj[curveKey].fitParams.length > 0) {
452
+ for (let j = 0; j < (parentData.fitParamColumns?.length ?? 0); j++) {
453
+ const paramName = parentData.fitParamColumns![j].name;
454
+ curvesObj[curveKey].info[paramName] = parentObj[curveKey].fitParams[j];
455
+ }
456
+ }
457
+ parentObj[curveKey].groupKey = groupKey; // save the group key for the parent object
458
+ }
459
+ }
460
+ const curve = curvesObj[curveKey];
461
+ curve.x.push(concentration);
462
+ curve.y.push(readout);
463
+ curve.outliers.push(outlier);
464
+ }
465
+
466
+ // create fit series
467
+ const colorHash: {[key: string]: string} = {};
468
+
469
+ const getColor = (key: string): string => {
470
+ if (colorHash[key]) return colorHash[key];
471
+ const color = DG.Color.getCategoricalColor(Object.keys(colorHash).length);
472
+ colorHash[key] = DG.Color.toHtml(color);
473
+ return colorHash[key];
474
+ };
475
+
476
+
477
+ const curvesObjsArray = Object.entries(curvesObj);
478
+ const tableColList: DG.Column[] = [];
479
+ const curvesCol = DG.Column.string('Fitted Curve', curvesObjsArray.length);
480
+ curvesCol.init((i) => {
481
+ const [curveKey, curve] = curvesObjsArray[i];
482
+ const x = curve.x;
483
+ const y = curve.y;
484
+ const outliers = curve.outliers;
485
+ const runID = curve.runID;
486
+ const markerType = getMarkerType(runID);
487
+ const params = parentObj[curveKey] ? parentObj[curveKey].fitParams : undefined;
488
+ const colorKey = (curve.info['Assay Name'] ?? '') + '||' + (curve.info['Target Entity'] ?? '');
489
+ const color = getColor(colorKey);
490
+ const fitFunctionName = parentObj?.[curveKey]?.fitFunction ? parentObj[curveKey].fitFunction : FIT_FUNCTION_4PL_DOSE_RESPONSE;
491
+ const s: IFitSeries = {
492
+ fit: undefined, fitFunction: fitFunctionName, clickToToggle: true, droplines: ['IC50'], name: `${runID}`,
493
+ 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)
494
+ };
495
+ const fitData: Omit<FitChartData, 'seriesOptions'> = {
496
+ chartOptions: {
497
+ xAxisName: concentrationCol.name,
498
+ yAxisName: readoutCol.name,
499
+ logX: true,
500
+ title: `${curveKey}`,
501
+ },
502
+ series: [s],
503
+ };
504
+ return JSON.stringify(fitData);
505
+ });
506
+ tableColList.push(curvesCol);
507
+ curvesCol.semType = 'fit';
508
+ curvesCol.setTag('cell.renderer', 'fit');
509
+ // add group column
510
+ tableColList.push(DG.Column.fromStrings(groupColumnName, curvesObjsArray.map((c) => c[1].groupKey)));
511
+
512
+ const otherColumns = Object.keys(curvesObjsArray[0][1].info);
513
+
514
+ for (const colName of otherColumns) {
515
+ const col = DG.Column.fromStrings(colName, curvesObjsArray.map((c) =>
516
+ c[1].info[colName]?.toString?.() ?? ''));
517
+ tableColList.push(col);
518
+ }
519
+
520
+
521
+ const getNumericValue = (x: any) =>
522
+ (x != undefined && !isNaN(x)) ?
523
+ (typeof x === 'number' && x != DG.FLOAT_NULL && x != DG.INT_NULL) ? x :
524
+ ((typeof x === 'string') ? ((Number.parseFloat(x) != undefined && !isNaN(Number.parseFloat(x))) ? Number.parseFloat(x) : undefined) : undefined) : undefined;
525
+
526
+ // add additional calculated columns, based on the results
527
+ // max percent inhibition, total results, all results and so on
528
+ // all of them will be an aggregate of some kind, so we need to group the needed data
529
+ const grouppedValues: {[groupKey: string]: {maxYs: number[], reportedIC50s: number[], qualifiedIC50s: string[],}} = {};
530
+ for (const [curveKey, curve] of curvesObjsArray) {
531
+ const groupKey = curve.groupKey;
532
+ if (!groupKey) continue;
533
+ if (!(groupKey in grouppedValues))
534
+ grouppedValues[groupKey] = {maxYs: [], reportedIC50s: [], qualifiedIC50s: []};
535
+ grouppedValues[groupKey].maxYs.push(Math.max(...curve.y.filter((_, i) => !curve.outliers[i])));
536
+ if (parentData && parentObj[curveKey]) {
537
+ if (parentObj[curveKey].reportedQualifiedIC50 ?? '' != '') {
538
+ grouppedValues[groupKey].qualifiedIC50s.push(parentObj[curveKey].reportedQualifiedIC50 as string);
539
+ let ic50 = getNumericValue(parentData.reportedQualifiedIC50Column ? parentObj[curveKey].reportedQualifiedIC50 : parentObj[curveKey].reportedIC50);
540
+ if (ic50 == undefined) {
541
+ try {
542
+ ic50 = DG.Qnum.parse((parentData.reportedQualifiedIC50Column ? parentObj[curveKey].reportedQualifiedIC50 : parentObj[curveKey].reportedIC50) as string);
543
+ } catch (_e) {
544
+ }
545
+ }
546
+ if (ic50 != undefined)
547
+ grouppedValues[groupKey].reportedIC50s.push(ic50);
548
+ }
549
+ }
550
+ }
551
+ const grouppedAggregations: {[groupKey: string]: {[key: string]: undefined | string | null}} = {};
552
+
553
+ for (const groupKey in grouppedValues) {
554
+ const values = grouppedValues[groupKey];
555
+ grouppedAggregations[groupKey] = {
556
+ 'Max Percent Inhibition': values.maxYs.length ? Math.max(...values.maxYs)?.toString() : null,
557
+ ...(parentData && parentData.table ? {
558
+ 'Number of total results': values.qualifiedIC50s.length?.toString(),
559
+ 'Number of reported results': values.reportedIC50s.length?.toString(),
560
+ 'Geomean IC50': values.reportedIC50s.length ? (Math.exp(values.reportedIC50s.reduce((a, b) => a + Math.log(b), 0) / values.reportedIC50s.length) || null)?.toString() : null, // log based, better for small values
561
+ 'Standard Deviation': values.reportedIC50s.length > 1 ? Math.sqrt(values.reportedIC50s.reduce((a, b) => a + (b - values.reportedIC50s.reduce((c, d) => c + d, 0) / values.reportedIC50s.length) ** 2, 0) / (values.reportedIC50s.length - 1))?.toString() : null,
562
+ 'All Results': values.qualifiedIC50s.join(', ')} : {}),
563
+ };
564
+ }
565
+ const grouppedAggregationsColNames = Object.keys(grouppedAggregations[Object.keys(grouppedAggregations)[0]]);
566
+ for (const colName of grouppedAggregationsColNames) {
567
+ const col = DG.Column.fromStrings(colName, curvesObjsArray.map((c) => grouppedAggregations[c[1].groupKey]?.[colName] ?? ''));
568
+ tableColList.push(col);
569
+ }
570
+
571
+
572
+ const resDF = DG.DataFrame.fromColumns(tableColList);
573
+ resDF.name = 'Fitted Curves';
574
+
575
+ if (!parentData || !parentData.table) {
576
+ const actualStatNames = {
577
+ 'interceptX': 'IC50',
578
+ 'top': 'Max',
579
+ 'bottom': 'Min',
580
+ 'slope': 'Hill',
581
+ 'auc': 'AUC',
582
+ };
583
+
584
+ Object.entries(actualStatNames).forEach(([statName, alias]) => {
585
+ const params = {table: resDF, colName: curvesCol.name, propName: statName, seriesNumber: 0};
586
+ DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(params).callSync({processed: false}).getOutputParamValue().name = alias;
587
+ });
588
+ if (actualStatNames['interceptX'])
589
+ resDF.col(actualStatNames['interceptX']) && (resDF.col(actualStatNames['interceptX'])!.meta.format = 'scientific');
590
+ }
591
+ return resDF;
592
+ };