@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,262 @@
1
+ /* eslint-disable max-len */
2
+ import {AnalysisOptions} from './plate-widget';
3
+
4
+ import * as DG from 'datagrok-api/dg';
5
+ import * as ui from 'datagrok-api/ui';
6
+ import * as grok from 'datagrok-api/grok';
7
+ import {mapFromRow} from './utils';
8
+ import {IPlateWellFilter, Plate, randomizeTableId} from './plate';
9
+ import {FIT_FUNCTION_4PL_REGRESSION, FIT_FUNCTION_SIGMOID, FitMarkerType, IFitPoint} from '@datagrok-libraries/statistics/src/fit/fit-curve';
10
+ import {FitConstants} from '../fit/const';
11
+ import {FitCellOutlierToggleArgs, setOutlier} from '../fit/fit-renderer';
12
+ import {_package} from '../package';
13
+ import {savePlate} from '../plates/plates-crud';
14
+ import {PlateWidget} from './plate-widget';
15
+
16
+
17
+ export class PlateDrcAnalysis {
18
+ static analysisView(plate: Plate, options?: Partial<AnalysisOptions>): PlateWidget {
19
+ const pw = PlateWidget.detailedView(plate);
20
+ const gridRoot = pw.grid.root;
21
+ const detailsRoot = pw.detailsDiv;
22
+ pw.plateActionsDiv = ui.div();
23
+ pw.plateDetailsDiv = ui.div();
24
+ detailsRoot!.prepend(pw.plateDetailsDiv);
25
+ detailsRoot!.append(pw.plateActionsDiv);
26
+ const defaultOptions: AnalysisOptions = {
27
+ roleName: 'layout', concentrationName: 'concentration', valueName: 'readout',
28
+ normalize: true, controlColumns: ['High Control', 'Low Control'], autoFilterOutliers: true,
29
+ categorizeFormula: '${rSquared} > 0.8 && ${Hill} > 0.25 && ${Max} > 80 && ${Max} < 120', statisticsColumns: ['Min', 'Max', 'rSquared', 'Hill', 'IC50', 'AUC'],
30
+ };
31
+
32
+ // system of aliases for the column names
33
+ const aliases = {
34
+ concentrationName: ['conc', 'dose', 'conc.', 'dilution', 'concentrations'],
35
+ valueName: ['response', 'value', 'signal', 'raw data', 'raw signal', 'raw', 'response', 'values'],
36
+ roleName: ['role', 'plate layout', 'plate positions', 'group', 'compound', 'well']
37
+ };
38
+ Object.entries(aliases).forEach(([key, value]) => {
39
+ const colName = defaultOptions[key as keyof typeof defaultOptions] as string;
40
+ if (plate.data.columns.contains(colName))
41
+ return;
42
+ const alias = value.find((v) => plate.data.columns.contains(v));
43
+ if (alias)
44
+ (defaultOptions[key as keyof typeof defaultOptions] as string) = alias;
45
+ });
46
+
47
+ // find control columns
48
+ if (plate.data.columns.contains(defaultOptions.roleName) && !defaultOptions.controlColumns.every((cc) => plate.data.col(defaultOptions.roleName)!.categories.includes(cc))) {
49
+ // if control columns are not provided, try to find them in the data
50
+ const controlCols = plate.data.col(defaultOptions.roleName)!.categories.filter((cat) => cat.toLowerCase().includes('control'));
51
+ // take maximum of 2 control columns
52
+ defaultOptions.controlColumns = controlCols.slice(0, 2);
53
+ }
54
+
55
+ const actOptions: AnalysisOptions & {normalizedColName?: string} = {...defaultOptions, ...options};
56
+
57
+ const statisticsAliases = {
58
+ 'rSquared': ['rsquared', 'r2', 'r squared', 'r^2'],
59
+ 'slope': ['slope', 'hill', 'steepness', 'hill slope'],
60
+ 'bottom': ['bottom', 'min', 'minimum', 'miny', 'min y'],
61
+ 'top': ['top', 'max', 'maximum', 'maxy', 'max y'],
62
+ 'interceptX': ['interceptx', 'intercept x', 'ic50', 'ic 50', 'ic-50', 'ic_50', 'ic 50 value', 'ic50 value', 'ic50value', 'ec50', 'ec 50', 'ec-50', 'ec_50', 'ec 50 value', 'ec50 value', 'ec50value'],
63
+ 'auc': ['auc', 'area under the curve', 'area under curve', 'area'],
64
+ };
65
+
66
+ const actualStatNames: Record<string, string> = {}; // will hold actual statistic name to its alias column name
67
+ actOptions.statisticsColumns.forEach((stat) => {
68
+ const alias = Object.entries(statisticsAliases).find(([_, aliases]) => aliases.includes(stat.toLowerCase()));
69
+ if (alias)
70
+ actualStatNames[alias[0]] = stat;
71
+ });
72
+
73
+
74
+ if (!gridRoot || !detailsRoot)
75
+ return pw;
76
+ // place them horizontally
77
+ const container = ui.divH([gridRoot, detailsRoot]);
78
+ pw.tabsContainer.appendChild(container);
79
+ detailsRoot.style.flex = '0 0 min(250px, 25%)';
80
+ gridRoot.style.flexGrow = '1';
81
+ gridRoot.style.removeProperty('width');
82
+
83
+ const drFilterOptions: IPlateWellFilter = {exclude: {[actOptions.roleName]: actOptions.controlColumns}};
84
+ let normed = false;
85
+ if (actOptions.normalize && actOptions.controlColumns.length === 2) {
86
+ const [lStats, hStats] = actOptions.controlColumns.map((colName) => {
87
+ return plate.getStatistics(actOptions.valueName, ['mean', 'std'], {match: {[actOptions.roleName]: colName}});
88
+ }).sort((a, b) => a.mean - b.mean);
89
+
90
+ defaultOptions.plateStatistics = {
91
+ 'Z Prime': (_plate) => 1 - (3 * (hStats.std + lStats.std) / Math.abs(hStats.mean - lStats.mean)),
92
+ 'Signal to background': (_plate) => hStats.mean / lStats.mean,
93
+ };
94
+ if (!actOptions.plateStatistics)
95
+ actOptions.plateStatistics = defaultOptions.plateStatistics;
96
+ actOptions.normalizedColName = plate.normalize(actOptions.valueName, (v) => (hStats.mean - v) / (hStats.mean - lStats.mean) * 100).name;
97
+ normed = true;
98
+ const plateStatMap: Record<string, string> = {};
99
+ Object.entries(actOptions.plateStatistics).forEach(([statName, statFunc]) => {
100
+ const value = statFunc(plate);
101
+ plateStatMap[statName] = typeof value === 'number' ? DG.format(value, '#0.0000') : value;
102
+ });
103
+ const statTable = ui.tableFromMap(plateStatMap);
104
+ pw.plateDetailsDiv!.appendChild(statTable);
105
+ // mark outliers that go outside the bounds
106
+
107
+ if (actOptions.autoFilterOutliers)
108
+ plate.markOutliersWhere(actOptions.normalizedColName!, (v) => v > 106 || v < -6, drFilterOptions);
109
+ }
110
+
111
+ const series = plate.doseResponseSeries({...drFilterOptions, value: normed ? actOptions.normalizedColName! : actOptions.valueName, concentration: actOptions.concentrationName, groupBy: actOptions.roleName});
112
+ const seriesVals = Object.entries(series);
113
+ const minMax = normed ? {minY: -10, maxY: 110} : 0;
114
+ const roleCol = DG.Column.string(actOptions.roleName, seriesVals.length);
115
+ const curveCol = DG.Column.string('Curve', seriesVals.length);
116
+ curveCol.init((i) => JSON.stringify(
117
+ {
118
+ 'chartOptions': {
119
+ 'xAxisName': actOptions.concentrationName,
120
+ 'yAxisName': normed ? `norm(${actOptions.valueName})` : actOptions.valueName,
121
+ 'logX': true,
122
+ 'title': `${seriesVals[i][0]}`,
123
+ ...minMax
124
+ },
125
+ // TODO: change to 4PL regression once fixed for normed data
126
+ 'series': [{...seriesVals[i][1], fit: undefined, fitFunction: FIT_FUNCTION_4PL_REGRESSION, clickToToggle: true, droplines: ['IC50'], name: seriesVals[i][0]}]
127
+ }
128
+
129
+ ));
130
+ roleCol.init((i) => seriesVals[i][0]);
131
+
132
+ const df = DG.DataFrame.fromColumns([roleCol, curveCol]);
133
+ df.name = pw.plate.data.name;
134
+ df.id = randomizeTableId();
135
+
136
+ curveCol.semType ='fit';
137
+ const curvesGrid = df.plot.grid();
138
+
139
+ // add statistics columns
140
+ Object.entries(actualStatNames).forEach(([statName, alias]) => {
141
+ const params = {table: df, colName: curveCol.name, propName: statName, seriesNumber: 0};
142
+ const col: DG.Column = ( DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(params).callSync({processed: false})).getOutputParamValue();
143
+ col.name = alias;
144
+ });
145
+ if (actualStatNames['interceptX'])
146
+ df.col(actualStatNames['interceptX']) && (df.col(actualStatNames['interceptX'])!.meta.format = 'scientific');
147
+
148
+ //categorize the curves
149
+
150
+ const criteriaCol = df.columns.addNewString(df.columns.getUnusedName('Criteria'));
151
+ criteriaCol.applyFormula(`if(${actOptions.categorizeFormula}, "Qualified", "Fails Criteria")`, DG.COLUMN_TYPE.STRING);
152
+ criteriaCol.meta.colors.setCategorical({'Fails Criteria': 4294922560, 'Qualified': 4283477800});
153
+
154
+ curvesGrid.root.style.width = '100%';
155
+ pw.root.style.display = 'flex';
156
+ pw.root.style.flexDirection = 'column';
157
+ pw.root.style.height = '100%';
158
+
159
+ pw.root.appendChild(curvesGrid.root);
160
+
161
+ // when selecting a cell on plate, go to appropriate curve and mark the corresponding point with different marker
162
+ // remember the previous change, so that we can revert it
163
+ let prevSelection: {seriesIndex: number, pointIndex: number, markerType: FitMarkerType, markerSize: number, markerColor: string, curvesGridCell?: DG.GridCell} | null = null;
164
+
165
+ pw.mapFromRowFunc = (row) => mapFromRow(row, (rowIdx, checkBoxState) => {
166
+ plate._markOutlier(rowIdx, checkBoxState);
167
+ if (prevSelection && prevSelection.curvesGridCell)
168
+ setOutlier(prevSelection.curvesGridCell, {x: 0, y: 0, outlier: !checkBoxState}, 0, prevSelection.pointIndex);
169
+ pw.grid.invalidate();
170
+ });
171
+
172
+ function clearPreviousSelection() {
173
+ try {
174
+ if (!prevSelection || (prevSelection.seriesIndex ?? -1) < 0)
175
+ return;
176
+
177
+ const series = curveCol.get(prevSelection.seriesIndex);
178
+ if (!series)
179
+ return;
180
+ const parsed = JSON.parse(series);
181
+ const points: IFitPoint[] = parsed.series[0]?.points;
182
+ if (points && points.length && points.length > prevSelection.pointIndex) {
183
+ points[prevSelection.pointIndex].marker = prevSelection.markerType;
184
+ points[prevSelection.pointIndex].size = prevSelection.markerSize;
185
+ points[prevSelection.pointIndex].color = prevSelection.markerColor;
186
+ curveCol.set(prevSelection.seriesIndex, JSON.stringify(parsed));
187
+ }
188
+ } catch (e) {
189
+ console.error(e);
190
+ } finally {
191
+ prevSelection = null;
192
+ }
193
+ }
194
+
195
+ // highlight selected point in the curve
196
+ pw.subs.push(pw.grid.onCurrentCellChanged.subscribe((gc) => {
197
+ clearPreviousSelection();
198
+ if (gc?.gridRow == null || gc?.gridRow == -1 || !gc?.gridColumn || gc?.gridColumn.idx == 0)
199
+ return;
200
+ const row = pw.plate._idx(gc.gridRow, gc.gridColumn.idx - 1);
201
+ if (row == undefined || row < 0)
202
+ return;
203
+ const catValue = pw.plate.data.get(actOptions.roleName, row)?.toLowerCase();
204
+ if (!catValue)
205
+ return;
206
+ const seriesIndex = seriesVals.findIndex(([serName, _]) => serName?.toLowerCase() === catValue);
207
+ if (seriesIndex < 0)
208
+ return;
209
+ const conscentration: number = pw.plate.data.get(actOptions.concentrationName, row);
210
+ const value: number = pw.plate.data.get(normed ? actOptions.normalizedColName! : actOptions.valueName, row);
211
+
212
+ const pointInSeriesIndex: number = seriesVals[seriesIndex][1].points.findIndex((p) => p.x === conscentration && p.y === value);
213
+ if (pointInSeriesIndex < 0)
214
+ return;
215
+
216
+ prevSelection = {seriesIndex, pointIndex: pointInSeriesIndex, markerType: seriesVals[seriesIndex][1].points[pointInSeriesIndex].marker ?? DG.MARKER_TYPE.CIRCLE,
217
+ markerSize: seriesVals[seriesIndex][1].points[pointInSeriesIndex].size ?? FitConstants.POINT_PX_SIZE, markerColor: seriesVals[seriesIndex][1].points[pointInSeriesIndex].color ?? DG.Color.toHtml(DG.Color.getCategoricalColor(0))};
218
+
219
+ const curveJSON = JSON.parse(curveCol.get(seriesIndex)!);
220
+ const points: IFitPoint[] = curveJSON.series[0]?.points;
221
+ if (points && points.length && points.length > pointInSeriesIndex) {
222
+ points[pointInSeriesIndex].marker = DG.MARKER_TYPE.SQUARE;
223
+ points[pointInSeriesIndex].size = FitConstants.POINT_PX_SIZE * 2;
224
+ points[pointInSeriesIndex].color = DG.Color.toHtml(DG.Color.green);
225
+ curveCol.set(seriesIndex, JSON.stringify(curveJSON));
226
+ }
227
+
228
+ // scroll in grid
229
+ const curveGridRow = curvesGrid.tableRowToGrid(seriesIndex);
230
+ prevSelection.curvesGridCell = curvesGrid.cell(curveCol.name, curveGridRow);
231
+ prevSelection.curvesGridCell && curvesGrid.scrollToCell(curveCol.name, curveGridRow);
232
+ }));
233
+
234
+ // mark outliers in the original plate if it is switched from curve manually
235
+
236
+ pw.subs.push(grok.events.onCustomEvent('fit-cell-outlier-toggle').subscribe((args: FitCellOutlierToggleArgs) => {
237
+ if (!args || !args.gridCell || !args.series || args.pointIdx == null || args.gridCell.cell.column !== curveCol)
238
+ return;
239
+ const point: IFitPoint = args.series.points[args.pointIdx];
240
+ if (point.meta !== null) {
241
+ plate._markOutlier(point.meta, !!point.outlier);
242
+ pw.grid.invalidate();
243
+ }
244
+ }));
245
+
246
+
247
+ const s = DG.debounce(curvesGrid.onAfterDrawContent, 300).subscribe(() => {
248
+ s.unsubscribe();
249
+ curvesGrid.col(curveCol.name) && (curvesGrid.col(curveCol.name)!.width = 400);
250
+ curvesGrid.props.rowHeight = 200;
251
+ });
252
+
253
+ if (actOptions.submitAction) {
254
+ const btn = ui.button('Save to ELN', () => {
255
+ savePlate(plate).then((_) => grok.shell.info('Plate saved'));
256
+ //actOptions.submitAction!(plate, df);
257
+ });
258
+ pw.plateActionsDiv!.appendChild(btn);
259
+ }
260
+ return pw;
261
+ }
262
+ }
@@ -1,8 +1,8 @@
1
- import {Plate} from "./plate";
2
- import {BmgPherastar96PlateReader} from "./readers/bmg-pherastar-96";
3
- import {DelfiaEnvision96MaxRluPlateReader} from "./readers/delfia-envision-96-max-rlu";
4
- import {SpectramaxPlateReader} from "./readers/spectramax";
5
- import {DelfiaEnvisionByRowPlateReader} from "./readers/delfia-envision-by-row";
1
+ import {Plate} from './plate';
2
+ import {BmgPherastar96PlateReader} from './readers/bmg-pherastar-96';
3
+ import {DelfiaEnvision96MaxRluPlateReader} from './readers/delfia-envision-96-max-rlu';
4
+ import {SpectramaxPlateReader} from './readers/spectramax';
5
+ import {DelfiaEnvisionByRowPlateReader} from './readers/delfia-envision-by-row';
6
6
 
