@datagrok/curves 1.6.0 → 1.8.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.
@@ -0,0 +1,478 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ 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';
8
+ //@ts-ignore
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';
14
+
15
+
16
+ export type AnalysisOptions = {
17
+ roleName: string,
18
+ concentrationName: string,
19
+ valueName: string
20
+ controlColumns: string[],
21
+ normalize: boolean,
22
+ autoFilterOutliers: boolean,
23
+ submitAction?: (plate: Plate, curvesDf: DG.DataFrame) => void,
24
+ categorizeFormula: string,
25
+ statisticsColumns: string[],
26
+ plateStatistics?: {[key: string]: (plate: Plate) => string | number}
27
+ }
28
+
29
+
30
+ const colorScheme = [DG.Color.white, DG.Color.gray];
31
+ export const dimensions = new Map([
32
+ [96, {rows: 8, cols: 12}],
33
+ [384, {rows: 16, cols: 24}],
34
+ [1536, {rows: 32, cols: 48}],
35
+ ]);
36
+
37
+ 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;
44
+ colorColumnName: string = '';
45
+ colorSelector?: DG.InputBase;
46
+ detailsDiv?: HTMLElement;
47
+ wellDetailsDiv?: HTMLElement;
48
+ plateDetailsDiv?: HTMLElement;
49
+ plateActionsDiv?: HTMLElement;
50
+ mapFromRowFunc: (row: DG.Row) => Record<string, any> = mapFromRow;
51
+
52
+ constructor() {
53
+ 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
+
60
+ this.grid.onCellRender.subscribe((args) => this.renderCell(args));
61
+ }
62
+
63
+ static fromPlate(plate: Plate) {
64
+ return PlateWidget.detailedView(plate.data);
65
+ }
66
+
67
+ static detailedView(table: DG.DataFrame): PlateWidget {
68
+ const pw = new PlateWidget();
69
+ pw.grid.root.style.width = '100%';
70
+ pw.plateData = table;
71
+ pw.colorSelector = ui.input.column('Color by', {
72
+ table: table,
73
+ value: pw._colorColumn,
74
+ onValueChanged: (v) => { pw._colorColumn = v; pw.grid.invalidate(); }
75
+ });
76
+ pw.detailsDiv = ui.divV([]);
77
+ pw.wellDetailsDiv = div();
78
+ pw.detailsDiv.appendChild(pw.wellDetailsDiv!);
79
+ pw.grid.onCurrentCellChanged.subscribe((gc) => {
80
+ 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))));
84
+ });
85
+
86
+ pw.root.prepend(pw.colorSelector.root);
87
+ pw.root.append(pw.detailsDiv);
88
+ return pw;
89
+ }
90
+
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) {
159
+
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);
163
+
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;
176
+ });
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
+ }
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;
325
+ });
326
+
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)
338
+
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);
357
+
358
+ // row header + all columns
359
+ this.grid.dataFrame = DG.DataFrame.create(this.rows);
360
+ this.grid.columns.clear();
361
+ for (let i = 0; i <= this.cols; i++)
362
+ this.grid.columns.add({gridColumnName: i.toString(), cellType: 'string'});
363
+
364
+ this.grid.invalidate();
365
+ }
366
+
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) {
374
+ const gc = args.cell;
375
+ args.g.fillStyle = 'grey'; //(args.cell.isColHeader ? 'red' : (args.cell.isRowHeader ? 'green' : 'blue'));
376
+ args.g.strokeStyle = 'grey';
377
+ 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);
381
+ g.textAlign = 'center';
382
+ g.textBaseline = 'middle';
383
+ g.font = `${Math.ceil(Math.min(...[16, w - 1, h - 1]))}px Roboto, Roboto Local`;
384
+ const isColoredByConc = this._colorColumn?.name?.toLowerCase()?.includes('conc');
385
+
386
+ // 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) {
391
+ const prefix = gc.gridRow > 25 ? 'A' : '';
392
+ g.fillText(prefix + String.fromCharCode(65 + gc.gridRow % 26), x + w / 2, y + h / 2);
393
+ }
394
+ else if (h > 0 && dataRow != null) {
395
+ g.beginPath();
396
+ const r = Math.min(h / 2, w / 2) * 0.8;
397
+ g.ellipse(x + w / 2, y + h / 2, r, r, 0, 0, 2 * Math.PI);
398
+ if (this._colorColumn) {
399
+ if (this._colorColumn.isCategorical && this._colorColumn.meta.colors.getType() !== DG.COLOR_CODING_TYPE.CATEGORICAL)
400
+ 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);
404
+ g.fillStyle = DG.Color.toHtml(color);
405
+ 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
+ }
417
+
418
+ g.stroke();
419
+ }
420
+ args.preventDefault();
421
+ }
422
+
423
+ getColor(dataRow: number, isLog?: boolean) {
424
+ const val = this._colorColumn!.get(dataRow)!;
425
+ const reducedVal = isLog ? safeLog((val - this._colorColumn!.min) * 1e9) : val;
426
+ const min = (isLog ? safeLog(Math.max(this._colorColumn!.min, 1)) : this._colorColumn!.min);
427
+ const max = isLog ? safeLog((this._colorColumn!.max - this._colorColumn!.min) * 1e9) : this._colorColumn!.max;
428
+ return DG.Color.scaleColor(reducedVal, min, max, undefined, colorScheme);
429
+ }
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
+
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;
478
+ }