@datagrok/hit-triage 1.10.0 → 1.10.2
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.
- package/CHANGELOG.md +19 -0
- package/CREDITS.md +101 -0
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/package.json +1 -1
- package/src/app/dialogs/merge-table-dialog.ts +356 -0
- package/src/app/hit-app-base.ts +1 -1
- package/src/app/hit-design-app.ts +26 -42
- package/src/app/hit-design-views/info-view.ts +13 -11
- package/src/app/hit-triage-views/info-view.ts +14 -12
- package/src/app/types.ts +24 -1
- package/src/app/utils/merge-table.ts +364 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/* eslint-disable max-len */
|
|
2
|
+
import * as DG from 'datagrok-api/dg';
|
|
3
|
+
import * as grok from 'datagrok-api/grok';
|
|
4
|
+
import {HitDesignApp} from '../hit-design-app';
|
|
5
|
+
import {HitAppBase} from '../hit-app-base';
|
|
6
|
+
import {HitDesignMergeConfig, HitDesignMergeMode, HitDesignTemplate} from '../types';
|
|
7
|
+
import {HitDesignMolColName, TileCategoriesColName, ViDColName, ViDSemType} from '../consts';
|
|
8
|
+
import {calculateCellValues} from './calculate-single-cell';
|
|
9
|
+
import {registerMolsBatch} from './molreg';
|
|
10
|
+
import {_package} from '../../package';
|
|
11
|
+
|
|
12
|
+
const MOL_NAME_HINTS = ['molecule', 'smiles', 'mol', 'structure', 'canonical_smiles', 'canonicalsmiles'];
|
|
13
|
+
const VID_NAME_HINTS = ['v-id', 'vid', 'v_id'];
|
|
14
|
+
|
|
15
|
+
// Mirrors the drag-n-drop path in HitDesignApp.handleUploadingDataframe: csv goes through
|
|
16
|
+
// DG.DataFrame.fromCsv, anything else is delegated to a registered file-handler function.
|
|
17
|
+
// HitAppBase.molFileExtReaders is statically filtered to only those extensions for which
|
|
18
|
+
// the platform actually exposes a reader, so this list reflects what we can really parse.
|
|
19
|
+
export const MERGE_ALLOWED_EXTENSIONS: string[] = ['csv', ...HitAppBase.molFileExtReaders.map((r) => r.ext)];
|
|
20
|
+
|
|
21
|
+
export function getFileInfoExtension(fi: DG.FileInfo): string {
|
|
22
|
+
const ext = fi.extension?.toLowerCase();
|
|
23
|
+
if (ext) return ext;
|
|
24
|
+
const name = fi.name?.toLowerCase() ?? '';
|
|
25
|
+
const dot = name.lastIndexOf('.');
|
|
26
|
+
return dot >= 0 ? name.slice(dot + 1) : '';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function readFileInfoToDataFrame(fi: DG.FileInfo): Promise<DG.DataFrame | null> {
|
|
30
|
+
const ext = getFileInfoExtension(fi);
|
|
31
|
+
if (ext === 'csv') {
|
|
32
|
+
const text = await fi.readAsString();
|
|
33
|
+
return DG.DataFrame.fromCsv(text);
|
|
34
|
+
}
|
|
35
|
+
const reader = HitAppBase.molFileExtReaders.find((r) => r.ext === ext);
|
|
36
|
+
if (!reader) return null;
|
|
37
|
+
const bytes = await fi.readAsBytes();
|
|
38
|
+
if (!bytes) return null;
|
|
39
|
+
const bytesArg = reader.handlerFunc.inputs[0].name;
|
|
40
|
+
const result: any = await reader.handlerFunc.apply({[bytesArg]: bytes});
|
|
41
|
+
return Array.isArray(result) ? result[0] : result;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function guessMoleculeColumn(df: DG.DataFrame): DG.Column | null {
|
|
45
|
+
const cols = df.columns.toList();
|
|
46
|
+
const semCols = cols.filter((c) => c.semType === DG.SEMTYPE.MOLECULE);
|
|
47
|
+
if (semCols.length > 0) {
|
|
48
|
+
const named = semCols.find((c) => MOL_NAME_HINTS.includes(c.name.toLowerCase()));
|
|
49
|
+
return named ?? semCols[0];
|
|
50
|
+
}
|
|
51
|
+
const named = cols.find((c) => MOL_NAME_HINTS.includes(c.name.toLowerCase()));
|
|
52
|
+
if (named) return named;
|
|
53
|
+
return cols.find((c) => c.type === DG.COLUMN_TYPE.STRING) ?? null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function guessVidColumn(df: DG.DataFrame): DG.Column | null {
|
|
57
|
+
const cols = df.columns.toList();
|
|
58
|
+
const named = cols.find((c) => VID_NAME_HINTS.includes(c.name.toLowerCase()));
|
|
59
|
+
if (named) return named;
|
|
60
|
+
const semCol = cols.find((c) => c.semType === ViDSemType);
|
|
61
|
+
if (semCol) return semCol;
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function isLocalUploadFileInfo(fi: DG.FileInfo): boolean {
|
|
66
|
+
const fullPath = (fi.fullPath ?? '').toLowerCase();
|
|
67
|
+
const name = (fi.name ?? '').toLowerCase();
|
|
68
|
+
return !fullPath || fullPath === name;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type SourceMapping = {col: DG.Column; target: string; isComputed: boolean};
|
|
72
|
+
|
|
73
|
+
function getSourceMappings(
|
|
74
|
+
incomingDf: DG.DataFrame,
|
|
75
|
+
computedDf: DG.DataFrame | null,
|
|
76
|
+
campMolColName: string,
|
|
77
|
+
cfg: HitDesignMergeConfig,
|
|
78
|
+
): SourceMapping[] {
|
|
79
|
+
const sources: SourceMapping[] = [];
|
|
80
|
+
for (const col of incomingDf.columns.toList()) {
|
|
81
|
+
// In SMILES mode, never carry over a V-iD-like column from the incoming table:
|
|
82
|
+
// campaign V-iDs are authoritative.
|
|
83
|
+
if (cfg.mode === 'smiles' && col.name === ViDColName) continue;
|
|
84
|
+
|
|
85
|
+
let target = col.name;
|
|
86
|
+
if (cfg.molColName && col.name === cfg.molColName) target = campMolColName;
|
|
87
|
+
if (cfg.mode === 'vid' && cfg.vidColName && col.name === cfg.vidColName) target = ViDColName;
|
|
88
|
+
|
|
89
|
+
sources.push({col, target, isComputed: false});
|
|
90
|
+
}
|
|
91
|
+
if (computedDf) {
|
|
92
|
+
for (const col of computedDf.columns.toList()) {
|
|
93
|
+
if (col.name === HitDesignMolColName || col.name === campMolColName) continue;
|
|
94
|
+
if (sources.some((s) => s.target === col.name)) continue;
|
|
95
|
+
sources.push({col, target: col.name, isComputed: true});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return sources;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function setCorrectedValue(toCol: DG.Column, fromCol: DG.Column, toIdx: number, fromIdx: number): void {
|
|
102
|
+
try {
|
|
103
|
+
if (toCol.type === fromCol.type) {
|
|
104
|
+
toCol.set(toIdx, fromCol.get(fromIdx), false);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (toCol.type === DG.COLUMN_TYPE.STRING) {
|
|
108
|
+
toCol.set(toIdx, fromCol.getString(fromIdx), false);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const v = fromCol.get(fromIdx);
|
|
112
|
+
if (toCol.type === DG.COLUMN_TYPE.INT) {
|
|
113
|
+
if (typeof v === 'number') toCol.set(toIdx, Math.round(v), false);
|
|
114
|
+
else if (typeof v === 'string' && v.length > 0 && !isNaN(Number(v))) toCol.set(toIdx, Math.round(Number(v)), false);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (toCol.type === DG.COLUMN_TYPE.FLOAT) {
|
|
118
|
+
if (typeof v === 'number') toCol.set(toIdx, v, false);
|
|
119
|
+
else if (typeof v === 'string' && v.length > 0 && !isNaN(Number(v))) toCol.set(toIdx, Number(v), false);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
toCol.set(toIdx, v, false);
|
|
123
|
+
} catch (e) {
|
|
124
|
+
_package.logger.error(`Merge: failed to set ${toCol.name}[${toIdx}] from ${fromCol.name}[${fromIdx}]: ${e}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isCellEmpty(col: DG.Column, idx: number): boolean {
|
|
129
|
+
if (col.isNone(idx)) return true;
|
|
130
|
+
if (col.type === DG.COLUMN_TYPE.STRING) {
|
|
131
|
+
const v = col.get(idx);
|
|
132
|
+
return v === '' || v == null;
|
|
133
|
+
}
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Computes the campaign-side join keys, returns the per-row key array and a key → row map.
|
|
139
|
+
* In SMILES mode the key is the canonical SMILES; in VID mode it's the V-iD string.
|
|
140
|
+
*/
|
|
141
|
+
function buildCampaignKeys(
|
|
142
|
+
campDf: DG.DataFrame,
|
|
143
|
+
campMolColName: string,
|
|
144
|
+
mode: HitDesignMergeMode,
|
|
145
|
+
): {keys: (string | null)[]; map: Map<string, number>} {
|
|
146
|
+
const keys: (string | null)[] = new Array(campDf.rowCount).fill(null);
|
|
147
|
+
const map = new Map<string, number>();
|
|
148
|
+
if (mode === 'smiles') {
|
|
149
|
+
const col = campDf.col(campMolColName);
|
|
150
|
+
if (!col) throw new Error(`Campaign has no molecule column "${campMolColName}"`);
|
|
151
|
+
for (let i = 0; i < campDf.rowCount; i++) {
|
|
152
|
+
const v = col.get(i);
|
|
153
|
+
if (!v) continue;
|
|
154
|
+
const canon = _package.convertToSmiles(v);
|
|
155
|
+
if (canon && canon !== 'MALFORMED_INPUT_VALUE') {
|
|
156
|
+
keys[i] = canon;
|
|
157
|
+
if (!map.has(canon)) map.set(canon, i);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
} else {
|
|
161
|
+
const col = campDf.col(ViDColName);
|
|
162
|
+
if (!col) throw new Error(`Campaign has no "${ViDColName}" column`);
|
|
163
|
+
for (let i = 0; i < campDf.rowCount; i++) {
|
|
164
|
+
const v = col.get(i);
|
|
165
|
+
if (!v) continue;
|
|
166
|
+
keys[i] = v;
|
|
167
|
+
if (!map.has(v)) map.set(v, i);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return {keys, map};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function buildIncomingKeys(incomingDf: DG.DataFrame, cfg: HitDesignMergeConfig): (string | null)[] {
|
|
174
|
+
const keys: (string | null)[] = new Array(incomingDf.rowCount).fill(null);
|
|
175
|
+
if (cfg.mode === 'smiles') {
|
|
176
|
+
const col = incomingDf.col(cfg.molColName!);
|
|
177
|
+
if (!col) throw new Error(`Incoming table has no column "${cfg.molColName}"`);
|
|
178
|
+
for (let i = 0; i < incomingDf.rowCount; i++) {
|
|
179
|
+
const v = col.get(i);
|
|
180
|
+
if (!v) continue;
|
|
181
|
+
const canon = _package.convertToSmiles(v);
|
|
182
|
+
if (canon && canon !== 'MALFORMED_INPUT_VALUE') keys[i] = canon;
|
|
183
|
+
}
|
|
184
|
+
} else {
|
|
185
|
+
const col = incomingDf.col(cfg.vidColName!);
|
|
186
|
+
if (!col) throw new Error(`Incoming table has no column "${cfg.vidColName}"`);
|
|
187
|
+
for (let i = 0; i < incomingDf.rowCount; i++) {
|
|
188
|
+
const v = col.get(i);
|
|
189
|
+
if (v) keys[i] = String(v);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return keys;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Merges `incomingDf` into the current campaign of `app` based on the supplied config.
|
|
197
|
+
* Supports both SMILES-based and V-iD-based joins, optional addition of new rows,
|
|
198
|
+
* and optional execution of the campaign compute pipeline on the incoming molecules.
|
|
199
|
+
*/
|
|
200
|
+
export async function mergeIntoCampaign<T extends HitDesignTemplate>(
|
|
201
|
+
app: HitDesignApp<T>,
|
|
202
|
+
incomingDf: DG.DataFrame,
|
|
203
|
+
cfg: HitDesignMergeConfig,
|
|
204
|
+
): Promise<void> {
|
|
205
|
+
if (!app.dataFrame) throw new Error('Campaign has no data');
|
|
206
|
+
const campDf = app.dataFrame;
|
|
207
|
+
const campMolColName = app.molColName;
|
|
208
|
+
|
|
209
|
+
// Effective flags: silently strip combinations that the dialog should already have prevented.
|
|
210
|
+
const canAddNewRows = cfg.addNewRows && !!cfg.molColName;
|
|
211
|
+
const willRunCompute = cfg.runComputeOnNewRows && canAddNewRows;
|
|
212
|
+
|
|
213
|
+
const {map: campKeyMap} = buildCampaignKeys(campDf, campMolColName, cfg.mode);
|
|
214
|
+
const incKeys = buildIncomingKeys(incomingDf, cfg);
|
|
215
|
+
|
|
216
|
+
// Decide which incoming rows match the campaign and which are net-new BEFORE running
|
|
217
|
+
// compute, so the compute pipeline only runs on the rows that will actually be added.
|
|
218
|
+
const matched: {campRow: number; incRow: number}[] = [];
|
|
219
|
+
const unmatched: number[] = [];
|
|
220
|
+
for (let i = 0; i < incomingDf.rowCount; i++) {
|
|
221
|
+
const k = incKeys[i];
|
|
222
|
+
if (!k) continue;
|
|
223
|
+
const campRow = campKeyMap.get(k);
|
|
224
|
+
if (campRow !== undefined) matched.push({campRow, incRow: i});
|
|
225
|
+
else if (canAddNewRows) unmatched.push(i);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Compute is only run for the unmatched (newly added) molecules, not for matched rows.
|
|
229
|
+
// The resulting DataFrame is row-aligned with `unmatched` (index `u`), not with the
|
|
230
|
+
// original incoming rows.
|
|
231
|
+
let computedDf: DG.DataFrame | null = null;
|
|
232
|
+
if (willRunCompute && cfg.molColName && unmatched.length > 0) {
|
|
233
|
+
const compute = app.campaign?.template?.compute ?? app.template?.compute;
|
|
234
|
+
const incMolCol = incomingDf.col(cfg.molColName);
|
|
235
|
+
if (compute && incMolCol) {
|
|
236
|
+
const newMols = unmatched.map((i) => incMolCol.get(i));
|
|
237
|
+
const descriptors = compute.descriptors.enabled ? compute.descriptors.args ?? [] : [];
|
|
238
|
+
try {
|
|
239
|
+
computedDf = await calculateCellValues(newMols, descriptors, compute.functions, compute.scripts ?? [], compute.queries ?? []);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
_package.logger.error(e);
|
|
242
|
+
grok.shell.warning('Merge: compute pipeline failed; merging without computed columns.');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const sources = getSourceMappings(incomingDf, computedDf, campMolColName, cfg);
|
|
248
|
+
|
|
249
|
+
// Add columns missing in the campaign
|
|
250
|
+
const newlyAdded = new Set<string>();
|
|
251
|
+
for (const s of sources) {
|
|
252
|
+
if (!campDf.columns.contains(s.target)) {
|
|
253
|
+
const nc = campDf.columns.addNew(s.target, s.col.type);
|
|
254
|
+
if (s.col.semType) nc.semType = s.col.semType;
|
|
255
|
+
newlyAdded.add(s.target);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
app.isJoining = true;
|
|
260
|
+
try {
|
|
261
|
+
// Fill matched rows. Computed columns are skipped here — they were only computed for
|
|
262
|
+
// the newly added subset and do not have values aligned with matched incoming rows.
|
|
263
|
+
for (const {campRow, incRow} of matched) {
|
|
264
|
+
for (const s of sources) {
|
|
265
|
+
if (s.isComputed) continue;
|
|
266
|
+
// Don't overwrite the join-key column on matched rows: it already matches by definition.
|
|
267
|
+
if (cfg.mode === 'smiles' && s.target === campMolColName) continue;
|
|
268
|
+
if (cfg.mode === 'vid' && s.target === ViDColName) continue;
|
|
269
|
+
|
|
270
|
+
const targetCol = campDf.col(s.target);
|
|
271
|
+
if (!targetCol) continue;
|
|
272
|
+
const fillEmpty = isCellEmpty(targetCol, campRow);
|
|
273
|
+
if (newlyAdded.has(s.target) || fillEmpty || cfg.clashStrategy === 'overwrite')
|
|
274
|
+
setCorrectedValue(targetCol, s.col, campRow, incRow);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Add unmatched rows.
|
|
279
|
+
const newRowStartIdx = campDf.rowCount;
|
|
280
|
+
if (unmatched.length > 0) {
|
|
281
|
+
const hasStages = (app.stages?.length ?? 0) > 0 && campDf.columns.contains(TileCategoriesColName);
|
|
282
|
+
for (let u = 0; u < unmatched.length; u++) {
|
|
283
|
+
const incRow = unmatched[u];
|
|
284
|
+
campDf.rows.addNew(null, true);
|
|
285
|
+
const newCampRow = campDf.rowCount - 1;
|
|
286
|
+
for (const s of sources) {
|
|
287
|
+
// Computed columns are aligned with the unmatched array (index `u`); incoming
|
|
288
|
+
// columns stay aligned with the original incoming row index.
|
|
289
|
+
const fromIdx = s.isComputed ? u : incRow;
|
|
290
|
+
setCorrectedValue(campDf.col(s.target)!, s.col, newCampRow, fromIdx);
|
|
291
|
+
}
|
|
292
|
+
if (hasStages) {
|
|
293
|
+
const stageCol = campDf.col(TileCategoriesColName)!;
|
|
294
|
+
if (isCellEmpty(stageCol, newCampRow))
|
|
295
|
+
stageCol.set(newCampRow, app.stages[0], false);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Re-register new molecules so they get fresh, dictionary-backed V-iDs.
|
|
300
|
+
// This deliberately overwrites any V-iD value carried over from the incoming table
|
|
301
|
+
// (incoming V-iDs are not authoritative for the campaign).
|
|
302
|
+
if (cfg.molColName) {
|
|
303
|
+
const incMolCol = incomingDf.col(cfg.molColName);
|
|
304
|
+
const campVidCol = campDf.col(ViDColName);
|
|
305
|
+
if (incMolCol && campVidCol && app.campaignId) {
|
|
306
|
+
const newMols = unmatched.map((i) => incMolCol.get(i)).filter((m) => !!m && m !== '');
|
|
307
|
+
if (newMols.length > 0) {
|
|
308
|
+
try {
|
|
309
|
+
const vidMap = await registerMolsBatch(newMols, app.campaignId, app.appName);
|
|
310
|
+
for (let j = 0; j < unmatched.length; j++) {
|
|
311
|
+
const mol = incMolCol.get(unmatched[j]);
|
|
312
|
+
const vid = mol ? vidMap.get(mol) : undefined;
|
|
313
|
+
if (vid) campVidCol.set(newRowStartIdx + j, vid, false);
|
|
314
|
+
}
|
|
315
|
+
} catch (e) {
|
|
316
|
+
_package.logger.error(e);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} finally {
|
|
323
|
+
setTimeout(() => {app.isJoining = false;}, 500);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
campDf.fireValuesChanged();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Runs the implicit "auto-merge on campaign open" pass: if the campaign has a saved
|
|
331
|
+
* mergeConfig with `autoMergeOnOpen` set and a `filePath` from the file share, re-read the
|
|
332
|
+
* file and merge it into the campaign in-place. Compute is force-disabled for this pass
|
|
333
|
+
* and the campaign is NOT saved — the merged state lives in memory until the user saves
|
|
334
|
+
* it themselves. Failures are logged and surfaced as a warning balloon; they never bubble
|
|
335
|
+
* up to the open flow so the campaign still opens.
|
|
336
|
+
*/
|
|
337
|
+
export async function autoMergeOnCampaignOpen<T extends HitDesignTemplate>(
|
|
338
|
+
app: HitDesignApp<T>,
|
|
339
|
+
): Promise<void> {
|
|
340
|
+
const cfg = app.campaign?.mergeConfig;
|
|
341
|
+
if (!cfg?.autoMergeOnOpen || !cfg.filePath) return;
|
|
342
|
+
if (!app.dataFrame) return;
|
|
343
|
+
try {
|
|
344
|
+
const exists = await grok.dapi.files.exists(cfg.filePath);
|
|
345
|
+
if (!exists) {
|
|
346
|
+
grok.shell.warning(`Auto-merge: source file not found or not accessible: ${cfg.filePath}`);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const fi = DG.FileInfo.fromString(cfg.filePath, '');
|
|
350
|
+
const df = await readFileInfoToDataFrame(fi);
|
|
351
|
+
if (!df) {
|
|
352
|
+
grok.shell.warning('Auto-merge: could not read the saved source file; merge skipped.');
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
await df.meta.detectSemanticTypes();
|
|
356
|
+
await grok.data.detectSemanticTypes(df);
|
|
357
|
+
// Compute pipeline never runs on the implicit pass — only structural data flows in.
|
|
358
|
+
const passCfg: HitDesignMergeConfig = {...cfg, runComputeOnNewRows: false};
|
|
359
|
+
await mergeIntoCampaign(app, df, passCfg);
|
|
360
|
+
} catch (e) {
|
|
361
|
+
_package.logger.error(e);
|
|
362
|
+
grok.shell.warning('Auto-merge failed; opening the campaign without merging.');
|
|
363
|
+
}
|
|
364
|
+
}
|