@datagrok/curves 1.6.0 → 1.9.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 (58) 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 +33 -0
  5. package/README.md +36 -8
  6. package/databases/plates/0000_init.sql +167 -0
  7. package/detectors.js +2 -2
  8. package/dist/package-test.js +15930 -1
  9. package/dist/package-test.js.map +1 -1
  10. package/dist/package.js +13750 -1
  11. package/dist/package.js.map +1 -1
  12. package/img/plate-dose-response-series.gif +0 -0
  13. package/img/plate-readers.gif +0 -0
  14. package/package.json +17 -11
  15. package/queries/plates-crud.sql +148 -0
  16. package/src/fit/const.ts +60 -59
  17. package/src/fit/data-to-curves.ts +220 -0
  18. package/src/fit/fit-demo.ts +6 -6
  19. package/src/fit/fit-grid-cell-handler.ts +94 -85
  20. package/src/fit/fit-renderer.ts +162 -98
  21. package/src/fit/multi-curve-viewer.ts +69 -28
  22. package/src/fit/render-utils.ts +346 -288
  23. package/src/package-api.ts +167 -0
  24. package/src/package-test.ts +7 -1
  25. package/src/package.g.ts +140 -2
  26. package/src/package.ts +221 -79
  27. package/src/plate/excel-plates.ts +112 -0
  28. package/src/plate/plate-cell-renderer.ts +48 -0
  29. package/src/plate/plate-drc-analysis.ts +262 -0
  30. package/src/plate/plate-reader.ts +28 -0
  31. package/src/plate/plate-well-validators.ts +41 -0
  32. package/src/plate/plate-widget.ts +242 -0
  33. package/src/plate/plate.ts +557 -0
  34. package/src/plate/plates-folder-preview.ts +63 -0
  35. package/src/plate/readers/bmg-pherastar-96.ts +42 -0
  36. package/src/plate/readers/delfia-envision-96-max-rlu.ts +16 -0
  37. package/src/plate/readers/delfia-envision-by-row.ts +18 -0
  38. package/src/plate/readers/spectramax.ts +42 -0
  39. package/src/plate/utils.ts +141 -0
  40. package/src/plates/numeric_matcher.ts +191 -0
  41. package/src/plates/objects/plate-template-handler.ts +48 -0
  42. package/src/plates/plates-app.ts +64 -0
  43. package/src/plates/plates-crud.ts +502 -0
  44. package/src/plates/plates-demo.ts +107 -0
  45. package/src/plates/plates.sql +169 -0
  46. package/src/plates/views/plates-create-view.ts +123 -0
  47. package/src/plates/views/plates-schema-view.ts +58 -0
  48. package/src/plates/views/plates-search-view.ts +137 -0
  49. package/src/plates/views/plates-templates-view.ts +38 -0
  50. package/src/tests/curves-cell-renderer-tests.ts +95 -75
  51. package/src/tests/detector-tests.ts +3 -2
  52. package/src/tests/fit-tests.ts +199 -163
  53. package/src/tests/plate-tests.ts +153 -0
  54. package/src/tests/transform-tests.ts +6 -6
  55. package/test-console-output-1.log +435 -0
  56. package/test-record-1.mp4 +0 -0
  57. package/tsconfig.json +1 -1
  58. package/src/fit/cell-render-viewer.ts +0 -54
