@datagrok/curves 1.8.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.
Files changed (55) hide show
  1. package/.eslintrc.json +39 -0
  2. package/.vscode/launch.json +10 -9
  3. package/.vscode/tasks.json +14 -0
  4. package/CHANGELOG.md +39 -0
  5. package/databases/plates/0000_init.sql +167 -0
  6. package/detectors.js +18 -2
  7. package/dist/package-test.js +16647 -1
  8. package/dist/package-test.js.map +1 -1
  9. package/dist/package.js +14467 -1
  10. package/dist/package.js.map +1 -1
  11. package/package.json +13 -9
  12. package/queries/plates-crud.sql +148 -0
  13. package/src/fit/const.ts +60 -60
  14. package/src/fit/data-to-curves.ts +592 -0
  15. package/src/fit/fit-demo.ts +6 -6
  16. package/src/fit/fit-grid-cell-handler.ts +49 -45
  17. package/src/fit/fit-renderer.ts +58 -57
  18. package/src/fit/multi-curve-viewer.ts +43 -21
  19. package/src/fit/render-utils.ts +315 -315
  20. package/src/package-api.ts +179 -0
  21. package/src/package-test.ts +1 -1
  22. package/src/package.g.ts +171 -3
  23. package/src/package.ts +227 -298
  24. package/src/plate/excel-plates.ts +1 -1
  25. package/src/plate/plate-cell-renderer.ts +20 -12
  26. package/src/plate/plate-drc-analysis.ts +262 -0
  27. package/src/plate/plate-reader.ts +5 -5
  28. package/src/plate/plate-well-validators.ts +41 -0
  29. package/src/plate/plate-widget.ts +132 -368
  30. package/src/plate/plate.ts +168 -57
  31. package/src/plate/plates-folder-preview.ts +63 -0
  32. package/src/plate/readers/bmg-pherastar-96.ts +7 -7
  33. package/src/plate/readers/delfia-envision-96-max-rlu.ts +4 -3
  34. package/src/plate/readers/delfia-envision-by-row.ts +3 -3
  35. package/src/plate/readers/spectramax.ts +7 -8
  36. package/src/plate/utils.ts +22 -10
  37. package/src/plates/numeric_matcher.ts +191 -0
  38. package/src/plates/objects/plate-template-handler.ts +48 -0
  39. package/src/plates/plates-app.ts +64 -0
  40. package/src/plates/plates-crud.ts +502 -0
  41. package/src/plates/plates-demo.ts +107 -0
  42. package/src/plates/plates.sql +169 -0
  43. package/src/plates/views/plates-create-view.ts +123 -0
  44. package/src/plates/views/plates-schema-view.ts +58 -0
  45. package/src/plates/views/plates-search-view.ts +137 -0
  46. package/src/plates/views/plates-templates-view.ts +37 -0
  47. package/src/pngRenderer.ts +98 -0
  48. package/src/tests/curves-cell-renderer-tests.ts +93 -92
  49. package/src/tests/detector-tests.ts +3 -2
  50. package/src/tests/fit-tests.ts +199 -198
  51. package/src/tests/plate-tests.ts +6 -7
  52. package/src/tests/transform-tests.ts +4 -4
  53. package/test-console-output-1.log +436 -0
  54. package/test-record-1.mp4 +0 -0
  55. package/tsconfig.json +1 -1