7
7
  export interface IPlateReader {
8
8
  isApplicable(s: string): boolean;
@@ -0,0 +1,41 @@
1
+ import { Plate } from "./plate";
2
+
3
+ export interface IPlateWellValidator {
4
+ name: string;
5
+ description: string;
6
+ validate(plate: Plate, row: number, col: number): string | null;
7
+ }
8
+
9
+ export const plateWellValidators: IPlateWellValidator[] = [
10
+ {
11
+ name: 'Concentration and volume go together',
12
+ description: 'Concentration and volume should either be both present or both absent',
13
+ validate: (plate: Plate, row: number, col: number) => {
14
+ if (!plate.data.col('concentration') || !plate.data.col('volume'))
15
+ return null;
16
+
17
+ const concentration = plate.get('concentration', row, col);
18
+ const volume = plate.get('volume', row, col);
19
+
20
+ if ((concentration && !volume) || (!concentration && volume))
21
+ return 'Concentration and volume should either be both present or both absent';
22
+
23
+ return null;
24
+ },
25
+ },
26
+
27
+ {
28
+ name: 'Concentration is not negative',
29
+ description: 'Concentration should not be negative',
30
+ validate: (plate: Plate, row: number, col: number) => {
31
+ if (!plate.data.col('concentration'))
32
+ return null;
33
+
34
+ const concentration = plate.get('concentration', row, col);
35
+ if (concentration != null && concentration < 0)
36
+ return 'Concentration should not be negative';
37
+
38
+ return null;
39
+ },
40
+ },
41
+ ];