@@ -0,0 +1,502 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+ import * as grok from 'datagrok-api/grok';
4
+ import {Plate} from '../plate/plate';
5
+ import {NumericMatcher, Matcher} from './numeric_matcher';
6
+ import {Subject} from 'rxjs';
7
+ import * as api from '../package-api';
8
+
9
+ export const events: Subject<CrudEvent> = new Subject();
10
+
11
+ /** Events emitted by the plates CRUD layer. */
12
+ export type CrudEvent = {
13
+ on: 'before' | 'after';
14
+ eventType: 'created' | 'read' | 'updated' | 'deleted';
15
+ objectType: TYPE;
16
+ object: Partial<PlateTemplate> | Partial<Plate> | Partial<PlateProperty>;
17
+ cancel?: boolean; // when set by the listener at the 'before' event, the operation is cancelled
18
+ }
19
+
20
+ export enum TYPE {
21
+ PLATE = 'Plate',
22
+ WELL = 'PlateWell',
23
+ TEMPLATE = 'PlateTemplate',
24
+ PROPERTY = 'PlateProperty',
25
+ }
26
+
27
+ export const entityTypes: string[] = [TYPE.PLATE, TYPE.WELL, TYPE.TEMPLATE, TYPE.PROPERTY];
28
+
29
+ export type PlateType = {
30
+ id: number;
31
+ name: string;
32
+ rows: number;
33
+ cols: number;
34
+ maxVolume?: number;
35
+ }
36
+
37
+ export interface PlateProperty extends DG.IProperty {
38
+ id: number;
39
+ name: string;
40
+ type: string; //DG.COLUMN_TYPE;
41
+ }
42
+
43
+ export type PropertyCondition = {
44
+ property: PlateProperty;
45
+ matcher: Matcher;
46
+ }
47
+
48
+ export type PlateQuery = {
49
+ plateMatchers: PropertyCondition[];
50
+ wellMatchers: PropertyCondition[];
51
+ }
52
+
53
+ export type PlateTemplate = {
54
+ id: number;
55
+ name: string;
56
+ description: string;
57
+ plate_layout_id: number;
58
+ plateProperties: Partial<PlateProperty>[];
59
+ wellProperties: Partial<PlateProperty>[];
60
+ }
61
+
62
+ export let wellProperties: PlateProperty[] = [
63
+ {id: 1000, name: 'Volume', type: DG.COLUMN_TYPE.FLOAT},
64
+ {id: 1001, name: 'Concentration', type: DG.COLUMN_TYPE.FLOAT},
65
+ {id: 1002, name: 'Sample', type: DG.COLUMN_TYPE.STRING},
66
+ {id: 1003, name: 'Well Role', type: DG.COLUMN_TYPE.STRING}
67
+ ];
68
+
69
+ export let plateProperties: PlateProperty[] = [];
70
+ export let plateTemplates: PlateTemplate[] = [];
71
+
72
+ export let plateTypes: PlateType[] = [
73
+ {id: 1, name: 'Generic 96 wells', rows: 8, cols: 12},
74
+ {id: 2, name: 'Generic 384 wells', rows: 16, cols: 24},
75
+ {id: 3, name: 'Generic 1536 wells', rows: 32, cols: 48},
76
+ ];
77
+
78
+ export let plateUniquePropertyValues: DG.DataFrame = DG.DataFrame.create();
79
+ export let wellUniquePropertyValues: DG.DataFrame = DG.DataFrame.create();
80
+
81
+ export const plateDbColumn: {[key: string]: string} = {
82
+ [DG.COLUMN_TYPE.FLOAT]: 'value_num',
83
+ [DG.COLUMN_TYPE.INT]: 'value_num',
84
+ [DG.COLUMN_TYPE.BOOL]: 'value_bool',
85
+ [DG.COLUMN_TYPE.STRING]: 'value_string',
86
+ };
87
+
88
+ let _initialized = false;
89
+ export async function initPlates(force: boolean = false) {
90
+ if (_initialized && !force)
91
+ return;
92
+
93
+ if (!_initialized)
94
+ events.subscribe((event) => grok.shell.info(`${event.on} ${event.eventType} ${event.objectType}`));
95
+
96
+
97
+ plateTemplates = (await api.queries.getPlateTemplates()).toJson();
98
+ plateProperties = (await api.queries.getPlateLevelProperties()).toJson();
99
+ wellProperties = (await api.queries.getWellLevelProperties()).toJson();
100
+ plateTypes = (await api.queries.getPlateTypes()).toJson();
101
+
102
+ plateUniquePropertyValues = await api.queries.getUniquePlatePropertyValues();
103
+ wellUniquePropertyValues = await api.queries.getUniqueWellPropertyValues();
104
+
105
+ const templateWellProperties = (await api.queries.getTemplateWellProperties()).toJson();
106
+ const templatePlateProperties = (await api.queries.getTemplatePlateProperties()).toJson();
107
+ for (const template of plateTemplates) {
108
+ template.wellProperties = templateWellProperties
109
+ .filter((p) => p.template_id == template.id).map((p) => findProp(wellProperties, p.property_id));
110
+ template.plateProperties = templatePlateProperties
111
+ .filter((p) => p.template_id == template.id).map((p) => findProp(plateProperties, p.property_id));
112
+ }
113
+
114
+ _initialized = true;
115
+ }
116
+
117
+
118
+ /** Creates a new plate for a user to edit. Does not add it to the database. */
119
+ export async function createNewPlateForTemplate(plateType: PlateType, plateTemplate: PlateTemplate): Promise<Plate> {
120
+ if (!plateTemplate.plate_layout_id) {
121
+ const plate = new Plate(plateType.rows, plateType.cols);
122
+ for (const property of plateTemplate.wellProperties)
123
+ plate.data.columns.addNew(property.name!, property.type! as DG.ColumnType);
124
+
125
+ return plate;
126
+ }
127
+
128
+ const p = await getPlateById(plateTemplate.plate_layout_id);
129
+ p.id = undefined;
130
+ return p;
131
+ }
132
+
133
+
134
+ export function findProp(props: PlateProperty[], id: number | string): PlateProperty {
135
+ if (typeof id === 'number')
136
+ return props.find((p) => p.id == id)!;
137
+ else
138
+ return props.find((p) => p.name.toLowerCase() == id.toLowerCase())!;
139
+ }
140
+
141
+ export function getUniquePropertyValues(prop: PlateProperty, df: DG.DataFrame): string[] {
142
+ const nameCol = df.col('name')!;
143
+ const valueCol = df.col('value_string')!;
144
+
145
+ return df.rows
146
+ .where((i) => nameCol.get(i) == prop.name)
147
+ .map((i) => valueCol.get(i))
148
+ .toArray();
149
+ }
150
+
151
+
152
+ export function getPlateUniquePropertyValues(prop: PlateProperty): string[] {
153
+ return getUniquePropertyValues(prop, plateUniquePropertyValues);
154
+ }
155
+
156
+ export function getWellUniquePropertyValues(prop: PlateProperty): string[] {
157
+ return getUniquePropertyValues(prop, wellUniquePropertyValues);
158
+ }
159
+
160
+ function getValueType(x: any): string {
161
+ if (typeof x === 'string')
162
+ return DG.TYPE.STRING;
163
+ if (typeof x === 'number')
164
+ return DG.TYPE.FLOAT;
165
+ if (typeof x === 'boolean')
166
+ return DG.TYPE.BOOL;
167
+ throw new Error('Not supported type');
168
+ }
169
+
170
+
171
+ function sqlStr(s?: string | number): string {
172
+ if (!s)
173
+ return 'null';
174
+ if (typeof s == 'string')
175
+ return `'${s}'`;
176
+ else
177
+ return `${s}`;
178
+ }
179
+
180
+
181
+ export async function getPlateById(id: number): Promise<Plate> {
182
+ const df: DG.DataFrame = await api.queries.getWellValuesById(id);
183
+ const plate = Plate.fromDbDataFrame(df);
184
+ events.next({on: 'after', eventType: 'read', objectType: TYPE.PLATE, object: plate});
185
+ return plate;
186
+ }
187
+
188
+
189
+ /**
190
+ * Build SQL that
191
+ * 1) keeps only plates whose plate-level properties match the user's filters
192
+ * 2) returns every plate-level property (name + value) for those plates
193
+ * packed into a single JSONB column called "properties".
194
+ *
195
+ * The JSON looks like:
196
+ * {
197
+ * "Volume": "100.0",
198
+ * "Concentration": "10.5",
199
+ * "Sample": "ABC-123",
200
+ * "Well Role": "DMSO",
201
+ * ...
202
+ * }
203
+ */
204
+ function getPlateSearchSql(query: PlateQuery): string {
205
+ // ---------- 1. Build the boolean conditions for the filter ----------
206
+ const existsClauses: string[] = [];
207
+
208
+ // Handle plate-level property conditions
209
+ for (const condition of query.plateMatchers) {
210
+ const dbColumn = plateDbColumn[condition.property.type];
211
+ existsClauses.push(`
212
+ EXISTS (
213
+ SELECT 1
214
+ FROM plates.plate_details pd_f
215
+ WHERE pd_f.plate_id = p.id
216
+ AND pd_f.property_id = ${condition.property.id}
217
+ AND (${condition.matcher.toSql(`pd_f.${dbColumn}`)})
218
+ )`);
219
+ }
220
+
221
+ // Handle well-level property conditions
222
+ for (const condition of query.wellMatchers) {
223
+ const dbColumn = plateDbColumn[condition.property.type];
224
+ existsClauses.push(`
225
+ EXISTS (
226
+ SELECT 1
227
+ FROM plates.plate_well_values pwv
228
+ WHERE pwv.plate_id = p.id
229
+ AND pwv.property_id = ${condition.property.id}
230
+ AND (${condition.matcher.toSql(`pwv.${dbColumn}`)})
231
+ )`);
232
+ }
233
+
234
+ const whereFilter =
235
+ existsClauses.length > 0 ? `WHERE ${existsClauses.join(' AND ')}` : '';
236
+
237
+ // ---------- 2. Final query – filter first, then collect all properties ----------
238
+ return `
239
+ WITH filtered_plates AS (
240
+ SELECT p.id, p.barcode, p.description
241
+ FROM plates.plates p
242
+ ${whereFilter}
243
+ )
244
+ SELECT
245
+ fp.id AS plate_id,
246
+ fp.barcode,
247
+ fp.description,
248
+ jsonb_pretty(
249
+ jsonb_object_agg(
250
+ pr.name,
251
+ CASE
252
+ WHEN pd.value_string IS NOT NULL THEN to_jsonb(pd.value_string)
253
+ WHEN pd.value_num IS NOT NULL THEN to_jsonb(pd.value_num)
254
+ WHEN pd.value_bool IS NOT NULL THEN to_jsonb(pd.value_bool)
255
+ WHEN pd.value_uuid IS NOT NULL THEN to_jsonb(pd.value_uuid)
256
+ WHEN pd.value_datetime IS NOT NULL THEN to_jsonb(pd.value_datetime)
257
+ ELSE to_jsonb(NULL::text) -- should never happen
258
+ END
259
+ )
260
+ ) AS properties
261
+ FROM filtered_plates fp
262
+ JOIN plates.plate_details pd ON pd.plate_id = fp.id
263
+ JOIN plates.properties pr ON pr.id = pd.property_id
264
+ GROUP BY fp.id, fp.barcode, fp.description
265
+ ORDER BY fp.id;
266
+ `.trim();
267
+ }
268
+
269
+ /**
270
+ * Build SQL that
271
+ * 1) keeps only wells whose plate-level and well-level properties match the user's filters
272
+ * 2) returns every well-level property (name + value) for those wells
273
+ * packed into a single JSONB column called "properties".
274
+ *
275
+ * The JSON looks like:
276
+ * {
277
+ * "Volume": "100.0",
278
+ * "Concentration": "10.5",
279
+ * "Sample": "ABC-123",
280
+ * "Well Role": "DMSO",
281
+ * ...
282
+ * }
283
+ */
284
+ function getWellSearchSql(query: PlateQuery): string {
285
+ // ---------- 1. Build the boolean conditions for the filter ----------
286
+ const whereClauses: string[] = [];
287
+
288
+ // Handle plate-level property conditions (using EXISTS for parent plate)
289
+ for (const condition of query.plateMatchers) {
290
+ const dbColumn = plateDbColumn[condition.property.type];
291
+ whereClauses.push(`
292
+ EXISTS (
293
+ SELECT 1
294
+ FROM plates.plate_details pd_f
295
+ WHERE pd_f.plate_id = pwv.plate_id
296
+ AND pd_f.property_id = ${condition.property.id}
297
+ AND (${condition.matcher.toSql(`pd_f.${dbColumn}`)})
298
+ )`);
299
+ }
300
+
301
+ // Handle well-level property conditions (direct filter on wells)
302
+ for (const condition of query.wellMatchers) {
303
+ const dbColumn = plateDbColumn[condition.property.type];
304
+ whereClauses.push(`
305
+ EXISTS (
306
+ SELECT 1
307
+ FROM plates.plate_well_values pwv_f
308
+ WHERE pwv_f.plate_id = pwv.plate_id
309
+ AND pwv_f.row = pwv.row
310
+ AND pwv_f.col = pwv.col
311
+ AND pwv_f.property_id = ${condition.property.id}
312
+ AND (${condition.matcher.toSql(`pwv_f.${dbColumn}`)})
313
+ )`);
314
+ }
315
+
316
+ const whereFilter =
317
+ whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';
318
+
319
+ // ---------- 2. Final query – filter first, then collect all well properties ----------
320
+ return `
321
+ WITH filtered_wells AS (
322
+ SELECT DISTINCT pwv.plate_id, pwv.row, pwv.col
323
+ FROM plates.plate_well_values pwv
324
+ JOIN plates.plates p ON p.id = pwv.plate_id
325
+ ${whereFilter}
326
+ )
327
+ SELECT
328
+ fw.plate_id,
329
+ p.barcode,
330
+ p.description AS plate_description,
331
+ fw.row,
332
+ fw.col,
333
+ jsonb_pretty(
334
+ jsonb_object_agg(
335
+ pr.name,
336
+ CASE
337
+ WHEN pwv.value_string IS NOT NULL THEN to_jsonb(pwv.value_string)
338
+ WHEN pwv.value_num IS NOT NULL THEN to_jsonb(pwv.value_num)
339
+ WHEN pwv.value_bool IS NOT NULL THEN to_jsonb(pwv.value_bool)
340
+ ELSE to_jsonb(NULL::text) -- should never happen
341
+ END
342
+ )
343
+ ) AS properties
344
+ FROM filtered_wells fw
345
+ JOIN plates.plates p ON p.id = fw.plate_id
346
+ JOIN plates.plate_well_values pwv ON pwv.plate_id = fw.plate_id
347
+ AND pwv.row = fw.row
348
+ AND pwv.col = fw.col
349
+ JOIN plates.properties pr ON pr.id = pwv.property_id
350
+ GROUP BY fw.plate_id, p.barcode, p.description, fw.row, fw.col
351
+ ORDER BY fw.plate_id, fw.row, fw.col;
352
+ `.trim();
353
+ }
354
+
355
+ export async function queryWells(query: PlateQuery): Promise<DG.DataFrame> {
356
+ const df = await grok.data.db.query('Admin:Plates', getWellSearchSql(query));
357
+ DG.Utils.jsonToColumns(df.col('properties')!);
358
+ df.col('properties')!.name = '~properties';
359
+ return df;
360
+ }
361
+
362
+ export async function queryPlates(query: PlateQuery): Promise<DG.DataFrame> {
363
+ const df = await grok.data.db.query('Admin:Plates', getPlateSearchSql(query));
364
+ DG.Utils.jsonToColumns(df.col('properties')!);
365
+ df.col('properties')!.name = '~properties';
366
+ return df;
367
+ }
368
+
369
+ export async function createProperty(prop: Partial<PlateProperty>): Promise<PlateProperty> {
370
+ prop.id = await api.queries.createProperty(prop.name!, prop.type!);
371
+ events.next({on: 'after', eventType: 'created', objectType: TYPE.PROPERTY, object: prop});
372
+ return prop as PlateProperty;
373
+ }
374
+
375
+ /**
376
+ * Saves the plate to the database.
377
+ * When a property is not found in the plateProperties array, it is created automatically
378
+ * if autoCreateProperties is true; otherwise, an error is thrown.
379
+ */
380
+ export async function savePlate(plate: Plate, options?: { autoCreateProperties?: boolean }) {
381
+ const autoCreateProperties = options?.autoCreateProperties ?? true;
382
+ await initPlates();
383
+
384
+ const plateSql =
385
+ `insert into plates.plates(plate_type_id, barcode)
386
+ values(${plate.plateTypeId}, ${sqlStr(plate.barcode)})
387
+ returning id`;
388
+ plate.id = (await grok.data.db.query('Admin:Plates', plateSql)).get('id', 0);
389
+
390
+ // register new plate level properties
391
+ for (const layer of Object.keys(plate.details)) {
392
+ const prop = findProp(plateProperties, layer);
393
+ if (autoCreateProperties && !prop) {
394
+ const valueType = getValueType(plate.details[layer]);
395
+ plateProperties.push(await createProperty({name: layer, type: valueType}));
396
+ grok.shell.info('Plate layer created: ' + layer);
397
+ } else if (!prop) { throw new Error(`Property ${layer} not found in plateProperties`); }
398
+ }
399
+
400
+ // register new well level properties
401
+ for (const layer of plate.getLayerNames()) {
402
+ const prop = findProp(wellProperties, layer);
403
+ if (autoCreateProperties && !prop) {
404
+ const col = plate.data.col(layer);
405
+ wellProperties.push(await createProperty({name: layer, type: col!.type}));
406
+ grok.shell.info('Well layer created: ' + layer);
407
+ } else if (!prop) { throw new Error(`Property ${layer} not found in wellProperties`); }
408
+ }
409
+
410
+ await grok.data.db.query('Admin:Plates', getPlateInsertSql(plate));
411
+ events.next({on: 'after', eventType: 'created', objectType: TYPE.PLATE, object: plate});
412
+ grok.shell.info('Plate saved');
413
+ }
414
+
415
+ export async function savePlateAsTemplate(plate: Plate, template: PlateTemplate) {
416
+ await savePlate(plate);
417
+ const sql = `update plates.templates set plate_layout_id = ${plate.id} where id = ${template.id}`;
418
+ await grok.data.db.query('Admin:Plates', sql);
419
+ }
420
+
421
+
422
+ function getPlateInsertSql(plate: Plate): string {
423
+ let sql = 'insert into plates.plate_wells(plate_id, row, col) values ' +
424
+ plate.wells.map((pw) => ` (${plate.id}, ${pw.row}, ${pw.col})`).toArray().join(',\n') + ';';
425
+
426
+ // plate data
427
+ for (const layer of Object.keys(plate.details)) {
428
+ const property = plateProperties.find((p) => p.name.toLowerCase() == layer.toLowerCase())!;
429
+ const dbCol = plateDbColumn[property.type];
430
+
431
+ sql += `\n insert into plates.plate_details(plate_id, property_id, ${dbCol}) values ` +
432
+ `(${plate.id}, ${property.id}, ${sqlStr(plate.details[layer])});`;
433
+ }
434
+
435
+ // well data
436
+ for (const layer of plate.getLayerNames()) {
437
+ const property = wellProperties.find((p) => p.name.toLowerCase() == layer.toLowerCase())!;
438
+ const dbCol = plateDbColumn[property.type];
439
+ sql += `\n\n insert into plates.plate_well_values(plate_id, row, col, property_id, ${dbCol}) values\n` +
440
+ plate.wells
441
+ .map((pw) => ` (${plate.id}, ${pw.row}, ${pw.col}, ${property.id}, ${sqlStr(pw[layer])})`)
442
+ .toArray().join(',\n') + ';';
443
+ }
444
+
445
+ return sql;
446
+ }
447
+
448
+ export async function createPlateTemplate(template: Partial<PlateTemplate>): Promise<PlateTemplate> {
449
+ template.id = await api.queries.createTemplate(template.name!, template.description!);
450
+ let sql = '';
451
+
452
+ for (let property of template.plateProperties ?? []) {
453
+ property = await createProperty(property);
454
+ plateProperties.push(property as PlateProperty);
455
+ sql += `insert into plates.template_plate_properties(template_id, property_id) values (${template.id}, ${property.id});\n`;
456
+ }
457
+
458
+ for (let property of template.wellProperties ?? []) {
459
+ property = await createProperty(property);
460
+ wellProperties.push(property as PlateProperty);
461
+ sql += `insert into plates.template_well_properties(template_id, property_id) values (${template.id}, ${property.id});\n`;
462
+ }
463
+
464
+ await grok.data.db.query('Admin:Plates', sql);
465
+ plateTemplates.push(template as PlateTemplate);
466
+
467
+ events.next({on: 'after', eventType: 'created', objectType: TYPE.TEMPLATE, object: template});
468
+ return template as PlateTemplate;
469
+ }
470
+
471
+ /** Checks if a plate template's properties are being used in any plates */
472
+ export async function plateTemplatePropertiesUsed(template: PlateTemplate): Promise<boolean> {
473
+ // Check if any plates are using this template's properties
474
+ const sql = `
475
+ SELECT EXISTS (
476
+ SELECT 1 FROM plates.plates p
477
+ JOIN plates.plate_details pd ON p.id = pd.plate_id
478
+ JOIN plates.template_plate_properties tpp ON pd.property_id = tpp.property_id
479
+ WHERE tpp.template_id = ${template.id}
480
+ UNION
481
+ SELECT 1 FROM plates.plates p
482
+ JOIN plates.plate_well_values pwv ON p.id = pwv.plate_id
483
+ JOIN plates.template_well_properties twp ON pwv.property_id = twp.property_id
484
+ WHERE twp.template_id = ${template.id}
485
+ ) as is_used`;
486
+
487
+ const result = await grok.data.db.query('Admin:Plates', sql);
488
+ return result.get('is_used', 0);
489
+ }
490
+
491
+ /** Deletes a plate template and its associated properties */
492
+ export async function deletePlateTemplate(template: PlateTemplate): Promise<void> {
493
+ // First delete the template's property associations
494
+ const deletePropsSql = `
495
+ DELETE FROM plates.template_plate_properties WHERE template_id = ${template.id};
496
+ DELETE FROM plates.template_well_properties WHERE template_id = ${template.id};
497
+ DELETE FROM plates.templates WHERE id = ${template.id};`;
498
+
499
+ await grok.data.db.query('Admin:Plates', deletePropsSql);
500
+ events.next({on: 'after', eventType: 'deleted', objectType: TYPE.TEMPLATE, object: template});
501
+ await initPlates(true); // Refresh the templates cache
502
+ }
@@ -0,0 +1,107 @@
1
+ import { PlateProperty, plateTypes, savePlate } from "./plates-crud";
2
+ import { initPlates } from "./plates-crud";
3
+ import * as DG from 'datagrok-api/dg';
4
+ import * as grok from 'datagrok-api/grok';
5
+ import { createPlateTemplate, createNewPlateForTemplate } from "./plates-crud";
6
+ import { Plate } from '../plate/plate';
7
+
8
+
9
+ export async function __createDummyPlateData() {
10
+ await initPlates(true);
11
+
12
+ await createDummyPlates();
13
+ await createDummyPlatesFromExcel();
14
+
15
+ await initPlates(true);
16
+ }
17
+
18
+ /** Demonstrates construction of templates and plates on the fly */
19
+ async function createDummyPlates() {
20
+ const cellCountingTemplate = await createPlateTemplate({
21
+ name: 'Cell counting',
22
+ description: 'Microscopy-based cell counting',
23
+ plateProperties: [
24
+ {name: 'Imaging device', choices: ['Kodak', 'Nikon'], type: DG.COLUMN_TYPE.STRING},
25
+ {name: 'Status', choices: ['Pending', 'Filling', 'Measuring', 'Done'], type: DG.COLUMN_TYPE.STRING},
26
+ {name: 'Plate cell count', min: 0, max: 10000, type: DG.COLUMN_TYPE.INT}
27
+ ],
28
+ wellProperties: [
29
+ {name: 'Well cell count', min: 0, max: 100, type: DG.COLUMN_TYPE.INT},
30
+ {name: 'Sample', choices: ['GRK-1', 'GRK-2', 'GRK-3', 'GRK-4', 'GRK-5', 'GRK-6'], type: DG.COLUMN_TYPE.STRING}
31
+ ]
32
+ });
33
+
34
+ const doseResponseTemplate = await createPlateTemplate({
35
+ name: 'Dose-response',
36
+ description: 'Dose-response campaign',
37
+ plateProperties: [
38
+ {name: 'Project', type: DG.COLUMN_TYPE.STRING, choices: ['Modulators of mGluR5', 'Agonists for GPCR GPR139', 'Glutaminase Inhibitors for TNBC']},
39
+ {name: 'Stage', type: DG.COLUMN_TYPE.STRING, choices: ['Lead generation', 'Lead optimization']},
40
+ {name: 'Chemist', type: DG.COLUMN_TYPE.STRING, choices: ['John Marlowski', 'Mary Hopton']},
41
+ {name: 'Biologist', type: DG.COLUMN_TYPE.STRING, choices: ['Anna Fei', 'Joan Dvorak']},
42
+ {name: 'QC Passed', type: DG.COLUMN_TYPE.BOOL},
43
+ {name: 'Z-Score', min: 0, max: 3, type: DG.COLUMN_TYPE.FLOAT},
44
+ ],
45
+ wellProperties: [
46
+ {name: 'Sample', choices: ['GRK-1', 'GRK-2', 'GRK-3', 'GRK-4', 'GRK-5', 'GRK-6'], type: DG.COLUMN_TYPE.STRING},
47
+ {name: 'Role', choices: ['Control', 'Treatment'], type: DG.COLUMN_TYPE.STRING},
48
+ {name: 'Concentration', min: 0, max: 100, type: DG.COLUMN_TYPE.FLOAT},
49
+ {name: 'Volume', min: 0, max: 100, type: DG.COLUMN_TYPE.FLOAT},
50
+ {name: 'Activity', min: 0, max: 100, type: DG.COLUMN_TYPE.FLOAT},
51
+ ]
52
+ });
53
+
54
+ await initPlates(true);
55
+
56
+ const getDemoValue = (property: PlateProperty) =>
57
+ property.choices ? DG.Utils.random(property.choices) :
58
+ property.type === DG.COLUMN_TYPE.BOOL ? Math.random() > 0.5 :
59
+ property.min !== undefined && property.max !== undefined ?
60
+ property.type === DG.COLUMN_TYPE.INT ?
61
+ Math.floor(property.min + Math.random() * (property.max - property.min)) :
62
+ property.min + Math.random() * (property.max - property.min) :
63
+ null;
64
+
65
+ for (const template of [cellCountingTemplate, doseResponseTemplate]) {
66
+ for (let i = 0; i < 20; i++) {
67
+ const plate = await createNewPlateForTemplate(plateTypes[0], template);
68
+ plate.details = Object.fromEntries(
69
+ template.plateProperties.map(p => [p.name!, getDemoValue(p as PlateProperty)])
70
+ );
71
+
72
+ // Initialize well properties
73
+ for (const property of template.wellProperties)
74
+ plate.data.col(property!.name!)?.init((_) => getDemoValue(property as PlateProperty));
75
+
76
+ await savePlate(plate);
77
+ }
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Demonstrates importing plates from Excel files
83
+ * and forcing them to comply to the template
84
+ */
85
+ async function createDummyPlatesFromExcel() {
86
+ // create a template for excel plates (you only need to do this once)
87
+ const excelPlateTemplate = await createPlateTemplate({
88
+ name: 'Excel',
89
+ description: 'Excel plates',
90
+ plateProperties: [ {name: 'Barcode', type: DG.COLUMN_TYPE.STRING } ],
91
+ wellProperties: [
92
+ {name: 'raw data', type: DG.COLUMN_TYPE.FLOAT },
93
+ {name: 'plate layout', type: DG.COLUMN_TYPE.STRING},
94
+ {name: 'concentrations', min: 0, max: 100, type: DG.COLUMN_TYPE.FLOAT}
95
+ ]
96
+ });
97
+ await initPlates(true);
98
+
99
+ // import excel plates from the directory
100
+ const xlsxFiles = await grok.dapi.files.list('System.DemoFiles/hts/xlsx_plates', false, '*.xlsx');
101
+ for (const file of xlsxFiles) {
102
+ const plate = await Plate.fromExcelFile(file);
103
+ plate.plateTemplateId = excelPlateTemplate.id;
104
+ plate.details = { Barcode: (Math.round(Math.random() * 100000)).toString().padStart(8, '0') };
105
+ await savePlate(plate, {autoCreateProperties: false});
106
+ }
107
+ }