@@ -0,0 +1,592 @@
1
+ /* eslint-disable max-len */
2
+
3
+ import {FIT_FUNCTION_4PL_DOSE_RESPONSE, FIT_FUNCTION_4PL_REGRESSION, FitChartData, FitMarkerType, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
4
+ import * as DG from 'datagrok-api/dg';
5
+ import * as grok from 'datagrok-api/grok';
6
+ import * as ui from 'datagrok-api/ui';
7
+ import * as api from '../package-api';
8
+ import wu from 'wu';
9
+ import {FitFunctionType, FitFunctionTypes} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
10
+
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;
35
+ }
36
+ return inputs;
37
+ }
38
+
39
+ export type FitFunctionEditorHistory = {
40
+ fitParamCols: string[],
41
+ fitFunction: FitFunctionType,
42
+ useFitParamCols: boolean
43
+ }
44
+
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
+ }
89
+ }
90
+ }
91
+ };
92
+ }
93
+
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;
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]);
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;
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);
175
+ }
176
+ };
177
+ }
178
+
179
+
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([]);
191
+
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'});
203
+
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]);
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'}});
252
+
253
+ ui.dialog('Data to Curves')
254
+ .add(horzForm)
255
+ .onOK(async () => {
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',
313
+ showControlPanel: false, showXLabels: false, showYLabels: false, showXSelectors: false, showYSelectors: true, packCategories: true,
314
+ onClick: 'Select'
315
+ });
316
+ tv.dockManager.dock(trellis, DG.DOCK_TYPE.TOP, tv.dockManager.findNode(tv.grid.root), 'Fitted Curves', 0.5);
317
+ const selectionGrid = tv.addViewer(DG.VIEWER.GRID, {rowSource: 'Selected', selectedRowsColor: DG.Color.white});
318
+ tv.dockManager.dock(selectionGrid, DG.DOCK_TYPE.FILL, tv.dockManager.findNode(tv.grid.root), 'Selected Curves');
319
+ selectionGrid.props.title = 'Selected Curves';
320
+
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';
325
+ }
326
+ })
327
+ .show()
328
+ .history(() => {
329
+ const formRes = wellLevelForm.getValues();
330
+ const {assayCol, batchIDCol, concentrationCol, readoutCol, compoundIDCol, excludeOutliersCol, runIDCol, targetEntityCol} = formRes;
331
+ const obj = {
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,
340
+ };
341
+ return {wells: JSON.stringify(Object.fromEntries(Object.entries(obj).filter(([_, v]) => !!v)) ?? {}), parent: JSON.stringify(parentTableForm.getHistory() ?? {})};
342
+ }, (v) => {
343
+ const wells = JSON.parse(v?.wells ?? '{}');
344
+ const parent = JSON.parse(v?.parent ?? '{}');
345
+ wellLevelForm.applyHistory(wells);
346
+ parentTableForm.applyHistory(parent);
347
+ });
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
+ };
@@ -7,7 +7,7 @@ import {_package} from '../package';
7
7
  import {IFitChartData, sigmoid} from '@datagrok-libraries/statistics/src/fit/fit-curve';
8
8
 
9
9
  import wu from 'wu';
10
- import {FitConstants} from "./const";
10
+ import {FitConstants} from './const';
11
11
 
12
12
  /** Returns random number from the interval */
13
13
  function rnd(min: number, max: number): number {
@@ -36,9 +36,9 @@ export function createSigmoidPoints(length: number, step: number, pointsPerX: nu
36
36
  // adding 20% noise
37
37
  const range = (pointsPerX === 1 ? 0.2 : 0.4) * (Math.max(...y) - Math.min(...y));
38
38
  const minY = Math.min(...y);
39
- for (let i = 0; i < x.length; i++) {
39
+ for (let i = 0; i < x.length; i++)
40
40
  y[i] = -minY + y[i] + rnd(0, range);
41
- }
41
+
42
42
 
43
43
  return {x: x, y: y, params: params};
44
44
  }
@@ -65,7 +65,7 @@ export function createDemoDataFrame(rowCount: number, chartsCount: number, chart
65
65
 
66
66
  const jsonColumn = df.columns.addNewString(`json chart ${colIdx}`); // charts as json
67
67
  jsonColumn.semType = FitConstants.FIT_SEM_TYPE;
68
- let charts = colIdx % 2 === 0 ? chartsPerCell : 1;
68
+ const charts = colIdx % 2 === 0 ? chartsPerCell : 1;
69
69
 
70
70
  for (let i = 0; i < rowCount; i++) {
71
71
  const chartData: IFitChartData = {
@@ -81,7 +81,7 @@ export function createDemoDataFrame(rowCount: number, chartsCount: number, chart
81
81
 
82
82
  for (let j = 0; j < charts; j++) {
83
83
  const points = createSigmoidPoints(seriesLength, step, pointsPerX);
84
- let color = DG.Color.toHtml(DG.Color.getCategoricalColor(colIdx * chartsPerCell + j));
84
+ const color = DG.Color.toHtml(DG.Color.getCategoricalColor(colIdx * chartsPerCell + j));
85
85
  chartData.series?.push({
86
86
  parameters: undefined,
87
87
  // TODO: make better parameter generating
@@ -105,6 +105,6 @@ export async function curveDemo(): Promise<void> {
105
105
  grok.shell.windows.showContextPanel = true;
106
106
  // const df = createDemoDataFrame(30, 5, 2);
107
107
  const df = await grok.data.loadTable(`${_package.webRoot}files/curves-demo.csv`);
108
- const tableView = grok.shell.addTableView(df);
108
+ const _tableView = grok.shell.addTableView(df);
109
109
  // tableView.addViewer('MultiCurveViewer');
110
110
  }