@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
@@ -1,16 +1,14 @@
1
+ /* eslint-disable max-len */
1
2
  import * as DG from 'datagrok-api/dg';
3
+ import {MARKER_TYPE, TYPE} from 'datagrok-api/dg';
2
4
  import * as ui from 'datagrok-api/ui';
3
- import * as grok from 'datagrok-api/grok';
4
- import {TYPE} from "datagrok-api/dg";
5
- import {div} from "datagrok-api/ui";
6
- import {safeLog, mapFromRow } from './utils';
7
- import {IPlateWellFilter, Plate, PLATE_OUTLIER_WELL_NAME, randomizeTableId} from './plate';
5
+ import {div} from 'datagrok-api/ui';
6
+ import {mapFromRow, safeLog, toExcelPosition} from './utils';
7
+ import {Plate, PLATE_OUTLIER_WELL_NAME} from './plate';
8
8
  //@ts-ignore
9
9
  import * as jStat from 'jstat';
10
- import {FIT_FUNCTION_4PL_REGRESSION, FIT_FUNCTION_SIGMOID, FitMarkerType, IFitPoint} from '@datagrok-libraries/statistics/src/fit/fit-curve';
11
- import { FitConstants } from '../fit/const';
12
- import {FitCellOutlierToggleArgs, setOutlier} from '../fit/fit-renderer';
13
- import { _package } from '../package';
10
+ import {IPlateWellValidator, plateWellValidators} from './plate-well-validators';
11
+ import {debounceTime, filter} from 'rxjs/operators';
14
12
 
15
13
 
