@gcszhn/mol4agent-core 0.3.0 → 0.4.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.
- package/README.md +171 -16
- package/README_zh.md +155 -14
- package/lib/color.d.ts +8 -0
- package/lib/color.js +16 -0
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/inspect-mol.d.ts +28 -0
- package/lib/inspect-mol.js +103 -0
- package/lib/inspect-plugin.d.ts +22 -0
- package/lib/inspect-plugin.js +339 -0
- package/lib/inspect.d.ts +88 -0
- package/lib/inspect.js +189 -0
- package/lib/protocol.d.ts +277 -15
- package/lib/protocol.js +32 -1
- package/lib/represent.d.ts +25 -0
- package/lib/represent.js +191 -0
- package/lib/select.d.ts +12 -0
- package/lib/select.js +41 -1
- package/lib/viewer.d.ts +40 -3
- package/lib/viewer.js +481 -173
- package/package.json +4 -2
package/lib/viewer.js
CHANGED
|
@@ -15,16 +15,22 @@ import { PluginConfig } from 'molstar/lib/mol-plugin/config';
|
|
|
15
15
|
import { applyStructureInteractivity } from 'molstar/lib/extensions/plugin/interactivity';
|
|
16
16
|
import { StateSelection, StateTransform } from 'molstar/lib/mol-state';
|
|
17
17
|
import { MeasurementGroupTag } from 'molstar/lib/mol-plugin-state/manager/structure/measurement';
|
|
18
|
-
import { StructureElement } from 'molstar/lib/mol-model/structure';
|
|
18
|
+
import { QueryContext, StructureElement, StructureSelection } from 'molstar/lib/mol-model/structure';
|
|
19
|
+
import { StructureSelectionQueries } from 'molstar/lib/mol-plugin-state/helpers/structure-selection-query';
|
|
20
|
+
import { StateTransforms } from 'molstar/lib/mol-plugin-state/transforms';
|
|
21
|
+
import { Mat4 } from 'molstar/lib/mol-math/linear-algebra';
|
|
22
|
+
import { alignAndSuperpose } from 'molstar/lib/mol-model/structure/structure/util/superposition';
|
|
23
|
+
import { tmAlign } from 'molstar/lib/mol-model/structure/structure/util/tm-align';
|
|
19
24
|
import { Color } from 'molstar/lib/mol-util/color';
|
|
20
25
|
import lightCss from 'molstar/build/viewer/theme/light.css';
|
|
21
26
|
import darkCss from 'molstar/build/viewer/theme/dark.css';
|
|
22
27
|
import { summarizeStructure } from "./parse/index.js";
|
|
23
28
|
import { molstarFormatOf } from "./formats.js";
|
|
24
|
-
import {
|
|
25
|
-
import { compileSelector, selectorSchema } from "./select.js";
|
|
29
|
+
import { Mol4AgentError, isStructureId, } from "./protocol.js";
|
|
30
|
+
import { compileSelector, describeSelector, selectorExpression, selectorSchema } from "./select.js";
|
|
31
|
+
import { applyRepresentation } from "./represent.js";
|
|
32
|
+
import { inspectViewer } from "./inspect-plugin.js";
|
|
26
33
|
import { formatColor, parseColor } from "./color.js";
|
|
27
|
-
let globalComponentSeq = 0;
|
|
28
34
|
/** Create the official Mol* viewer inside `options.container`. */
|
|
29
35
|
export async function createMolViewer(options) {
|
|
30
36
|
let theme = options.theme ?? 'dark';
|
|
@@ -78,12 +84,14 @@ export async function createMolViewer(options) {
|
|
|
78
84
|
plugin.canvas3d?.setProps({ renderer: { backgroundColor: Color(background) } });
|
|
79
85
|
let pendingFocus;
|
|
80
86
|
const focusLoaded = () => {
|
|
81
|
-
if (pendingFocus === undefined)
|
|
87
|
+
if (pendingFocus === undefined || pendingFocus.length === 0)
|
|
82
88
|
return;
|
|
83
89
|
if (host.clientWidth < 32 || host.clientHeight < 32)
|
|
84
90
|
return;
|
|
85
91
|
plugin.handleResize();
|
|
86
|
-
|
|
92
|
+
// focusLoci accepts several loci; this frames every loaded structure while
|
|
93
|
+
// keeping the single-structure behavior of the original load path.
|
|
94
|
+
plugin.managers.camera.focusLoci(pendingFocus.map(structure => StructureElement.Loci.all(structure)));
|
|
87
95
|
pendingFocus = undefined;
|
|
88
96
|
plugin.canvas3d?.requestDraw();
|
|
89
97
|
};
|
|
@@ -93,8 +101,89 @@ export async function createMolViewer(options) {
|
|
|
93
101
|
plugin.canvas3d?.requestDraw();
|
|
94
102
|
});
|
|
95
103
|
resizeObserver.observe(host);
|
|
96
|
-
|
|
104
|
+
const scene = { entries: [] };
|
|
97
105
|
let disposed = false;
|
|
106
|
+
const nextDefaultId = () => {
|
|
107
|
+
let index = 2;
|
|
108
|
+
while (scene.entries.some(entry => entry.id === `structure-${index}`))
|
|
109
|
+
index += 1;
|
|
110
|
+
return `structure-${index}`;
|
|
111
|
+
};
|
|
112
|
+
const publicEntry = (entry) => ({
|
|
113
|
+
id: entry.id,
|
|
114
|
+
format: entry.format,
|
|
115
|
+
summary: entry.summary,
|
|
116
|
+
...(entry.label === undefined ? {} : { label: entry.label }),
|
|
117
|
+
});
|
|
118
|
+
const addToScene = async (data, options) => {
|
|
119
|
+
const id = options?.id ?? nextDefaultId();
|
|
120
|
+
if (!isStructureId(id)) {
|
|
121
|
+
throw new Mol4AgentError('INVALID_COMMAND', `invalid structure id "${id}"; use 1-64 letters, digits, ".", "_" or "-", starting with a letter or digit`);
|
|
122
|
+
}
|
|
123
|
+
if (scene.entries.some(entry => entry.id === id)) {
|
|
124
|
+
throw new Mol4AgentError('DUPLICATE_STRUCTURE_ID', `structure id "${id}" is already loaded`);
|
|
125
|
+
}
|
|
126
|
+
const descriptor = molstarFormatOf(data.format);
|
|
127
|
+
const label = data.label ?? 'structure';
|
|
128
|
+
const binary = data.binary ?? descriptor.binary;
|
|
129
|
+
// Adapters hand bytes; Mol*'s text parsers need a String data object.
|
|
130
|
+
// Wrapping a PDB/mmCIF file as Binary parses to an empty trajectory.
|
|
131
|
+
const payload = binary
|
|
132
|
+
? data.data
|
|
133
|
+
: typeof data.data === 'string'
|
|
134
|
+
? data.data
|
|
135
|
+
: new TextDecoder('utf-8', { fatal: false }).decode(data.data);
|
|
136
|
+
const dataObject = await plugin.builders.data.rawData({ data: payload, label });
|
|
137
|
+
const trajectory = await plugin.builders.structure.parseTrajectory(dataObject, descriptor.parser);
|
|
138
|
+
const requestedPreset = options?.preset;
|
|
139
|
+
const representationPreset = requestedPreset === undefined || requestedPreset === 'default'
|
|
140
|
+
? undefined
|
|
141
|
+
: requestedPreset;
|
|
142
|
+
const preset = await plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', representationPreset === undefined
|
|
143
|
+
? undefined
|
|
144
|
+
: { representationPreset: representationPreset });
|
|
145
|
+
const presetStructure = preset?.structure;
|
|
146
|
+
const structure = presetStructure?.cell?.obj?.data
|
|
147
|
+
?? plugin.managers.structure.hierarchy.current.structures.at(-1)?.cell.obj?.data;
|
|
148
|
+
const cellRef = presetStructure?.cell?.transform?.ref
|
|
149
|
+
?? plugin.managers.structure.hierarchy.current.structures.at(-1)?.cell.transform.ref;
|
|
150
|
+
if (structure === undefined || cellRef === undefined) {
|
|
151
|
+
throw new Mol4AgentError('LOAD_FAILED', 'Mol* parsed the file but did not build a structure hierarchy; the format may be unsupported for this file');
|
|
152
|
+
}
|
|
153
|
+
const entry = {
|
|
154
|
+
id,
|
|
155
|
+
cellRef,
|
|
156
|
+
format: data.format,
|
|
157
|
+
summary: summarizeSafely(data),
|
|
158
|
+
...(data.label === undefined ? {} : { label: data.label }),
|
|
159
|
+
};
|
|
160
|
+
scene.entries = [...scene.entries, entry];
|
|
161
|
+
scene.summary = entry.summary;
|
|
162
|
+
// Frame the whole scene: after adding a second structure the user needs to
|
|
163
|
+
// see the pair, not just the newcomer that may be far away.
|
|
164
|
+
pendingFocus = scene.entries
|
|
165
|
+
.map(item => rootStructureOf(plugin, item))
|
|
166
|
+
.filter((item) => item !== undefined);
|
|
167
|
+
focusLoaded();
|
|
168
|
+
plugin.canvas3d?.requestDraw();
|
|
169
|
+
return publicEntry(entry);
|
|
170
|
+
};
|
|
171
|
+
const removeFromScene = async (id) => {
|
|
172
|
+
const entry = scene.entries.find(item => item.id === id);
|
|
173
|
+
if (entry === undefined) {
|
|
174
|
+
throw new Mol4AgentError('UNKNOWN_STRUCTURE', `no structure with id "${id}" is loaded`);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
await plugin.managers.structure.hierarchy.remove([entry.cellRef], false);
|
|
178
|
+
}
|
|
179
|
+
catch (reason) {
|
|
180
|
+
throw new Mol4AgentError('INVALID_COMMAND', `could not remove structure "${id}": ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
181
|
+
}
|
|
182
|
+
scene.entries = scene.entries.filter(item => item.id !== id);
|
|
183
|
+
scene.summary = scene.entries.at(-1)?.summary;
|
|
184
|
+
pendingFocus = undefined;
|
|
185
|
+
plugin.canvas3d?.requestDraw();
|
|
186
|
+
};
|
|
98
187
|
const viewerApi = {
|
|
99
188
|
diagnostics() {
|
|
100
189
|
const structures = plugin.managers.structure.hierarchy.current.structures;
|
|
@@ -118,7 +207,7 @@ export async function createMolViewer(options) {
|
|
|
118
207
|
structures: structures.length,
|
|
119
208
|
components,
|
|
120
209
|
representations,
|
|
121
|
-
atoms: summary
|
|
210
|
+
atoms: scene.entries.reduce((count, entry) => count + entry.summary.atomCount, 0),
|
|
122
211
|
};
|
|
123
212
|
},
|
|
124
213
|
async load(data, loadOptions) {
|
|
@@ -147,44 +236,44 @@ export async function createMolViewer(options) {
|
|
|
147
236
|
console.warn('[mol4agent] could not clear the previous structure', reason);
|
|
148
237
|
}
|
|
149
238
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
: requestedPreset;
|
|
166
|
-
const preset = await plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', representationPreset === undefined
|
|
167
|
-
? undefined
|
|
168
|
-
: { representationPreset: representationPreset });
|
|
169
|
-
const structure = preset
|
|
170
|
-
?.structure?.cell?.obj?.data
|
|
171
|
-
?? plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
|
|
172
|
-
if (structure === undefined) {
|
|
173
|
-
throw new Mol4AgentError('LOAD_FAILED', 'Mol* parsed the file but did not build a structure hierarchy; the format may be unsupported for this file');
|
|
174
|
-
}
|
|
175
|
-
pendingFocus = structure;
|
|
176
|
-
focusLoaded();
|
|
177
|
-
summary = summarizeSafely(data);
|
|
178
|
-
plugin.canvas3d?.requestDraw();
|
|
179
|
-
return summary;
|
|
239
|
+
scene.entries = [];
|
|
240
|
+
scene.summary = undefined;
|
|
241
|
+
const entry = await addToScene(data, { ...loadOptions, id: loadOptions?.id ?? 'structure' });
|
|
242
|
+
return entry.summary;
|
|
243
|
+
},
|
|
244
|
+
async addStructure(data, addOptions) {
|
|
245
|
+
assertAlive();
|
|
246
|
+
return addToScene(data, addOptions);
|
|
247
|
+
},
|
|
248
|
+
async removeStructure(id) {
|
|
249
|
+
assertAlive();
|
|
250
|
+
await removeFromScene(id);
|
|
251
|
+
},
|
|
252
|
+
listStructures() {
|
|
253
|
+
return scene.entries.map(publicEntry);
|
|
180
254
|
},
|
|
181
255
|
summary() {
|
|
182
|
-
return summary;
|
|
256
|
+
return scene.summary;
|
|
257
|
+
},
|
|
258
|
+
inspect(request) {
|
|
259
|
+
assertAlive();
|
|
260
|
+
return inspectViewer(plugin, request ?? {}, structureId => {
|
|
261
|
+
const entry = findEntry(scene, structureId);
|
|
262
|
+
if (entry === undefined) {
|
|
263
|
+
throw new Mol4AgentError('UNKNOWN_STRUCTURE', `no structure with id "${structureId}" is loaded`);
|
|
264
|
+
}
|
|
265
|
+
const structure = effectiveStructureOf(plugin, entry);
|
|
266
|
+
return structure === undefined ? [] : [structure];
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
tmScore(request) {
|
|
270
|
+
assertAlive();
|
|
271
|
+
return tmScoreStructures(plugin, scene, request);
|
|
183
272
|
},
|
|
184
273
|
async execute(command) {
|
|
185
274
|
try {
|
|
186
275
|
assertAlive();
|
|
187
|
-
return await executeCommand(plugin, command,
|
|
276
|
+
return await executeCommand(plugin, command, scene, theme);
|
|
188
277
|
}
|
|
189
278
|
catch (error) {
|
|
190
279
|
if (error instanceof Mol4AgentError) {
|
|
@@ -273,129 +362,47 @@ export async function createMolViewer(options) {
|
|
|
273
362
|
}
|
|
274
363
|
return viewerApi;
|
|
275
364
|
}
|
|
276
|
-
async function executeCommand(plugin, command,
|
|
277
|
-
if (
|
|
365
|
+
async function executeCommand(plugin, command, scene, theme) {
|
|
366
|
+
if (scene.entries.length === 0) {
|
|
278
367
|
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'load a structure before sending viewer commands' };
|
|
279
368
|
}
|
|
280
369
|
switch (command.op) {
|
|
281
370
|
case 'represent': {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
const component = await plugin.builders.structure.tryCreateComponentFromExpression(structure.cell, expression, selectionKey(command.target), { label: 'mol4agent selection' });
|
|
308
|
-
if (component === undefined)
|
|
309
|
-
continue;
|
|
310
|
-
const rep = await plugin.builders.structure.representation.addRepresentation(component, {
|
|
311
|
-
type: (style.type ?? 'ball-and-stick'),
|
|
312
|
-
color: (style.color ?? 'uniform'),
|
|
313
|
-
...(colorParams === undefined ? {} : { colorParams: colorParams }),
|
|
314
|
-
}, { tag: 'mol4agent-selection' });
|
|
315
|
-
if (rep !== undefined)
|
|
316
|
-
targeted += 1;
|
|
317
|
-
}
|
|
318
|
-
if (targeted === 0) {
|
|
319
|
-
return {
|
|
320
|
-
ok: false,
|
|
321
|
-
op: command.op,
|
|
322
|
-
code: 'REPRESENT_FAILED',
|
|
323
|
-
message: `Mol* did not create a representation for ${command.target.kind}`,
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
plugin.canvas3d?.requestDraw();
|
|
327
|
-
return {
|
|
328
|
-
ok: true,
|
|
329
|
-
op: command.op,
|
|
330
|
-
message: `applied ${style.type ?? 'ball-and-stick'} / ${style.color ?? 'uniform'}${colorSuffix} to ${command.target.kind}`,
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
const previousComponents = structures.flatMap(structure => [...structure.components]);
|
|
334
|
-
// A single Cartoon representation hides HETATM ligands. Use Mol*'s
|
|
335
|
-
// polymer-and-ligand preset for the default cartoon style so ATP/HEM/etc.
|
|
336
|
-
// stay visible. A uniform colorParams is passed through the preset theme
|
|
337
|
-
// so "gray cartoon" still keeps the ligand representation.
|
|
338
|
-
const polymerAndLigand = style.type === undefined || style.type === 'cartoon';
|
|
339
|
-
let added = 0;
|
|
340
|
-
if (polymerAndLigand) {
|
|
341
|
-
for (const structure of structures) {
|
|
342
|
-
await plugin.builders.structure.representation.applyPreset(structure.cell, 'polymer-and-ligand', {
|
|
343
|
-
theme: {
|
|
344
|
-
globalName: style.color ?? 'chain-id',
|
|
345
|
-
...(colorParams === undefined ? {} : { globalColorParams: colorParams }),
|
|
346
|
-
},
|
|
347
|
-
});
|
|
348
|
-
added += 1;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
else {
|
|
352
|
-
// Representations live under components. Build one fresh all-atom
|
|
353
|
-
// component, then drop the previous components; removing only their
|
|
354
|
-
// reps can take the reused component (and the new reps) with it.
|
|
355
|
-
const all = selectionExpression({ kind: 'all' });
|
|
356
|
-
for (const structure of structures) {
|
|
357
|
-
const component = await plugin.builders.structure.tryCreateComponentFromExpression(structure.cell, all, `mol4agent-global-${globalComponentSeq += 1}`, { label: 'mol4agent global' });
|
|
358
|
-
if (component === undefined)
|
|
359
|
-
continue;
|
|
360
|
-
const rep = await plugin.builders.structure.representation.addRepresentation(component, {
|
|
361
|
-
type: (style.type ?? 'cartoon'),
|
|
362
|
-
color: (style.color ?? 'chain-id'),
|
|
363
|
-
...(colorParams === undefined ? {} : { colorParams: colorParams }),
|
|
364
|
-
});
|
|
365
|
-
if (rep !== undefined)
|
|
366
|
-
added += 1;
|
|
371
|
+
if (command.target?.structureId === undefined)
|
|
372
|
+
return applyRepresentation(plugin, command);
|
|
373
|
+
const scoped = scopedEntries(scene, command.target)
|
|
374
|
+
.map(entry => currentStructureRef(plugin, entry))
|
|
375
|
+
.filter((ref) => ref !== undefined);
|
|
376
|
+
return applyRepresentation(plugin, command, scoped);
|
|
377
|
+
}
|
|
378
|
+
case 'select': {
|
|
379
|
+
const mode = command.mode ?? 'select';
|
|
380
|
+
if (mode === 'select')
|
|
381
|
+
plugin.managers.interactivity.lociSelects.deselectAll();
|
|
382
|
+
let focused = false;
|
|
383
|
+
let matched = 0;
|
|
384
|
+
for (const entry of scopedEntries(scene, command.target)) {
|
|
385
|
+
const loci = lociOfSelector(plugin, entry, command.target);
|
|
386
|
+
if (loci === undefined || StructureElement.Loci.isEmpty(loci))
|
|
387
|
+
continue;
|
|
388
|
+
matched += 1;
|
|
389
|
+
if (mode === 'select')
|
|
390
|
+
plugin.managers.interactivity.lociSelects.select({ loci }, true);
|
|
391
|
+
else
|
|
392
|
+
plugin.managers.interactivity.lociHighlights.highlight({ loci }, true);
|
|
393
|
+
if (command.focus === true && !focused) {
|
|
394
|
+
plugin.managers.camera.focusLoci(loci);
|
|
395
|
+
focused = true;
|
|
367
396
|
}
|
|
368
397
|
}
|
|
369
|
-
if (
|
|
398
|
+
if (matched === 0) {
|
|
370
399
|
return {
|
|
371
400
|
ok: false,
|
|
372
401
|
op: command.op,
|
|
373
|
-
code: '
|
|
374
|
-
message: `
|
|
402
|
+
code: 'NO_STRUCTURE',
|
|
403
|
+
message: `the ${command.target.kind} selector matched no atoms`,
|
|
375
404
|
};
|
|
376
405
|
}
|
|
377
|
-
try {
|
|
378
|
-
// The representation preset updates the existing tagged representations
|
|
379
|
-
// in place. Removing the pre-command refs would remove those updates
|
|
380
|
-
// (the refs are the same transforms), leaving a blank viewport.
|
|
381
|
-
if (!polymerAndLigand && previousComponents.length > 0) {
|
|
382
|
-
await plugin.managers.structure.hierarchy.remove(previousComponents, true);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
catch (reason) {
|
|
386
|
-
console.warn('[mol4agent] could not remove the previous representation', reason);
|
|
387
|
-
}
|
|
388
|
-
plugin.canvas3d?.requestDraw();
|
|
389
|
-
return { ok: true, op: command.op, message: `applied ${style.type ?? 'cartoon'} / ${style.color ?? 'chain-id'}${colorSuffix}` };
|
|
390
|
-
}
|
|
391
|
-
case 'select': {
|
|
392
|
-
const compiled = compileSelector(command.target);
|
|
393
|
-
const mode = command.mode ?? 'select';
|
|
394
|
-
applyStructureInteractivity(plugin, {
|
|
395
|
-
...compiled,
|
|
396
|
-
action: command.focus === true ? [mode, 'focus'] : mode,
|
|
397
|
-
applyGranularity: true,
|
|
398
|
-
});
|
|
399
406
|
return { ok: true, op: command.op, message: `${mode}ed ${command.target.kind}` };
|
|
400
407
|
}
|
|
401
408
|
case 'clear-selection': {
|
|
@@ -405,13 +412,26 @@ async function executeCommand(plugin, command, hasStructure, theme) {
|
|
|
405
412
|
}
|
|
406
413
|
case 'focus': {
|
|
407
414
|
if (command.target === undefined) {
|
|
408
|
-
const
|
|
409
|
-
|
|
415
|
+
const loci = scene.entries
|
|
416
|
+
.map(entry => effectiveStructureOf(plugin, entry))
|
|
417
|
+
.filter((structure) => structure !== undefined)
|
|
418
|
+
.map(structure => StructureElement.Loci.all(structure))
|
|
419
|
+
.filter(loci => !StructureElement.Loci.isEmpty(loci));
|
|
420
|
+
if (loci.length === 0)
|
|
410
421
|
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
|
|
411
|
-
plugin.managers.camera.focusLoci(
|
|
412
|
-
return { ok: true, op: command.op, message: 'focused the whole
|
|
422
|
+
plugin.managers.camera.focusLoci(loci);
|
|
423
|
+
return { ok: true, op: command.op, message: 'focused the whole scene' };
|
|
424
|
+
}
|
|
425
|
+
const loci = [];
|
|
426
|
+
for (const entry of scopedEntries(scene, command.target)) {
|
|
427
|
+
const entryLoci = lociOfSelector(plugin, entry, command.target);
|
|
428
|
+
if (entryLoci !== undefined && !StructureElement.Loci.isEmpty(entryLoci))
|
|
429
|
+
loci.push(entryLoci);
|
|
413
430
|
}
|
|
414
|
-
|
|
431
|
+
if (loci.length === 0) {
|
|
432
|
+
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: `the ${command.target.kind} selector matched no atoms` };
|
|
433
|
+
}
|
|
434
|
+
plugin.managers.camera.focusLoci(loci);
|
|
415
435
|
return { ok: true, op: command.op, message: `focused ${command.target.kind}` };
|
|
416
436
|
}
|
|
417
437
|
case 'camera': {
|
|
@@ -428,15 +448,25 @@ async function executeCommand(plugin, command, hasStructure, theme) {
|
|
|
428
448
|
return { ok: true, op: command.op, message: `background ${formatColor(color)}` };
|
|
429
449
|
}
|
|
430
450
|
case 'measure': {
|
|
431
|
-
const structure = firstStructure(plugin);
|
|
432
|
-
if (structure === undefined) {
|
|
433
|
-
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
|
|
434
|
-
}
|
|
435
451
|
const schemas = command.targets.map(selectorSchema);
|
|
436
452
|
if (schemas.some(schema => schema === undefined)) {
|
|
437
453
|
return invalid(command.op, 'measure targets must be chain/residue/comp/schema selectors, not semantic categories');
|
|
438
454
|
}
|
|
439
|
-
const loci =
|
|
455
|
+
const loci = [];
|
|
456
|
+
for (let index = 0; index < command.targets.length; index += 1) {
|
|
457
|
+
const selector = command.targets[index];
|
|
458
|
+
const schema = schemas[index];
|
|
459
|
+
const entryLoci = lociOfSchema(plugin, scene, selector, schema);
|
|
460
|
+
if (entryLoci === undefined) {
|
|
461
|
+
return {
|
|
462
|
+
ok: false,
|
|
463
|
+
op: command.op,
|
|
464
|
+
code: 'NO_STRUCTURE',
|
|
465
|
+
message: `measure target ${index + 1} matched no atoms`,
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
loci.push(entryLoci);
|
|
469
|
+
}
|
|
440
470
|
const manager = plugin.managers.structure.measurement;
|
|
441
471
|
const needed = command.kind === 'distance' ? 2 : command.kind === 'angle' ? 3 : 4;
|
|
442
472
|
if (loci.length !== needed)
|
|
@@ -453,23 +483,176 @@ async function executeCommand(plugin, command, hasStructure, theme) {
|
|
|
453
483
|
const schema = selectorSchema(command.target);
|
|
454
484
|
if (schema === undefined)
|
|
455
485
|
return invalid(command.op, 'label targets must be chain/residue/comp/schema selectors');
|
|
456
|
-
const
|
|
457
|
-
if (
|
|
458
|
-
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: '
|
|
486
|
+
const loci = lociOfSchema(plugin, scene, command.target, schema);
|
|
487
|
+
if (loci === undefined) {
|
|
488
|
+
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'the label selector matched no atoms' };
|
|
459
489
|
}
|
|
460
|
-
const loci = StructureElement.Schema.toLoci(structure, schema);
|
|
461
490
|
await plugin.managers.structure.measurement.addLabel(loci, command.text === undefined
|
|
462
491
|
? undefined
|
|
463
492
|
: { visualParams: { customText: command.text } });
|
|
464
493
|
return { ok: true, op: command.op, message: 'label added' };
|
|
465
494
|
}
|
|
495
|
+
case 'remove-structure': {
|
|
496
|
+
const entry = findEntry(scene, command.structureId);
|
|
497
|
+
if (entry === undefined) {
|
|
498
|
+
return {
|
|
499
|
+
ok: false,
|
|
500
|
+
op: command.op,
|
|
501
|
+
code: 'UNKNOWN_STRUCTURE',
|
|
502
|
+
message: `no structure with id "${command.structureId}" is loaded`,
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
try {
|
|
506
|
+
await plugin.managers.structure.hierarchy.remove([entry.cellRef], false);
|
|
507
|
+
}
|
|
508
|
+
catch (reason) {
|
|
509
|
+
return {
|
|
510
|
+
ok: false,
|
|
511
|
+
op: command.op,
|
|
512
|
+
code: 'INVALID_COMMAND',
|
|
513
|
+
message: `could not remove structure "${command.structureId}": ${reason instanceof Error ? reason.message : String(reason)}`,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
scene.entries = scene.entries.filter(item => item.id !== command.structureId);
|
|
517
|
+
scene.summary = scene.entries.at(-1)?.summary;
|
|
518
|
+
plugin.canvas3d?.requestDraw();
|
|
519
|
+
return { ok: true, op: command.op, message: `removed structure ${command.structureId}` };
|
|
520
|
+
}
|
|
521
|
+
case 'visibility': {
|
|
522
|
+
const entry = findEntry(scene, command.structureId);
|
|
523
|
+
if (entry === undefined) {
|
|
524
|
+
return {
|
|
525
|
+
ok: false,
|
|
526
|
+
op: command.op,
|
|
527
|
+
code: 'UNKNOWN_STRUCTURE',
|
|
528
|
+
message: `no structure with id "${command.structureId}" is loaded`,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
const ref = currentStructureRef(plugin, entry);
|
|
532
|
+
if (ref === undefined) {
|
|
533
|
+
return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'the structure is no longer in the Mol* hierarchy' };
|
|
534
|
+
}
|
|
535
|
+
plugin.managers.structure.hierarchy.toggleVisibility([ref], command.visible ? 'show' : 'hide');
|
|
536
|
+
plugin.canvas3d?.requestDraw();
|
|
537
|
+
return {
|
|
538
|
+
ok: true,
|
|
539
|
+
op: command.op,
|
|
540
|
+
message: `${command.visible ? 'showed' : 'hid'} structure ${command.structureId}`,
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
case 'align': {
|
|
544
|
+
const reference = findEntry(scene, command.reference);
|
|
545
|
+
const target = findEntry(scene, command.target);
|
|
546
|
+
if (reference === undefined) {
|
|
547
|
+
return {
|
|
548
|
+
ok: false,
|
|
549
|
+
op: command.op,
|
|
550
|
+
code: 'UNKNOWN_STRUCTURE',
|
|
551
|
+
message: `no reference structure with id "${command.reference}" is loaded`,
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
if (target === undefined) {
|
|
555
|
+
return {
|
|
556
|
+
ok: false,
|
|
557
|
+
op: command.op,
|
|
558
|
+
code: 'UNKNOWN_STRUCTURE',
|
|
559
|
+
message: `no target structure with id "${command.target}" is loaded`,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
if (reference.id === target.id) {
|
|
563
|
+
return invalid(command.op, 'reference and target must be different structures');
|
|
564
|
+
}
|
|
565
|
+
const method = command.method ?? 'tm-align';
|
|
566
|
+
if (method !== 'tm-align' && method !== 'sequence') {
|
|
567
|
+
return invalid(command.op, `unknown alignment method "${method}"; supported: tm-align, sequence`);
|
|
568
|
+
}
|
|
569
|
+
const referenceLoci = traceLociOf(plugin, reference, command.referenceChain);
|
|
570
|
+
const targetLoci = traceLociOf(plugin, target, command.targetChain);
|
|
571
|
+
if (referenceLoci === undefined || StructureElement.Loci.isEmpty(referenceLoci)) {
|
|
572
|
+
return {
|
|
573
|
+
ok: false,
|
|
574
|
+
op: command.op,
|
|
575
|
+
code: 'ALIGN_FAILED',
|
|
576
|
+
message: command.referenceChain === undefined
|
|
577
|
+
? `reference structure "${reference.id}" has no polymer trace atoms to align`
|
|
578
|
+
: `reference chain "${command.referenceChain}" has no polymer trace atoms to align`,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
if (targetLoci === undefined || StructureElement.Loci.isEmpty(targetLoci)) {
|
|
582
|
+
return {
|
|
583
|
+
ok: false,
|
|
584
|
+
op: command.op,
|
|
585
|
+
code: 'ALIGN_FAILED',
|
|
586
|
+
message: command.targetChain === undefined
|
|
587
|
+
? `target structure "${target.id}" has no polymer trace atoms to align`
|
|
588
|
+
: `target chain "${command.targetChain}" has no polymer trace atoms to align`,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
let result;
|
|
592
|
+
let bTransform;
|
|
593
|
+
if (method === 'tm-align') {
|
|
594
|
+
const aligned = tmAlign(referenceLoci, targetLoci);
|
|
595
|
+
bTransform = aligned.bTransform;
|
|
596
|
+
result = {
|
|
597
|
+
method,
|
|
598
|
+
reference: reference.id,
|
|
599
|
+
target: target.id,
|
|
600
|
+
rmsd: aligned.rmsd,
|
|
601
|
+
alignedLength: aligned.alignedLength,
|
|
602
|
+
tmScoreA: aligned.tmScoreA,
|
|
603
|
+
tmScoreB: aligned.tmScoreB,
|
|
604
|
+
// Mol*'s structure-level tmAlign wrapper does not pass sequences, so
|
|
605
|
+
// its sequenceIdentity is always 0. Omit it instead of reporting a
|
|
606
|
+
// misleading 0%.
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
const [aligned] = alignAndSuperpose([referenceLoci, targetLoci]);
|
|
611
|
+
if (aligned === undefined) {
|
|
612
|
+
return { ok: false, op: command.op, code: 'ALIGN_FAILED', message: 'sequence alignment produced no transform' };
|
|
613
|
+
}
|
|
614
|
+
bTransform = aligned.bTransform;
|
|
615
|
+
result = {
|
|
616
|
+
method,
|
|
617
|
+
reference: reference.id,
|
|
618
|
+
target: target.id,
|
|
619
|
+
rmsd: aligned.rmsd,
|
|
620
|
+
alignedLength: aligned.nAlignedElements,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
// If the reference is itself already transformed, compose that transform
|
|
624
|
+
// so the target lands on the currently displayed reference pose.
|
|
625
|
+
const referenceTransform = effectiveStructureOf(plugin, reference)?.coordinateSystem.matrix;
|
|
626
|
+
const matrix = referenceTransform !== undefined && !Mat4.isIdentity(referenceTransform)
|
|
627
|
+
? Mat4.mul(Mat4(), referenceTransform, bTransform)
|
|
628
|
+
: bTransform;
|
|
629
|
+
await applyStructureTransform(plugin, target, matrix);
|
|
630
|
+
// The target moved; frame the aligned pair so the result is visible. This
|
|
631
|
+
// mirrors Mol*'s own superposition UI, which resets the camera afterwards.
|
|
632
|
+
const referenceEffective = effectiveStructureOf(plugin, reference);
|
|
633
|
+
const targetEffective = effectiveStructureOf(plugin, target);
|
|
634
|
+
if (referenceEffective !== undefined && targetEffective !== undefined) {
|
|
635
|
+
plugin.managers.camera.focusLoci([
|
|
636
|
+
StructureElement.Loci.all(referenceEffective),
|
|
637
|
+
StructureElement.Loci.all(targetEffective),
|
|
638
|
+
]);
|
|
639
|
+
}
|
|
640
|
+
plugin.canvas3d?.requestDraw();
|
|
641
|
+
const scores = result.tmScoreA === undefined
|
|
642
|
+
? `RMSD ${result.rmsd.toFixed(2)} A over ${result.alignedLength} aligned atoms`
|
|
643
|
+
: `TM-score ${result.tmScoreA.toFixed(4)}/${result.tmScoreB?.toFixed(4)}, RMSD ${result.rmsd.toFixed(2)} A, `
|
|
644
|
+
+ `${result.alignedLength} aligned residues`;
|
|
645
|
+
return {
|
|
646
|
+
ok: true,
|
|
647
|
+
op: command.op,
|
|
648
|
+
message: `aligned ${target.id} onto ${reference.id} (${method}): ${scores}`,
|
|
649
|
+
data: result,
|
|
650
|
+
};
|
|
651
|
+
}
|
|
466
652
|
}
|
|
467
653
|
}
|
|
468
|
-
function
|
|
469
|
-
|
|
470
|
-
return 'elements' in compiled
|
|
471
|
-
? StructureElement.Schema.toExpression(compiled.elements)
|
|
472
|
-
: compiled.expression(undefined);
|
|
654
|
+
function firstStructure(plugin) {
|
|
655
|
+
return plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
|
|
473
656
|
}
|
|
474
657
|
/** Stable key so repeated styles of one selection update the same component. */
|
|
475
658
|
function selectionKey(selector) {
|
|
@@ -480,8 +663,133 @@ function selectionKey(selector) {
|
|
|
480
663
|
}
|
|
481
664
|
return `mol4agent-sel-${(hash >>> 0).toString(36)}`;
|
|
482
665
|
}
|
|
483
|
-
function
|
|
484
|
-
return
|
|
666
|
+
function findEntry(scene, id) {
|
|
667
|
+
return scene.entries.find(entry => entry.id === id);
|
|
668
|
+
}
|
|
669
|
+
/** Entries a selector applies to; an unknown structureId is a model-facing error. */
|
|
670
|
+
function scopedEntries(scene, selector) {
|
|
671
|
+
if (selector.structureId === undefined)
|
|
672
|
+
return scene.entries;
|
|
673
|
+
const entry = findEntry(scene, selector.structureId);
|
|
674
|
+
if (entry === undefined) {
|
|
675
|
+
throw new Mol4AgentError('UNKNOWN_STRUCTURE', `no structure with id "${selector.structureId}" is loaded`);
|
|
676
|
+
}
|
|
677
|
+
return [entry];
|
|
678
|
+
}
|
|
679
|
+
function currentStructureRef(plugin, entry) {
|
|
680
|
+
return plugin.managers.structure.hierarchy.current.structures
|
|
681
|
+
.find(structure => structure.cell.transform.ref === entry.cellRef);
|
|
682
|
+
}
|
|
683
|
+
/** Untransformed structure data; alignment inputs use this plus a composed matrix. */
|
|
684
|
+
function rootStructureOf(plugin, entry) {
|
|
685
|
+
const cell = plugin.state.data.cells.get(entry.cellRef);
|
|
686
|
+
return cell?.obj?.data;
|
|
687
|
+
}
|
|
688
|
+
/** Structure data as currently displayed (after any alignment transform). */
|
|
689
|
+
function effectiveStructureOf(plugin, entry) {
|
|
690
|
+
const ref = currentStructureRef(plugin, entry);
|
|
691
|
+
return ref?.transform?.cell.obj?.data ?? ref?.cell.obj?.data;
|
|
692
|
+
}
|
|
693
|
+
function lociOfSelector(plugin, entry, selector) {
|
|
694
|
+
const structure = effectiveStructureOf(plugin, entry);
|
|
695
|
+
if (structure === undefined)
|
|
696
|
+
return undefined;
|
|
697
|
+
const compiled = compileSelector(selector);
|
|
698
|
+
return 'elements' in compiled
|
|
699
|
+
? StructureElement.Loci.fromSchema(structure, compiled.elements)
|
|
700
|
+
: StructureElement.Loci.fromExpression(structure, compiled.expression(undefined));
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Resolve a schema selector to the first non-empty loci. Without a
|
|
704
|
+
* `structureId`, structures are searched in load order; this keeps single
|
|
705
|
+
* structure behavior and avoids failing when a chain appears in several
|
|
706
|
+
* structures.
|
|
707
|
+
*/
|
|
708
|
+
function lociOfSchema(plugin, scene, selector, schema) {
|
|
709
|
+
for (const entry of scopedEntries(scene, selector)) {
|
|
710
|
+
const structure = effectiveStructureOf(plugin, entry);
|
|
711
|
+
if (structure === undefined)
|
|
712
|
+
continue;
|
|
713
|
+
const loci = StructureElement.Schema.toLoci(structure, schema);
|
|
714
|
+
if (!StructureElement.Loci.isEmpty(loci))
|
|
715
|
+
return loci;
|
|
716
|
+
}
|
|
717
|
+
return undefined;
|
|
718
|
+
}
|
|
719
|
+
/** Polymer trace (CA/C4'/P) loci, optionally restricted to one auth chain. */
|
|
720
|
+
function traceLociOf(plugin, entry, chain) {
|
|
721
|
+
const structure = rootStructureOf(plugin, entry);
|
|
722
|
+
if (structure === undefined)
|
|
723
|
+
return undefined;
|
|
724
|
+
const loci = StructureSelection.toLociWithCurrentUnits(StructureSelectionQueries.trace.query(new QueryContext(structure)));
|
|
725
|
+
if (chain === undefined)
|
|
726
|
+
return loci;
|
|
727
|
+
return StructureElement.Loci.intersect(loci, StructureElement.Loci.fromSchema(structure, { auth_asym_id: chain }));
|
|
728
|
+
}
|
|
729
|
+
/** Resolve one selector to its polymer-trace atoms in the displayed coordinates. */
|
|
730
|
+
function selectorLabel(selector) {
|
|
731
|
+
const label = describeSelector(selector);
|
|
732
|
+
return selector.structureId === undefined ? label : `${label} [${selector.structureId}]`;
|
|
733
|
+
}
|
|
734
|
+
function traceLociForSelector(plugin, scene, selector) {
|
|
735
|
+
for (const entry of scopedEntries(scene, selector)) {
|
|
736
|
+
// TM-align is invariant to rigid transforms, so compare the original
|
|
737
|
+
// coordinates; using a decorated (moved) structure changes atom pairing.
|
|
738
|
+
const structure = rootStructureOf(plugin, entry);
|
|
739
|
+
if (structure === undefined)
|
|
740
|
+
continue;
|
|
741
|
+
const selected = StructureElement.Loci.fromExpression(structure, selectorExpression(selector));
|
|
742
|
+
const trace = StructureSelection.toLociWithCurrentUnits(StructureSelectionQueries.trace.query(new QueryContext(structure)));
|
|
743
|
+
// Keep trace order: TM-align pairs positions by index.
|
|
744
|
+
const loci = StructureElement.Loci.intersect(trace, selected);
|
|
745
|
+
const atoms = StructureElement.Loci.size(loci);
|
|
746
|
+
if (atoms > 0)
|
|
747
|
+
return { label: selectorLabel(selector), loci, atoms };
|
|
748
|
+
}
|
|
749
|
+
throw new Mol4AgentError('TM_SCORE_FAILED', `selection "${selectorLabel(selector)}" has no polymer trace atoms (CA/C4'/P) to compare`);
|
|
750
|
+
}
|
|
751
|
+
/** Read-only TM-align comparison; unlike `align` it applies no transform. */
|
|
752
|
+
function tmScoreStructures(plugin, scene, request) {
|
|
753
|
+
if (scene.entries.length === 0) {
|
|
754
|
+
throw new Mol4AgentError('NO_STRUCTURE', 'load a structure before computing a TM-score');
|
|
755
|
+
}
|
|
756
|
+
const reference = traceLociForSelector(plugin, scene, request.reference);
|
|
757
|
+
const target = traceLociForSelector(plugin, scene, request.target);
|
|
758
|
+
const result = tmAlign(reference.loci, target.loci);
|
|
759
|
+
if (result.alignedLength === 0) {
|
|
760
|
+
throw new Mol4AgentError('TM_SCORE_FAILED', 'TM-align found no aligned residues between the selections');
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
method: 'tm-align',
|
|
764
|
+
reference: reference.label,
|
|
765
|
+
target: target.label,
|
|
766
|
+
rmsd: result.rmsd,
|
|
767
|
+
tmScoreA: result.tmScoreA,
|
|
768
|
+
tmScoreB: result.tmScoreB,
|
|
769
|
+
alignedLength: result.alignedLength,
|
|
770
|
+
referenceAtoms: reference.atoms,
|
|
771
|
+
targetAtoms: target.atoms,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Insert or update the Mol* decorator that moves one structure. The decorator
|
|
776
|
+
* is the sole child of the structure cell, so later components attach below it
|
|
777
|
+
* and render the transformed coordinates.
|
|
778
|
+
*/
|
|
779
|
+
async function applyStructureTransform(plugin, entry, matrix) {
|
|
780
|
+
const params = {
|
|
781
|
+
transform: {
|
|
782
|
+
name: 'matrix',
|
|
783
|
+
params: { data: matrix, transpose: false },
|
|
784
|
+
},
|
|
785
|
+
};
|
|
786
|
+
const existing = plugin.state.data.selectQ(q => q.byRef(entry.cellRef).subtree().withTransformer(StateTransforms.Model.TransformStructureConformation))[0];
|
|
787
|
+
const tree = existing === undefined
|
|
788
|
+
? plugin.state.data.build()
|
|
789
|
+
.to(entry.cellRef)
|
|
790
|
+
.insert(StateTransforms.Model.TransformStructureConformation, params, { tags: ['mol4agent-align'] })
|
|
791
|
+
: plugin.state.data.build().to(existing).update(params);
|
|
792
|
+
await plugin.runTask(plugin.state.data.updateTree(tree));
|
|
485
793
|
}
|
|
486
794
|
function invalid(op, message) {
|
|
487
795
|
return { ok: false, op, code: 'INVALID_COMMAND', message };
|