@datagrok/curves 1.5.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,446 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as grok from 'datagrok-api/grok';
3
+ import * as ui from 'datagrok-api/ui';
4
+ import wu from 'wu';
5
+ import {
6
+ assure,
7
+ firstWhere,
8
+ getMaxPosition,
9
+ jstatStatistics,
10
+ JSTATStatistics,
11
+ numToExcel,
12
+ parseExcelPosition, toStandardSize
13
+ } from "./utils";
14
+ import type ExcelJS from 'exceljs';
15
+ import {findPlatePositions, getPlateFromSheet} from "./excel-plates";
16
+ import {FitFunctionType, FitSeries} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
17
+ import {AnalysisOptions, PlateWidget} from './plate-widget';
18
+ import {inspectCurve} from '../fit/fit-renderer';
19
+
20
+
21
+ /** Represents a well in the experimental plate */
22
+ export interface PlateWell {
23
+ row: number;
24
+ col: number;
25
+ volume?: number;
26
+ concentration?: number;
27
+ [key: string]: any;
28
+ }
29
+
30
+
31
+ interface IPlateCsvImportOptions {
32
+ rowColumn?: string;
33
+ colColumn?: string;
34
+ positionColumn?: string;
35
+ volumeColumn?: string;
36
+ concentrationColumn?: string;
37
+ field?: string; // used as a field name when a 12x8 table is passed; if not passed, defaults to 'value'
38
+ }
39
+
40
+
41
+ export interface IPlateWellFilter {
42
+ includeEmpty?: boolean;
43
+ match?: {[key: string]: any};
44
+ exclude?: {[key: string]: any};
45
+ }
46
+
47
+
48
+ interface ISeriesData {
49
+ x: number[];
50
+ y: number[];
51
+ }
52
+
53
+ // export class PlateLayer<TData> {
54
+ // plate: Plate;
55
+ // data: Float64Array ArrayLike<number> DG.Column<TData>;
56
+ // role: 'concentration' | 'volume';
57
+ //
58
+ // /** Array of non-empty values */
59
+ // values(filter?: IPlateWellFilter): Array<any> {
60
+ // const col = this.data.columns.byName(data.name);
61
+ // assure(col != null, `Field does not exist: ${field}`);
62
+ //
63
+ // const result = [];
64
+ // for (let i = 0; i < this.rows * this.cols; i++)
65
+ // if ((filter?.includeEmpty ?? false) || !col.isNone(i))
66
+ // result.push(col.isNone(i) ? null : col.get(i));
67
+ //
68
+ // return result;
69
+ // }
70
+ // }
71
+
72
+ export const PLATE_OUTLIER_WELL_NAME = 'Outlier';
73
+
74
+ export function randomizeTableId() {
75
+ return `${Math.random()}-${Math.random()}-${Math.random()}-${Math.random()}-${Math.random()}-${Math.random()}-${Math.random()}-${Math.random()}`;
76
+ }
77
+
78
+ /** Represents experimental plate (typically 96-, 384-, or 1536-well assay plates) */
79
+ export class Plate {
80
+ data: DG.DataFrame;
81
+ //layers: PlateLayer[];
82
+ rows: number = 8;
83
+ cols: number = 12;
84
+
85
+ constructor(rows: number, cols: number) {
86
+ this.data = DG.DataFrame.create(rows * cols);
87
+ this.rows = rows;
88
+ this.cols = cols;
89
+ }
90
+
91
+ /** Creates an empty plate of the standard size to fit the specified positions. t*/
92
+ static autoSize(positions: Iterable<[number, number]>): Plate {
93
+ const [rows, cols] = toStandardSize(getMaxPosition(positions));
94
+ return new Plate(rows, cols);
95
+ }
96
+
97
+ _idx(row: number, col: number): number {
98
+ return row * this.cols + col;
99
+ }
100
+
101
+ //well(row: number, col: number): PlateWell { return new PlateWell(); }
102
+
103
+ _markOutlier(row: number, flag: boolean = true) {
104
+ const outlierCol = this.data.columns.getOrCreate(PLATE_OUTLIER_WELL_NAME, DG.TYPE.BOOL);
105
+ outlierCol.set(row, flag);
106
+ }
107
+
108
+ markOutlier(row: number, col: number, flag: boolean = true) {
109
+ this._markOutlier(this._idx(row, col), flag);
110
+ }
111
+
112
+ _isOutlier(row: number): boolean {
113
+ const outlierCol = this.data.columns.getOrCreate(PLATE_OUTLIER_WELL_NAME, DG.TYPE.BOOL);
114
+ return outlierCol.get(row);
115
+ }
116
+ isOutlier(row: number, col: number): boolean {
117
+ return this._isOutlier(this._idx(row, col));
118
+ }
119
+
120
+ markOutliersWhere(field: string, valueFunc: (fieldValue: any) => boolean, filter?: IPlateWellFilter) {
121
+ this.values([field], filter).forEach((v) => {
122
+ if(valueFunc(v[field]))
123
+ this._markOutlier(v.innerDfRow, true);
124
+ })
125
+ }
126
+
127
+ static fromTable(table: DG.DataFrame, field?: string): Plate {
128
+ const rows = table.rowCount;
129
+ // remove row letters
130
+ function containsRowLetters(c: DG.Column): boolean {
131
+ return c.type == DG.TYPE.STRING && DG.range(rows).every((i) => numToExcel(i) == c.get(i).toUpperCase());
132
+ }
133
+
134
+ const dataColumns = wu(table.columns).filter((c) => !containsRowLetters(c)).toArray();
135
+ const cols = dataColumns.length;
136
+ const plate = new Plate(rows, cols);
137
+
138
+ const nonEmptyCols = dataColumns.filter((c) => c.stats.missingValueCount != rows);
139
+ const toString = (nonEmptyCols.length > 0 && nonEmptyCols.findIndex((c) => c.type != nonEmptyCols[0].type) != -1);
140
+ const type = toString
141
+ ? DG.TYPE.STRING
142
+ : firstWhere(dataColumns, c => c.stats.missingValueCount != rows)?.type ?? DG.TYPE.STRING;
143
+
144
+ const dataColumn = plate.data.columns.addNew(table.name ?? field, type);
145
+
146
+ for (let colIdx = 0; colIdx < dataColumns.length; colIdx ++)
147
+ if (dataColumns[colIdx].stats.missingValueCount != rows)
148
+ for (let i = 0; i < rows; i++)
149
+ dataColumn.set(plate._idx(i, colIdx), type != DG.TYPE.STRING ? dataColumns[colIdx].get(i) : dataColumns[colIdx].getString(i), false);
150
+
151
+ return plate;
152
+ }
153
+
154
+
155
+ /** Constructs a plate from a dataframe where each row corresponds to a well.
156
+ * Automatically detects position column (has to be in Excel notation). */
157
+ static fromTableByRow(table: DG.DataFrame, field?: string): Plate {
158
+ const posCol = wu(table.columns)
159
+ .find((c) => c.type == DG.TYPE.STRING && /^([A-Za-z]+)(\d+)$/.test(c.get(0)));
160
+ if (!posCol)
161
+ throw 'Column with well positions not found';
162
+
163
+ const [rows, cols] = toStandardSize(getMaxPosition(wu(posCol.values()).map(parseExcelPosition)));
164
+ const plate = new Plate(rows, cols);
165
+
166
+ for (const col of table.columns) {
167
+ if (col.isEmpty || col == posCol)
168
+ continue;
169
+
170
+ const plateCol = plate.data.columns.addNew(col.name, col.type);
171
+ for (let r = 0; r < col.length; r++) {
172
+ const [wellRow, wellCol] = parseExcelPosition(posCol.get(r));
173
+ plateCol.set(wellRow * cols + wellCol, col.get(r), false);
174
+ }
175
+ }
176
+
177
+ return plate;
178
+ }
179
+
180
+ static async fromCsvTableFile(csvPath: string, field: string, options?: DG.CsvImportOptions): Promise<Plate> {
181
+ return this.fromTable(await grok.dapi.files.readCsv(csvPath, options), field);
182
+ }
183
+
184
+ // getClosestRoleName(fileName: string): string {
185
+ // const roleRoleNames = ['role', 'compound', 'compound name'];
186
+ // const concentrationRoleNames = ['concentration', 'conc', 'dilution'];
187
+ // const valueRoleNames = ['value', 'readout', 'response', 'activity', 'signal', 'absorbance', 'fluorescence', 'luminescence', 'intensity', 'od', 'optical density'];
188
+ // const foundRoleIndex = [roleRoleNames, concentrationRoleNames, valueRoleNames];
189
+
190
+ // }
191
+
192
+ static fromCsvTable(csv: string, field: string, options?: DG.CsvImportOptions): Plate {
193
+ return this.fromTable(DG.DataFrame.fromCsv(csv, options), field);
194
+ }
195
+
196
+ static fromCsv(csv: string, options?: IPlateCsvImportOptions): Plate {
197
+ const df = DG.DataFrame.fromCsv(csv);
198
+
199
+ // we do not need first row with row letters
200
+ if (DG.range(df.rowCount).every((i) => df.col(0)!.get(i) == String.fromCharCode(65 + i)))
201
+ df.columns.remove(df.columns.byIndex(0).name);
202
+
203
+ // sometimes there is an unnecessary last column in the end
204
+ if (df.columns.length == 13 || df.columns.length == 25 || df.columns.length == 49 && df.col(df.columns.length - 1)?.isEmpty)
205
+ df.columns.remove(df.columns.length - 1);
206
+
207
+ // TODO: tall format?
208
+ // if (df.columns.contains('pos'))
209
+ // return new Plate(0, 0);
210
+
211
+ return this.fromTable(df, options?.field ?? 'value');
212
+ }
213
+
214
+ /** Merges the attributes from {@link plates} into one plate. */
215
+ static fromPlates(plates: Plate[], name?: string) {
216
+ assure(plates.length > 0, 'Array is empty.');
217
+ assure(plates.every(p => p.rows == plates[0].rows && p.cols == plates[0].cols), 'Plate dimensions differ.');
218
+
219
+ const result = plates.reduce((p1, p2) => p1 ? p1.merge(p2) : p2.clone());
220
+ if (name != null)
221
+ result.data.name = name;
222
+ return result;
223
+ }
224
+
225
+ static async fromExcelFileInfo(fi: DG.FileInfo): Promise<Plate> {
226
+ return fi.data && fi.data.length ? await Plate.fromExcel(fi.data, fi.friendlyName) : await Plate.fromExcelPath(fi.fullPath, fi.friendlyName);
227
+ }
228
+
229
+ static async fromExcelPath(excelPath: string, name?: string): Promise<Plate> {
230
+ const content = await grok.dapi.files.readAsBytes(excelPath);
231
+ return this.fromExcel(content, name);
232
+ }
233
+
234
+ /** Constructs the plates from the specified Excel file.
235
+ * Plate positions are detected automatically. */
236
+ static async fromExcel(excelBytes: Uint8Array, name?: string): Promise<Plate> {
237
+ await DG.Utils.loadJsCss(['/js/common/exceljs.min.js']);
238
+
239
+ //@ts-ignore
240
+ const loadedExcelJS = window.ExcelJS as ExcelJS;
241
+ const workbook = new loadedExcelJS.Workbook() as ExcelJS.Workbook;
242
+ // @ts-ignore reason: some typescript error with araryLike and arrayBufferLike
243
+ const wb= await workbook.xlsx.load(excelBytes);
244
+
245
+ const platePositions = findPlatePositions(wb);
246
+ if (platePositions.length == 0) throw 'Plates not found in "${excelPath}"';
247
+ const p0 = platePositions[0];
248
+ if (!platePositions.every((pc) => pc.rows == p0.rows || pc.cols == p0.cols))
249
+ throw `Plate sizes differ in "${name}"`;
250
+
251
+ return Plate.fromPlates(platePositions.map(p => getPlateFromSheet(p)), name);
252
+ }
253
+
254
+ /** Generates [count] increasing integer numbers, starting with 0. */
255
+ get wells(): IterableIterator<PlateWell> {
256
+ const self = this; // Capture this context
257
+ return (function* () {
258
+ for (let row = 0; row < self.rows; row++) {
259
+ for (let col = 0; col < self.cols; col++) {
260
+ const well: PlateWell = {
261
+ row: row,
262
+ col: col,
263
+ };
264
+ for (const field of self.data.columns) {
265
+ if (!field.isNone(self._idx(row, col))) {
266
+ well[field.name] = field.get(self._idx(row, col));
267
+ }
268
+ }
269
+ yield well;
270
+ }
271
+ }
272
+ })();
273
+ }
274
+
275
+ /** Returns the specified field value at the specified positions (0-based).
276
+ * The following examples all return volume for the C4 well:
277
+ * - plate.get('volume', 2, 3)
278
+ * - plate.get('volume', 'C4')
279
+ * */
280
+ get(field: string, rowIdxOrPos: number | string, colIdx?: number): any {
281
+ assure(this.data.columns.byName(field) != null, `Field does not exist: ${field}`);
282
+ if (typeof rowIdxOrPos === 'number' && !colIdx)
283
+ throw 'Column not defined';
284
+
285
+ const [row, col] = (typeof rowIdxOrPos === 'string') ? parseExcelPosition(rowIdxOrPos) : [rowIdxOrPos, colIdx!];
286
+ return this.data.columns.byName(field).get(this._idx(row, col));
287
+ }
288
+
289
+ /** Changes all numerical values to the results of the specified normalization function */
290
+ normalize(field: string, f: (value: number) => number, inplace: boolean = false) {
291
+ const originalCol = this.data.getCol(field);
292
+ const col = inplace ? originalCol : this.data.columns.addNewFloat(this.data.columns.getUnusedName(`${field}_normalized`));
293
+ col.init((i) => originalCol.isNone(i) ? null : f(originalCol.get(i)));
294
+ return col;
295
+ }
296
+
297
+ matches(i: number, filter: IPlateWellFilter): boolean {
298
+ const cols = this.data.columns;
299
+ // we allow both any and array of any things in matches object, so we need to convert it to array to have one api
300
+ const arMatches = filter.match ? Object.entries(filter.match).reduce((acc, [key, value]) => {acc[key] = Array.isArray(value) ? value : [value]; return acc;}, {} as Record<string, any[]>) : null;
301
+ const arExclude = filter.exclude ? Object.entries(filter.exclude).reduce((acc, [key, value]) => {acc[key] = Array.isArray(value) ? value : [value]; return acc;}, {} as Record<string, any[]>) : null;
302
+ return !filter || (!arMatches && !arExclude) ||
303
+ (
304
+ Object.keys(arMatches ?? {}).filter((m) => cols.contains(m)).every((key) => arMatches![key].some((m) => this.data.columns.byName(key).get(i) === m)) &&
305
+ Object.keys(arExclude ?? {}).filter((m) => cols.contains(m)).every((key) => arExclude![key].every((e) => this.data.columns.byName(key).get(i) !== e)));
306
+ }
307
+
308
+ count(filter?: IPlateWellFilter): number {
309
+ if (!filter)
310
+ return this.rows * this.cols;
311
+ let c = 0;
312
+ for (let i = 0; i < this.rows * this.cols; i++)
313
+ if (this.matches(i, filter))
314
+ c++;
315
+ return c;
316
+ }
317
+
318
+ /** Array of non-empty values */
319
+ values(fields: string[], filter?: IPlateWellFilter): Array<Record<string, any> & {innerDfRow: number}> {
320
+ const cols = fields.map((f) => this.data.columns.byName(f));
321
+ assure(cols.every((c) => c != null), `Field does not exist: ${fields.find((_, i) => cols[i] == null)}`);
322
+ const colsObj: Record<string, DG.Column> = {};
323
+ for (let i = 0; i < fields.length; i++)
324
+ colsObj[fields[i]] = cols[i];
325
+ const result: (Record<string, any> & {innerDfRow: number}) [] = [];
326
+ for (let i = 0; i < this.rows * this.cols; i++) {
327
+ if (((filter?.includeEmpty ?? false) || cols.every((col) => !col.isNone(i))) && (!filter || this.matches(i, filter))) {
328
+ const res = fields.reduce((acc, f) => { acc[f] = colsObj[f].isNone(i) ? null : colsObj[f].get(i); return acc; }, {} as Record<string, any> & {innerDfRow: number});
329
+ res.innerDfRow = i;
330
+ result.push(res);
331
+ }
332
+ }
333
+ return result;
334
+ }
335
+
336
+ /// Returns specified field statistics for the specified filter and specified field name
337
+ getStatistics<T extends JSTATStatistics[]>(field: string, statistics: T, filter?: IPlateWellFilter): Record<T[number], number> {
338
+ const values = this.fieldValues(field, filter);
339
+ const result: Record<JSTATStatistics, number> = {} as Record<JSTATStatistics, number>;
340
+ for (const stat of statistics) {
341
+ result[stat] = jstatStatistics[stat](values);
342
+ }
343
+ return result;
344
+ }
345
+
346
+ fieldValues(field: string, filter?: IPlateWellFilter): Array<any> {
347
+ return this.values([field], filter).map((v) => v[field]);
348
+ }
349
+
350
+ static inspectSeriesByName(records: Record<string, FitSeries>, seriesName: string, fitFunctionName: FitFunctionType): void {
351
+ if (!seriesName || !fitFunctionName)
352
+ return;
353
+ Plate.inspectSeries(records[seriesName], fitFunctionName);
354
+ }
355
+
356
+ static inspectSeries(series: FitSeries, fitFunctionName: FitFunctionType) {
357
+ const seriesName = series?.name ?? 'Series';
358
+ if (!series || !fitFunctionName)
359
+ return;
360
+ const curveCol = DG.Column.string('Curve', 1);
361
+ curveCol.set(0, JSON.stringify({
362
+ chartOptions: {
363
+ logX: true,
364
+ title: seriesName,
365
+ },
366
+ series: [{...series, fit: undefined, fitFunction: fitFunctionName, clickToToggle: true, droplines: ['IC50'], name: seriesName}]
367
+ }), false);
368
+ const df = DG.DataFrame.fromColumns([curveCol]);
369
+ df.name = seriesName;
370
+ df.id = randomizeTableId();
371
+ curveCol.semType = 'fit';
372
+ curveCol.tags[DG.Tags.CellRenderer] = 'fit';
373
+ const grid = DG.Viewer.grid(df);
374
+ const gridCell = grid.cell('Curve', 0);
375
+ grok.shell.windows.showContextPanel = true;
376
+ grok.shell.o = gridCell;
377
+ inspectCurve(gridCell, {width: 480, height: 370}, true);
378
+ }
379
+
380
+ doseResponseSeries(options?: IPlateWellFilter & { concentration?: string; value?: string, groupBy?: string}): Record<string, FitSeries> {
381
+ const valueOptions = {includeEmpty: options?.includeEmpty ?? false, exclude: options?.exclude ?? {'role': ['High Control', 'Low Control']}}
382
+ const concKey = options?.concentration ?? 'concentration';
383
+ const valueKey = options?.value ?? 'value';
384
+ const values = this.values([concKey, valueKey, ...(options?.groupBy ? [options.groupBy] : [])], valueOptions);
385
+
386
+ const series: Record<string, ISeriesData & Record<string, any>> = {};
387
+ for (const v of values) {
388
+ const group = options?.groupBy ? v[options.groupBy] : '0';
389
+ if (!series[group])
390
+ series[group] = {x: [], y: [], meta: [], outlier: []};
391
+ series[group].x.push(v[concKey]);
392
+ series[group].y.push(v[valueKey]);
393
+ series[group].meta.push(v.innerDfRow);
394
+ series[group].outlier.push(this._isOutlier(v.innerDfRow));
395
+ }
396
+ return Object.fromEntries(Object.entries(series).map(([k, v]) => {
397
+ const fitSeries = new FitSeries(v.x.map((_, i) => ({x: v.x[i], y: v.y[i], outlier: v.outlier[i], meta: v.meta[i]})).sort((a, b) => a.x - b.x));
398
+ fitSeries.name = k;
399
+ return [k, fitSeries];
400
+ }));
401
+ }
402
+
403
+ getAnalysisDialog(options: AnalysisOptions) {
404
+ ui.dialog('Plate Analysis')
405
+ .add(PlateWidget.analysisView(this, options))
406
+ .showModal(true);
407
+ }
408
+
409
+ getAnalysisView(options: AnalysisOptions) {
410
+ const view = DG.View.fromRoot(PlateWidget.analysisView(this, options).root);
411
+ view.name = 'Plate Analysis';
412
+ return grok.shell.addView(view);
413
+ }
414
+
415
+ /** Adds data from the other plate to this plate. Typically, you would apply plate layout */
416
+ merge(plate: Plate) {
417
+ for (const col of plate.data.columns) {
418
+ this.data.columns.add(col.clone());
419
+ }
420
+ return this;
421
+ }
422
+
423
+ /** Deep cloning */
424
+ clone(): Plate {
425
+ const cloned = new Plate(this.rows, this.cols);
426
+ cloned.data = this.data.clone();
427
+ return cloned;
428
+ }
429
+
430
+ print() {
431
+ for (const fieldCol of this.data.columns) {
432
+ console.log();
433
+ console.log(fieldCol.name);
434
+ console.log(DG.range(this.cols + 1).map((col) => col == 0 ? '' : `${col}`).toArray().join('\t'));
435
+ for (let row = 0; row < this.rows; row++) {
436
+ console.log(numToExcel(row) + '\t' +
437
+ DG.range(this.cols).map((col) => fieldCol.getString(this._idx(row, col))).toArray().join(',\t'));
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+
444
+
445
+
446
+
@@ -0,0 +1,42 @@
1
+ import {Plate} from "../plate";
2
+ import {IPlateReader} from "../plate-reader";
3
+ import { parseExcelPosition } from "../utils";
4
+
5
+ export class BmgPherastar96PlateReader implements IPlateReader {
6
+ isApplicable(s: string): boolean {
7
+ return s.includes('No. of Channels / Multichromatics:') && s.includes('No. of Cycles:');
8
+ }
9
+
10
+ read(s: string): Plate {
11
+ // Find the data section starting with "A01;"
12
+ const dataStart = s.indexOf('A01;');
13
+ if (dataStart === -1) throw new Error('Data section not found');
14
+
15
+ // Split into lines and process each line
16
+ const lines = s.substring(dataStart).split('\n')
17
+ .map(line => line.trim())
18
+ .filter(line => line.length > 0)
19
+ .map(line => line.split(';').map(s => s.trim()));
20
+
21
+ const plate = Plate.autoSize(lines.map((line) => parseExcelPosition(line[0])));
22
+
23
+ // Create columns for both channels
24
+ const channelA = plate.data.columns.addNewFloat('Channel A');
25
+ const channelB = plate.data.columns.addNewFloat('Channel B');
26
+
27
+ // Process each line
28
+ for (const line of lines) {
29
+ const [pos, valA, valB] = line;
30
+ if (!pos || pos.length !== 3) continue;
31
+
32
+ const [row, col] = parseExcelPosition(pos);
33
+
34
+ // Set values in the plate
35
+ const idx = plate._idx(row, col);
36
+ channelA.set(idx, parseFloat(valA), false);
37
+ channelB.set(idx, parseFloat(valB), false);
38
+ }
39
+
40
+ return plate;
41
+ }
42
+ }
@@ -0,0 +1,15 @@
1
+ import {Plate} from "../plate";
2
+ import {IPlateReader} from "../plate-reader";
3
+
4
+ export class DelfiaEnvision96MaxRluPlateReader implements IPlateReader {
5
+ isApplicable(s: string): boolean {
6
+ return s.startsWith('Plate information') && s.includes('DELFIA') && s.includes('Number of the wells in the plate,,,,96');
7
+ }
8
+
9
+ read(s: string): Plate {
10
+ const start = s.indexOf(',01,02,03,04,05,06,07,08,09,10,11,12,');
11
+ let end = s.indexOf('\n\n', start + 1);
12
+ end = end != -1 ? end : s.indexOf('\r\n\r\n', start + 1);
13
+ return Plate.fromCsv(s.substring(start, end));
14
+ }
15
+ }
@@ -0,0 +1,18 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import {Plate} from "../plate";
3
+ import {IPlateReader} from "../plate-reader";
4
+
5
+ export class DelfiaEnvisionByRowPlateReader implements IPlateReader {
6
+ isApplicable(s: string): boolean {
7
+ return s.includes('PltRpt=1') && s.includes('Group=1');
8
+ }
9
+
10
+ read(content: string): Plate {
11
+ let end = content.indexOf('\n\n');
12
+ end = end == -1 ? content.indexOf('\r\n\r\n') : end;
13
+ const csv = content.substring(content.indexOf('\n') + 1, end);
14
+ const table = DG.DataFrame.fromCsv(csv, {delimiter: '\t'});
15
+
16
+ return Plate.fromTableByRow(table);
17
+ }
18
+ }
@@ -0,0 +1,43 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import { Plate } from "../plate";
3
+ import { IPlateReader } from "../plate-reader";
4
+
5
+ export class SpectramaxPlateReader implements IPlateReader {
6
+ isApplicable(s: string): boolean {
7
+ return s.includes('Plate:') && s.includes('##BLOCKS=');
8
+ }
9
+
10
+ read(content: string): Plate {
11
+ const lines = content.split(/\r\n|\r|\n/);
12
+ const header = lines[2].split('\t').filter(s => s !== '');
13
+ const plateCount = parseInt(lines[1].split('\t')[8]);
14
+
15
+ // empty measurements names in the beginning are ok - need for indexing, will be ignored later
16
+ const plateMeasurementNames = header.filter((s, i) => s == "" && i < 5 || !/^-?\d+$/.test(s));
17
+ const cols = header.filter((s) => /^-?\d+$/.test(s)).length;
18
+ const rows = cols * 2 / 3;
19
+ const plates = [];
20
+
21
+ for (let plateIdx = 0; plateIdx < plateCount; plateIdx++) {
22
+ const plate = new Plate(rows, cols);
23
+ const headerValues = lines[plateIdx * (rows + 1) + 3].split('\t');
24
+ const plateMeasurements = plateMeasurementNames
25
+ .map((v, i) => v + ': ' + headerValues[i])
26
+ .filter((v, i) => v != '')
27
+ .join(', ');
28
+
29
+ const data = plate.data.columns.addNewFloat(plateMeasurements);
30
+ for (let row = 0; row < rows; row++) {
31
+ const rowIdx = plateIdx * (rows + 1) + 3 + row;
32
+ const values = lines[rowIdx].split('\t');
33
+ for (let col = 0; col < cols; col++) {
34
+ data.set(row * cols + col, parseFloat(values[col + 2].replace(',', '.')), false);
35
+ }
36
+ }
37
+
38
+ plates.push(plate);
39
+ }
40
+
41
+ return Plate.fromPlates(plates);
42
+ }
43
+ }