16
14
  export type AnalysisOptions = {
@@ -34,390 +32,198 @@ export const dimensions = new Map([
34
32
  [1536, {rows: 32, cols: 48}],
35
33
  ]);
36
34
 
35
+ /** Visualizes multiple layers of {@link Plate} in tabbed interface and lets you edit it */
37
36
  export class PlateWidget extends DG.Widget {
38
- _plateData: DG.DataFrame = DG.DataFrame.create();
39
- _colorColumn?: DG.Column;
40
- grid: DG.Grid = DG.Viewer.heatMap(this._plateData);
41
- _posToRow: Map<String, number> = new Map();
42
- rows = 0;
43
- cols = 0;
37
+ _colorColumn?: DG.Column | undefined;
38
+ _plate: Plate = new Plate(8, 12);
39
+ grid: DG.Grid = DG.Viewer.heatMap(DG.DataFrame.create());
44
40
  colorColumnName: string = '';
45
41
  colorSelector?: DG.InputBase;
46
42
  detailsDiv?: HTMLElement;
47
43
  wellDetailsDiv?: HTMLElement;
48
44
  plateDetailsDiv?: HTMLElement;
49
45
  plateActionsDiv?: HTMLElement;
46
+ tabs: DG.TabControl = DG.TabControl.create();
47
+ tabsContainer: HTMLElement = ui.divH([], 'curves-plate-tabs-container');
48
+ _editable: boolean = false;
50
49
  mapFromRowFunc: (row: DG.Row) => Record<string, any> = mapFromRow;
50
+ grids: Map<string, DG.Grid> = new Map();
51
+ wellValidators: IPlateWellValidator[] = plateWellValidators;
52
+ wellValidationErrors: Map<string, string[]> = new Map();
53
+
54
+ get editable() { return this._editable; }
55
+ set editable(x: boolean) {
56
+ this._editable = x;
57
+ this.syncGrids();
58
+ }
51
59
 
52
60
  constructor() {
53
61
  super(ui.div([], 'curves-plate-widget'));
54
- this.root.appendChild(this.grid.root);
55
-
56
- this.subs.push(this.grid.onAfterDrawContent.subscribe(() => {
57
- this.grid.root.querySelectorAll('.d4-range-selector').forEach((el) => (el as HTMLElement).style.display = 'none');
58
- }));
59
62
 
60
- this.grid.onCellRender.subscribe((args) => this.renderCell(args));
63
+ this.tabs.root.style.flexGrow = '1';
64
+ // this.tabs.root.style.height = '100%';
65
+ //this.tabs.addPane('Summary', () => this.grid.root);
66
+
67
+ this.tabsContainer.appendChild(this.tabs.root);
68
+ this.root.appendChild(this.tabsContainer);
69
+
70
+ this.grid.props.showHeatmapScrollbars = false;
71
+ this.grid.props.colHeaderHeight = 30;
72
+ this.grid.onCellRender.subscribe((args) => this.renderCell(args, true));
73
+ this.grid.onCellRendered.subscribe((args) => {
74
+ const cell = args.cell;
75
+ if (cell.gridRow >= 0 && cell.gridColumn.idx > 0) {
76
+ try {
77
+ const pos = toExcelPosition(cell.gridRow, cell.gridColumn.idx - 1);
78
+ const errors = this.wellValidationErrors.get(pos);
79
+ if (errors && errors.length > 0)
80
+ DG.Paint.marker(args.g, DG.MARKER_TYPE.CROSS_BORDER, cell.bounds.midX, cell.bounds.midY, DG.Color.red, 10);
81
+ } catch (e) {
82
+ console.error(e);
83
+ }
84
+ }
85
+ });
61
86
  }
62
87
 
63
88
  static fromPlate(plate: Plate) {
64
- return PlateWidget.detailedView(plate.data);
89
+ return PlateWidget.detailedView(plate);
65
90
  }
66
91
 
67
- static detailedView(table: DG.DataFrame): PlateWidget {
92
+ static detailedView(plate: Plate): PlateWidget {
68
93
  const pw = new PlateWidget();
69
94
  pw.grid.root.style.width = '100%';
70
- pw.plateData = table;
95
+ pw.plate = plate;
71
96
  pw.colorSelector = ui.input.column('Color by', {
72
- table: table,
97
+ table: plate.data,
73
98
  value: pw._colorColumn,
74
99
  onValueChanged: (v) => { pw._colorColumn = v; pw.grid.invalidate(); }
75
100
  });
76
101
  pw.detailsDiv = ui.divV([]);
77
102
  pw.wellDetailsDiv = div();
78
103
  pw.detailsDiv.appendChild(pw.wellDetailsDiv!);
79
- pw.grid.onCurrentCellChanged.subscribe((gc) => {
104
+ pw.grid.onCurrentCellChanged.pipe(filter((gc) => gc.gridRow >= 0 && gc.gridColumn.idx > 0)).subscribe((gc) => {
80
105
  ui.empty(pw.wellDetailsDiv!);
81
- const row = pw.dataRow(gc);
82
- if (row != null && row >= 0)
83
- pw.wellDetailsDiv!.appendChild(ui.tableFromMap(pw.mapFromRowFunc(pw.plateData.rows.get(row))));
106
+ const map = pw.mapFromRowFunc(pw.plate.data.rows.get(plate._idx(gc.gridRow, gc.gridColumn.idx - 1)));
107
+ pw.wellDetailsDiv!.appendChild(ui.tableFromMap(map));
84
108
  });
85
109
 
86
110
  pw.root.prepend(pw.colorSelector.root);
87
- pw.root.append(pw.detailsDiv);
111
+ pw.tabsContainer.appendChild(pw.detailsDiv);
88
112
  return pw;
89
113
  }
90
114
 
91
- static analysisView(plate: Plate, options?: Partial<AnalysisOptions>): PlateWidget {
92
- const pw = PlateWidget.detailedView(plate.data);
93
- const gridRoot = pw.grid.root;
94
- const detailsRoot = pw.detailsDiv;
95
- pw.plateActionsDiv = ui.div();
96
- pw.plateDetailsDiv = ui.div();
97
- detailsRoot!.prepend(pw.plateDetailsDiv);
98
- detailsRoot!.append(pw.plateActionsDiv);
99
- const defaultOptions: AnalysisOptions = {
100
- roleName: 'layout', concentrationName: 'concentration', valueName: 'readout',
101
- normalize: true, controlColumns: ['High Control', 'Low Control'], autoFilterOutliers: true,
102
- categorizeFormula: '${rSquared} > 0.8 && ${Hill} > 0.25 && ${Max} > 80 && ${Max} < 120', statisticsColumns: ['Min', 'Max', 'rSquared', 'Hill', 'IC50', 'AUC'],
103
- };
104
-
105
- // system of aliases for the column names
106
- const aliases = {
107
- concentrationName: ['conc', 'dose', 'conc.', 'dilution', 'concentrations'],
108
- valueName: ['response', 'value', 'signal', 'raw data', 'raw signal', 'raw', 'response', 'values'],
109
- roleName: ['role', 'plate layout', 'plate positions', 'group', 'compound', 'well']
110
- };
111
- Object.entries(aliases).forEach(([key , value]) => {
112
- const colName = defaultOptions[key as keyof typeof defaultOptions] as string;
113
- if (plate.data.columns.contains(colName))
114
- return;
115
- const alias = value.find((v) => plate.data.columns.contains(v));
116
- if (alias)
117
- (defaultOptions[key as keyof typeof defaultOptions] as string) = alias;
118
- })
119
-
120
- // find control columns
121
- if (plate.data.columns.contains(defaultOptions.roleName) && !defaultOptions.controlColumns.every((cc) => plate.data.col(defaultOptions.roleName)!.categories.includes(cc))) {
122
- // if control columns are not provided, try to find them in the data
123
- const controlCols = plate.data.col(defaultOptions.roleName)!.categories.filter((cat) => cat.toLowerCase().includes('control'));
124
- // take maximum of 2 control columns
125
- defaultOptions.controlColumns = controlCols.slice(0, 2);
126
- }
127
-
128
- const actOptions: AnalysisOptions & {normalizedColName?: string} = {...defaultOptions, ...options};
129
-
130
- const statisticsAliases = {
131
- 'rSquared': ['rsquared', 'r2', 'r squared', 'r^2'],
132
- 'slope': ['slope', 'hill', 'steepness', 'hill slope'],
133
- 'bottom': ['bottom', 'min', 'minimum', 'miny', 'min y'],
134
- 'top': ['top', 'max', 'maximum', 'maxy', 'max y'],
135
- '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'],
136
- 'auc': ['auc', 'area under the curve', 'area under curve', 'area'],
137
- };
138
-
139
- const actualStatNames: Record<string, string> = {}; // will hold actual statistic name to its alias column name
140
- actOptions.statisticsColumns.forEach((stat) => {
141
- const alias = Object.entries(statisticsAliases).find(([_, aliases]) => aliases.includes(stat.toLowerCase()));
142
- if (alias)
143
- actualStatNames[alias[0]] = stat;
144
- });
145
-
146
-
147
- if (!gridRoot || !detailsRoot)
148
- return pw;
149
- // place them horizontally
150
- const container = ui.divH([gridRoot, detailsRoot]);
151
- pw.root.appendChild(container);
152
- detailsRoot.style.flex = '0 0 min(250px, 25%)';
153
- gridRoot.style.flexGrow = '1';
154
- gridRoot.style.removeProperty('width');
155
-
156
- const drFilterOptions: IPlateWellFilter = {exclude: {[actOptions.roleName]: actOptions.controlColumns}};
157
- let normed = false;
158
- if (actOptions.normalize && actOptions.controlColumns.length === 2) {
115
+ initPlateGrid(grid: DG.Grid, isSummary: boolean = false) {
116
+ grid.props.showHeatmapScrollbars = false;
117
+ grid.props.allowColReordering = false;
118
+ grid.props.allowRowReordering = false;
119
+ grid.props.allowSorting = false;
120
+ grid.props.allowEdit = !isSummary;
121
+ grid.props.showRowGridlines = true;
122
+ grid.props.showColumnGridlines = true;
123
+ grid.props.heatmapColors = false;
124
+ grid.props.colHeaderHeight = 25;
125
+
126
+ grid.onCellRender.subscribe((args) => this.renderCell(args, isSummary));
127
+ }
159
128
 
160
- const [lStats, hStats] = actOptions.controlColumns.map((colName) => {
161
- return plate.getStatistics(actOptions.valueName, ['mean', 'std'], {match: {[actOptions.roleName]: colName}});
162
- }).sort((a,b) => a.mean - b.mean);
129
+ get plate(): Plate { return this._plate; }
130
+ set plate(p: Plate) {
131
+ this._plate = p;
132
+ this.refresh();
133
+ }
163
134
 
164
- defaultOptions.plateStatistics = {
165
- 'Z Prime': (_plate) => 1 - (3 * (hStats.std + lStats.std) / Math.abs(hStats.mean - lStats.mean)),
166
- 'Signal to background': (_plate) => hStats.mean / lStats.mean,
167
- }
168
- if (!actOptions.plateStatistics)
169
- actOptions.plateStatistics = defaultOptions.plateStatistics;
170
- actOptions.normalizedColName = plate.normalize(actOptions.valueName, (v) => (hStats.mean - v) / (hStats.mean - lStats.mean) * 100).name;
171
- normed = true;
172
- const plateStatMap: Record<string, string> = {};
173
- Object.entries(actOptions.plateStatistics).forEach(([statName, statFunc]) => {
174
- const value = statFunc(plate);
175
- plateStatMap[statName] = typeof value === 'number' ? DG.format(value, '#0.0000') : value;
135
+ /** Re-renders the UI */
136
+ refresh() {
137
+ this.tabs.clear();
138
+ this.tabs.addPane('Summary', () => this.grid.root);
139
+ for (const layer of this.plate.getLayerNames()) {
140
+ this.tabs.addPane(layer, () => {
141
+ const df = this.plate.toGridDataFrame(layer);
142
+ const grid = DG.Viewer.heatMap(df);
143
+ grid.columns.add({gridColumnName: '0', cellType: 'string', index: 1}); // to show row numbers in Excel format - will be done in initPlateGrid
144
+ df.onValuesChanged.pipe(debounceTime(1000)).subscribe(() => {
145
+ const p = this.plate;
146
+ for (let i = 0; i < df.rowCount; i++) {
147
+ for (let j = 0; j < df.columns.length - 1; j++)
148
+ p.data.col(layer)!.set(p._idx(i, j), df.get(`${j + 1}`, i));
149
+ }
150
+ this.wellValidationErrors = p.validateWells(this.wellValidators);
151
+ });
152
+ this.initPlateGrid(grid, false);
153
+ this.grids.set(layer, grid);
154
+ return grid.root;
176
155
  });
177
- const statTable = ui.tableFromMap(plateStatMap);
178
- pw.plateDetailsDiv!.appendChild(statTable);
179
- // mark outliers that go outside the bounds
180
-
181
- if (actOptions.autoFilterOutliers) {
182
- plate.markOutliersWhere(actOptions.normalizedColName!, (v) => v > 106 || v < -6, drFilterOptions);
183
- }
184
- }
185
-
186
- const series = plate.doseResponseSeries({...drFilterOptions, value: normed ? actOptions.normalizedColName! : actOptions.valueName , concentration: actOptions.concentrationName, groupBy: actOptions.roleName});
187
- const seriesVals = Object.entries(series);
188
- const minMax = normed ? {minY: -10, maxY: 110} : 0;
189
- const roleCol = DG.Column.string(actOptions.roleName, seriesVals.length);
190
- const curveCol = DG.Column.string('Curve', seriesVals.length);
191
- curveCol.init((i) => JSON.stringify(
192
- {
193
- "chartOptions": {
194
- "xAxisName": actOptions.concentrationName,
195
- "yAxisName": normed ? `norm(${actOptions.valueName})` : actOptions.valueName,
196
- "logX": true,
197
- "title": `${seriesVals[i][0]}`,
198
- ...minMax
199
- },
200
- // TODO: change to 4PL regression once fixed for normed data
201
- series: [{...seriesVals[i][1], fit: undefined, fitFunction: FIT_FUNCTION_4PL_REGRESSION, clickToToggle: true, droplines: ['IC50'], name: seriesVals[i][0]}]
202
- }
203
-
204
- ));
205
- roleCol.init((i) => seriesVals[i][0]);
206
-
207
- const df = DG.DataFrame.fromColumns([roleCol, curveCol]);
208
- df.name = pw.plateData.name;
209
- df.id = randomizeTableId();
210
-
211
- curveCol.semType ='fit';
212
- const curvesGrid = df.plot.grid();
213
-
214
- // add statistics columns
215
- Object.entries(actualStatNames).forEach(([statName, alias]) => {
216
- const params = {df: df, colName: curveCol.name, propName: statName, seriesName: 'series 0', seriesNumber: 0, newColName: alias};
217
- DG.Func.find({name: 'addStatisticsColumn'})[0].prepare(params).callSync({processed: false});
218
- });
219
- if (actualStatNames['interceptX'])
220
- df.col(actualStatNames['interceptX']) && (df.col(actualStatNames['interceptX'])!.meta.format = 'scientific');
221
-
222
- //categorize the curves
223
-
224
- const criteriaCol = df.columns.addNewString(df.columns.getUnusedName('Criteria'));
225
- criteriaCol.applyFormula(`if(${actOptions.categorizeFormula}, "Qualified", "Fails Criteria")`, 'string');
226
- criteriaCol.meta.colors.setCategorical({ "Fails Criteria":4294922560, "Qualified":4283477800 });
227
-
228
- curvesGrid.root.style.width = '100%';
229
- pw.root.style.display = 'flex';
230
- pw.root.style.flexDirection = 'column';
231
- pw.root.style.height = '100%';
232
-
233
- pw.root.appendChild(curvesGrid.root);
234
-
235
- // when selecting a cell on plate, go to appropriate curve and mark the corresponding point with different marker
236
- // remember the previous change, so that we can revert it
237
- let prevSelection: {seriesIndex: number, pointIndex: number, markerType: FitMarkerType, markerSize: number, markerColor: string, curvesGridCell?: DG.GridCell} | null = null;
238
-
239
- pw.mapFromRowFunc = (row) => mapFromRow(row, (rowIdx, checkBoxState) => {
240
- plate._markOutlier(rowIdx, checkBoxState);
241
- if (prevSelection && prevSelection.curvesGridCell)
242
- setOutlier(prevSelection.curvesGridCell, {x: 0, y: 0, outlier: !checkBoxState}, 0, prevSelection.pointIndex);
243
- pw.grid.invalidate();
244
- });
245
-
246
- function clearPreviousSelection() {
247
- try {
248
- if (!prevSelection || (prevSelection.seriesIndex ?? -1) < 0) {
249
- return;
250
- }
251
- const series = curveCol.get(prevSelection.seriesIndex);
252
- if (!series)
253
- return;
254
- const parsed = JSON.parse(series);
255
- const points: IFitPoint[] = parsed.series[0]?.points;
256
- if (points && points.length && points.length > prevSelection.pointIndex) {
257
- points[prevSelection.pointIndex].marker = prevSelection.markerType;
258
- points[prevSelection.pointIndex].size = prevSelection.markerSize;
259
- points[prevSelection.pointIndex].color = prevSelection.markerColor;
260
- curveCol.set(prevSelection.seriesIndex, JSON.stringify(parsed));
261
- }
262
- } catch (e) {
263
- console.error(e);
264
- } finally {
265
- prevSelection = null;
266
- }
267
156
  }
268
-
269
- // highlight selected point in the curve
270
- pw.subs.push(pw.grid.onCurrentCellChanged.subscribe((gc) => {
271
- clearPreviousSelection();
272
- if (gc?.gridRow == null || gc?.gridRow == -1 || !gc?.gridColumn || gc?.gridColumn.idx == 0)
273
- return;
274
- const row = pw.dataRow(gc);
275
- if (row == undefined || row < 0)
276
- return;
277
- const catValue = pw.plateData.get(actOptions.roleName, row)?.toLowerCase();
278
- if (!catValue)
279
- return;
280
- const seriesIndex = seriesVals.findIndex(([serName, _]) => serName?.toLowerCase() === catValue);
281
- if (seriesIndex < 0)
282
- return;
283
- const conscentration: number = pw.plateData.get(actOptions.concentrationName, row);
284
- const value: number = pw.plateData.get(normed ? actOptions.normalizedColName! : actOptions.valueName, row);
285
-
286
- const pointInSeriesIndex: number = seriesVals[seriesIndex][1].points.findIndex((p) => p.x === conscentration && p.y === value);
287
- if (pointInSeriesIndex < 0)
288
- return;
289
-
290
- prevSelection = {seriesIndex, pointIndex: pointInSeriesIndex, markerType: seriesVals[seriesIndex][1].points[pointInSeriesIndex].marker ?? DG.MARKER_TYPE.CIRCLE,
291
- 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))};
292
-
293
- const curveJSON = JSON.parse(curveCol.get(seriesIndex)!);
294
- const points: IFitPoint[] = curveJSON.series[0]?.points;
295
- if (points && points.length && points.length > pointInSeriesIndex) {
296
- points[pointInSeriesIndex].marker = DG.MARKER_TYPE.SQUARE;
297
- points[pointInSeriesIndex].size = FitConstants.POINT_PX_SIZE * 2;
298
- points[pointInSeriesIndex].color = DG.Color.toHtml(DG.Color.green);
299
- curveCol.set(seriesIndex, JSON.stringify(curveJSON));
300
- }
301
-
302
- // scroll in grid
303
- const curveGridRow = curvesGrid.tableRowToGrid(seriesIndex);
304
- prevSelection.curvesGridCell = curvesGrid.cell(curveCol.name, curveGridRow);
305
- prevSelection.curvesGridCell && curvesGrid.scrollToCell(curveCol.name, curveGridRow);
306
- }));
307
-
308
- // mark outliers in the original plate if it is switched from curve manually
309
-
310
- pw.subs.push(grok.events.onCustomEvent('fit-cell-outlier-toggle').subscribe((args: FitCellOutlierToggleArgs) => {
311
- if (!args || !args.gridCell || !args.series || args.pointIdx == null || args.gridCell.cell.column !== curveCol)
312
- return;
313
- const point: IFitPoint = args.series.points[args.pointIdx];
314
- if (point.meta !== null) {
315
- plate._markOutlier(point.meta, !!point.outlier);
316
- pw.grid.invalidate();
317
- }
318
- }));
319
-
320
-
321
- const s = DG.debounce(curvesGrid.onAfterDrawContent, 300).subscribe(() => {
322
- s.unsubscribe();
323
- curvesGrid.col(curveCol.name) && (curvesGrid.col(curveCol.name)!.width = 400);
324
- curvesGrid.props.rowHeight = 200;
157
+ ui.tools.waitForElementInDom(this.tabs.root).then(() => {
158
+ this.tabs.currentPane = this.tabs.getPane('Summary');
325
159
  });
326
160
 
327
- if (actOptions.submitAction) {
328
- const btn = ui.button('Save to ELN', () => actOptions.submitAction!(plate, df));
329
- pw.plateActionsDiv!.appendChild(btn);
330
- }
331
- return pw;
332
- }
333
-
334
- get plateData() { return this._plateData; }
335
- set plateData(t: DG.DataFrame) {
336
- this._plateData = t;
337
- this._colorColumn = t.columns.firstWhere((col) => col.name == 'activity' && col.type == TYPE.FLOAT)
161
+ this.syncGrids();
338
162
 
339
- ?? t.columns.firstWhere((col) => (col.name == 'concentration' || col.name == 'concentrations') && col.type == TYPE.FLOAT)
340
- ?? t.columns.firstWhere((col) => col.name != 'row' && col.name != 'col' && col.type == TYPE.FLOAT)
341
- ?? t.columns.firstWhere((col) => col.type == TYPE.FLOAT)
342
- ?? t.columns.byIndex(0);
343
-
344
- let rowCol: DG.Column<number> = this._plateData.col('row')!;
345
- let colCol: DG.Column<number> = this._plateData.col('col')!;
346
- this.rows = rowCol?.stats?.max ?? dimensions.get(t.rowCount)?.rows;
347
- this.cols = colCol?.stats?.max ?? dimensions.get(t.rowCount)?.cols;
348
-
349
- if (this.rows == null || this.cols == null)
350
- throw 'Row/col columns not found, and dataframe length is not of the recognized sizes (96, 384, 1536)';
351
-
352
- for (let i = 0; i < this._plateData.rowCount; i++)
353
- if (rowCol && colCol)
354
- this._posToRow.set(`${rowCol.get(i)}:${colCol.get(i)}`, i);
355
- else
356
- this._posToRow.set(`${Math.floor(i / this.cols)}:${i % this.cols + 1}`, i);
163
+ const t = this.plate.data;
164
+ this._colorColumn = t.columns.firstWhere((col) => col.name == 'activity' && col.type == TYPE.FLOAT) ??
165
+ t.columns.firstWhere((col) => (col.name == 'concentration' || col.name == 'concentrations') && col.type == TYPE.FLOAT) ??
166
+ t.columns.firstWhere((col) => col.name != 'row' && col.name != 'col' && col.type == TYPE.FLOAT) ??
167
+ t.columns.firstWhere((col) => col.type == TYPE.FLOAT) ??
168
+ (t.columns.length > 0 ? t.columns.byIndex(0) : undefined);
357
169
 
358
170
  // row header + all columns
359
- this.grid.dataFrame = DG.DataFrame.create(this.rows);
171
+ this.grid.dataFrame = DG.DataFrame.create(this.plate.rows);
360
172
  this.grid.columns.clear();
361
- for (let i = 0; i <= this.cols; i++)
173
+ for (let i = 0; i <= this.plate.cols; i++)
362
174
  this.grid.columns.add({gridColumnName: i.toString(), cellType: 'string'});
363
175
 
364
176
  this.grid.invalidate();
365
177
  }
366
178
 
367
- dataRow(gc: DG.GridCell): number | undefined {
368
- // we do not increment gridColumn index by 1 because there is a row number column with index 0 which we do not count
369
- // so data columns start with 1 anyway
370
- return this._posToRow.get(`${gc.gridRow}:${gc.gridColumn.idx}`);
371
- }
372
-
373
- renderCell(args:DG.GridCellRenderArgs) {
179
+ renderCell(args:DG.GridCellRenderArgs, summary: boolean = false) {
374
180
  const gc = args.cell;
375
181
  args.g.fillStyle = 'grey'; //(args.cell.isColHeader ? 'red' : (args.cell.isRowHeader ? 'green' : 'blue'));
376
182
  args.g.strokeStyle = 'grey';
377
183
  args.g.lineWidth = 1;
378
- let g = args.g;
379
- let x = args.bounds.x, y = args.bounds.y, w = args.bounds.width, h = args.bounds.height;
380
- const dataRow = this.dataRow(gc);
184
+ const g = args.g;
185
+ const x = args.bounds.x; const y = args.bounds.y; const w = args.bounds.width; const h = args.bounds.height;
381
186
  g.textAlign = 'center';
382
187
  g.textBaseline = 'middle';
383
188
  g.font = `${Math.ceil(Math.min(...[16, w - 1, h - 1]))}px Roboto, Roboto Local`;
384
189
  const isColoredByConc = this._colorColumn?.name?.toLowerCase()?.includes('conc');
385
190
 
386
191
  // column header
387
- if (gc.isColHeader && gc.gridColumn.idx > 0)
388
- g.fillText('' + gc.gridColumn.idx, x + w / 2, y + h / 2);
389
- // row header
390
- else if (gc.gridColumn.idx == 0 && gc.gridRow >= 0) {
192
+ const hasRowHeader = gc.grid.columns.byIndex(0)?.cellType === 'row header';
193
+ if (gc.isColHeader && gc.gridColumn.idx > (hasRowHeader ? 1 : 0)) {
194
+ g.fillText('' + (gc.gridColumn.idx - (hasRowHeader ? 1 : 0)), x + w / 2, y + h / 2);
195
+ args.preventDefault();
196
+ } else if (gc.isColHeader) {
197
+ args.preventDefault();
198
+ return;
199
+ } else if ((gc.gridColumn.name == '0' || gc.gridColumn.idx == 0) && gc.gridRow >= 0) {
391
200
  const prefix = gc.gridRow > 25 ? 'A' : '';
392
201
  g.fillText(prefix + String.fromCharCode(65 + gc.gridRow % 26), x + w / 2, y + h / 2);
393
- }
394
- else if (h > 0 && dataRow != null) {
202
+ args.preventDefault();
203
+ } else if (summary && h > 0 && gc.gridRow >= 0 && gc.gridColumn.idx > 0) {
204
+ const dataRow = this._plate._idx(gc.gridRow, gc.gridColumn.idx - 1);
205
+
395
206
  g.beginPath();
396
207
  const r = Math.min(h / 2, w / 2) * 0.8;
397
208
  g.ellipse(x + w / 2, y + h / 2, r, r, 0, 0, 2 * Math.PI);
398
209
  if (this._colorColumn) {
399
210
  if (this._colorColumn.isCategorical && this._colorColumn.meta.colors.getType() !== DG.COLOR_CODING_TYPE.CATEGORICAL)
400
211
  this._colorColumn.meta.colors.setCategorical();
401
- const color = this._colorColumn.isNone(dataRow) ? DG.Color.white : this._colorColumn.isNumerical
402
- ? this.getColor(dataRow, isColoredByConc)
403
- : this._colorColumn.meta.colors.getColor(dataRow);
212
+ const color = this._colorColumn.isNone(dataRow) ? DG.Color.white : this._colorColumn.isNumerical ?
213
+ this.getColor(dataRow, isColoredByConc) :
214
+ this._colorColumn.meta.colors.getColor(dataRow);
404
215
  g.fillStyle = DG.Color.toHtml(color);
405
216
  g.fill();
406
- const outlierCol = this.plateData.col(PLATE_OUTLIER_WELL_NAME);
407
- if (outlierCol?.get(dataRow)) {
408
- g.strokeStyle = DG.Color.toHtml(DG.Color.red);
409
- g.lineWidth = 2;
410
- g.moveTo(x + w / 2 - r, y + h / 2 - r);
411
- g.lineTo(x + w / 2 + r, y + h / 2 + r);
412
- g.moveTo(x + w / 2 + r, y + h / 2 - r);
413
- g.lineTo(x + w / 2 - r, y + h / 2 + r);
414
- g.stroke();
415
- }
416
217
  }
417
218
 
418
219
  g.stroke();
220
+ const outlierCol = this.plate.data.col(PLATE_OUTLIER_WELL_NAME);
221
+ if (outlierCol?.get(dataRow))
222
+ DG.Paint.marker(g, MARKER_TYPE.CROSS_X_BORDER, x + w / 2, y + h / 2, DG.Color.red, r * 2);
419
223
  }
420
- args.preventDefault();
224
+
225
+ if (summary)
226
+ args.preventDefault();
421
227
  }
422
228
 
423
229
  getColor(dataRow: number, isLog?: boolean) {
@@ -427,52 +233,10 @@ export class PlateWidget extends DG.Widget {
427
233
  const max = isLog ? safeLog((this._colorColumn!.max - this._colorColumn!.min) * 1e9) : this._colorColumn!.max;
428
234
  return DG.Color.scaleColor(reducedVal, min, max, undefined, colorScheme);
429
235
  }
430
- }
431
-
432
-
433
- export async function getPlatesFolderPreview(files: DG.FileInfo[]): Promise<DG.Widget | DG.ViewBase | undefined> {
434
-
435
- const csvFiles = files.filter((f) => f?.name?.toLowerCase()?.endsWith('.csv'));
436
- let csvView: DG.Widget | undefined = undefined;
437
- if (csvFiles.length > 2) {
438
-
439
- const plate = Plate.fromPlates(await Promise.all(csvFiles.map(async (f) => await Plate.fromCsvTableFile(f.fullPath, f.name.toLowerCase().substring(0, f.name.length - 4)))));
440
- csvView = PlateWidget.analysisView(plate, {submitAction: () => {grok.shell.info('Plate Submitted')}});
441
- plate.data.name = `${csvFiles.map((file) => file.name.slice(0, file.name.length - 4)).join('_')}.csv`;
442
- if (csvFiles.length === files.length)
443
- return csvView;
444
- }
445
- const multiView = new DG.MultiView({viewFactories: {}});
446
236
 
447
- if (csvView) {
448
- multiView.addView('Plate 1', () => DG.View.fromRoot(csvView!.root), true);
449
- }
450
-
451
- const xlsxFiles = files.filter((f) => f?.name?.toLowerCase()?.endsWith('.xlsx') && f?.name?.toLowerCase().includes('plate'));
452
-
453
- if (xlsxFiles.length == 0)
454
- return csvView;
455
-
456
- for (const xlsxFile of xlsxFiles) {
457
- try {
458
- const plate = await Plate.fromExcelFileInfo(xlsxFile);
459
- const pw = PlateWidget.analysisView(plate, {submitAction: () => {grok.shell.info('Plate Submitted')}});
460
- const v = DG.View.fromRoot(pw.root);
461
- v.name = xlsxFile.name.substring(0, xlsxFile.name.length - 5);
462
- multiView.addView(v.name, () => v, true);
463
- } catch (e) {
464
- _package.logger.error(e);
465
- }
466
- }
467
- setTimeout(() => {
468
- const header: HTMLElement | null = multiView.root.querySelector('.d4-tab-header-stripe');
469
- if (!header)
470
- return;
471
- header.style.overflow = 'scroll';
472
-
473
- const headerItems = header.querySelectorAll('.d4-tab-header');
474
- headerItems?.forEach((el) => (el as HTMLElement).style.whiteSpace = 'nowrap');
475
- }, 300)
476
-
477
- return multiView;
237
+ /** Applies plate widget options to all grids */
238
+ syncGrids() {
239
+ for (const grid of this.grids.values())
240
+ grid.props.allowEdit = this.editable;
241
+ }
478
242
  }