@gcszhn/mol4agent-core 0.2.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/lib/viewer.js CHANGED
@@ -15,26 +15,34 @@ 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 { COLOR_THEMES, Mol4AgentError, REPRESENTATION_TYPES, } from "./protocol.js";
25
- import { compileSelector, selectorSchema } from "./select.js";
26
- let globalComponentSeq = 0;
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";
33
+ import { formatColor, parseColor } from "./color.js";
27
34
  /** Create the official Mol* viewer inside `options.container`. */
28
35
  export async function createMolViewer(options) {
36
+ let theme = options.theme ?? 'dark';
37
+ const themeBackground = () => (theme === 'dark' ? '#101418' : '#ffffff');
38
+ // Validate adapter-provided background before mounting anything.
39
+ const background = resolveColor(options.background ?? themeBackground());
29
40
  const host = document.createElement('div');
30
41
  host.style.cssText = 'position:relative;width:100%;height:100%;min-height:0;overflow:hidden;';
31
42
  options.container.appendChild(host);
32
43
  // The document body can mount before the sidebar gives it a size. Mol* needs
33
44
  // a real box for its UI and camera; wait for one, then keep following resizes.
34
45
  await waitForHostSize(host, 3000);
35
- let theme = options.theme ?? 'dark';
36
- const themeBackground = () => (theme === 'dark' ? '#101418' : '#ffffff');
37
- const background = options.background ?? themeBackground();
38
46
  const themeStyle = document.createElement('style');
39
47
  themeStyle.dataset.mol4agentTheme = theme;
40
48
  themeStyle.textContent = theme === 'dark' ? darkCss : lightCss;
@@ -73,15 +81,17 @@ export async function createMolViewer(options) {
73
81
  host.remove();
74
82
  throw error;
75
83
  }
76
- plugin.canvas3d?.setProps({ renderer: { backgroundColor: toColor(background) } });
84
+ plugin.canvas3d?.setProps({ renderer: { backgroundColor: Color(background) } });
77
85
  let pendingFocus;
78
86
  const focusLoaded = () => {
79
- if (pendingFocus === undefined)
87
+ if (pendingFocus === undefined || pendingFocus.length === 0)
80
88
  return;
81
89
  if (host.clientWidth < 32 || host.clientHeight < 32)
82
90
  return;
83
91
  plugin.handleResize();
84
- plugin.managers.camera.focusLoci(StructureElement.Loci.all(pendingFocus));
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)));
85
95
  pendingFocus = undefined;
86
96
  plugin.canvas3d?.requestDraw();
87
97
  };
@@ -91,8 +101,89 @@ export async function createMolViewer(options) {
91
101
  plugin.canvas3d?.requestDraw();
92
102
  });
93
103
  resizeObserver.observe(host);
94
- let summary;
104
+ const scene = { entries: [] };
95
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
+ };
96
187
  const viewerApi = {
97
188
  diagnostics() {
98
189
  const structures = plugin.managers.structure.hierarchy.current.structures;
@@ -116,7 +207,7 @@ export async function createMolViewer(options) {
116
207
  structures: structures.length,
117
208
  components,
118
209
  representations,
119
- atoms: summary?.atomCount ?? 0,
210
+ atoms: scene.entries.reduce((count, entry) => count + entry.summary.atomCount, 0),
120
211
  };
121
212
  },
122
213
  async load(data, loadOptions) {
@@ -145,44 +236,44 @@ export async function createMolViewer(options) {
145
236
  console.warn('[mol4agent] could not clear the previous structure', reason);
146
237
  }
147
238
  }
148
- const descriptor = molstarFormatOf(data.format);
149
- const label = data.label ?? 'structure';
150
- const binary = data.binary ?? descriptor.binary;
151
- // Adapters hand bytes; Mol*'s text parsers need a String data object.
152
- // Wrapping a PDB/mmCIF file as Binary parses to an empty trajectory.
153
- const payload = binary
154
- ? data.data
155
- : typeof data.data === 'string'
156
- ? data.data
157
- : new TextDecoder('utf-8', { fatal: false }).decode(data.data);
158
- const dataObject = await plugin.builders.data.rawData({ data: payload, label });
159
- const trajectory = await plugin.builders.structure.parseTrajectory(dataObject, descriptor.parser);
160
- const requestedPreset = loadOptions?.preset;
161
- const representationPreset = requestedPreset === undefined || requestedPreset === 'default'
162
- ? undefined
163
- : requestedPreset;
164
- const preset = await plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', representationPreset === undefined
165
- ? undefined
166
- : { representationPreset: representationPreset });
167
- const structure = preset
168
- ?.structure?.cell?.obj?.data
169
- ?? plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
170
- if (structure === undefined) {
171
- throw new Mol4AgentError('LOAD_FAILED', 'Mol* parsed the file but did not build a structure hierarchy; the format may be unsupported for this file');
172
- }
173
- pendingFocus = structure;
174
- focusLoaded();
175
- summary = summarizeSafely(data);
176
- plugin.canvas3d?.requestDraw();
177
- 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);
178
254
  },
179
255
  summary() {
180
- 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);
181
272
  },
182
273
  async execute(command) {
183
274
  try {
184
275
  assertAlive();
185
- return await executeCommand(plugin, command, summary !== undefined, theme);
276
+ return await executeCommand(plugin, command, scene, theme);
186
277
  }
187
278
  catch (error) {
188
279
  if (error instanceof Mol4AgentError) {
@@ -205,7 +296,7 @@ export async function createMolViewer(options) {
205
296
  themeStyle.dataset.mol4agentTheme = next;
206
297
  themeStyle.textContent = next === 'dark' ? darkCss : lightCss;
207
298
  plugin.canvas3d?.setProps({
208
- renderer: { backgroundColor: toColor(themeBackground()) },
299
+ renderer: { backgroundColor: Color(resolveColor(themeBackground())) },
209
300
  });
210
301
  plugin.canvas3d?.requestDraw();
211
302
  },
@@ -220,6 +311,9 @@ export async function createMolViewer(options) {
220
311
  throw new Mol4AgentError('CAPTURE_FAILED', 'viewport screenshot helper is unavailable');
221
312
  const width = captureOptions?.width ?? 1024;
222
313
  const height = captureOptions?.height ?? 768;
314
+ const captureBackground = captureOptions?.background === undefined
315
+ ? undefined
316
+ : resolveColor(captureOptions.background);
223
317
  const previousBackground = plugin.canvas3d?.props.renderer.backgroundColor;
224
318
  try {
225
319
  helper.behaviors.values.next({
@@ -227,8 +321,8 @@ export async function createMolViewer(options) {
227
321
  resolution: { name: 'custom', params: { width, height } },
228
322
  transparent: captureOptions?.transparent ?? false,
229
323
  });
230
- if (captureOptions?.background !== undefined && plugin.canvas3d !== undefined) {
231
- plugin.canvas3d.setProps({ renderer: { backgroundColor: toColor(captureOptions.background) } });
324
+ if (captureBackground !== undefined && plugin.canvas3d !== undefined) {
325
+ plugin.canvas3d.setProps({ renderer: { backgroundColor: Color(captureBackground) } });
232
326
  }
233
327
  const uri = await helper.getImageDataUri();
234
328
  const comma = uri.indexOf(',');
@@ -268,122 +362,47 @@ export async function createMolViewer(options) {
268
362
  }
269
363
  return viewerApi;
270
364
  }
271
- async function executeCommand(plugin, command, hasStructure, theme) {
272
- if (!hasStructure) {
365
+ async function executeCommand(plugin, command, scene, theme) {
366
+ if (scene.entries.length === 0) {
273
367
  return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'load a structure before sending viewer commands' };
274
368
  }
275
369
  switch (command.op) {
276
370
  case 'represent': {
277
- const style = command.style;
278
- if (style.type !== undefined && !REPRESENTATION_TYPES.includes(style.type)) {
279
- return invalid(command.op, `unknown representation "${style.type}"; supported: ${REPRESENTATION_TYPES.join(', ')}`);
280
- }
281
- if (style.color !== undefined && !COLOR_THEMES.includes(style.color)) {
282
- return invalid(command.op, `unknown colour theme "${style.color}"; supported: ${COLOR_THEMES.join(', ')}`);
283
- }
284
- const structures = plugin.managers.structure.hierarchy.current.structures;
285
- if (structures.length === 0) {
286
- return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
287
- }
288
- // A target means "add this style to a selection", not "replace the whole
289
- // scene". The selection gets its own component so the rest of the
290
- // structure keeps its current representation.
291
- if (command.target !== undefined) {
292
- const expression = selectionExpression(command.target);
293
- let targeted = 0;
294
- for (const structure of structures) {
295
- const component = await plugin.builders.structure.tryCreateComponentFromExpression(structure.cell, expression, selectionKey(command.target), { label: 'mol4agent selection' });
296
- if (component === undefined)
297
- continue;
298
- const rep = await plugin.builders.structure.representation.addRepresentation(component, {
299
- type: (style.type ?? 'ball-and-stick'),
300
- color: (style.color ?? 'uniform'),
301
- ...(style.colorParams === undefined ? {} : { colorParams: style.colorParams }),
302
- }, { tag: 'mol4agent-selection' });
303
- if (rep !== undefined)
304
- targeted += 1;
305
- }
306
- if (targeted === 0) {
307
- return {
308
- ok: false,
309
- op: command.op,
310
- code: 'REPRESENT_FAILED',
311
- message: `Mol* did not create a representation for ${command.target.kind}`,
312
- };
313
- }
314
- plugin.canvas3d?.requestDraw();
315
- return {
316
- ok: true,
317
- op: command.op,
318
- message: `applied ${style.type ?? 'ball-and-stick'} / ${style.color ?? 'uniform'} to ${command.target.kind}`,
319
- };
320
- }
321
- const previousComponents = structures.flatMap(structure => [...structure.components]);
322
- // A single Cartoon representation hides HETATM ligands. Use Mol*'s
323
- // polymer-and-ligand preset for the default cartoon style so ATP/HEM/etc.
324
- // stay visible. A uniform colorParams is passed through the preset theme
325
- // so "gray cartoon" still keeps the ligand representation.
326
- const polymerAndLigand = style.type === undefined || style.type === 'cartoon';
327
- let added = 0;
328
- if (polymerAndLigand) {
329
- for (const structure of structures) {
330
- await plugin.builders.structure.representation.applyPreset(structure.cell, 'polymer-and-ligand', {
331
- theme: {
332
- globalName: style.color ?? 'chain-id',
333
- ...(style.colorParams === undefined ? {} : { globalColorParams: { value: style.colorParams.value } }),
334
- },
335
- });
336
- added += 1;
337
- }
338
- }
339
- else {
340
- // Representations live under components. Build one fresh all-atom
341
- // component, then drop the previous components; removing only their
342
- // reps can take the reused component (and the new reps) with it.
343
- const all = selectionExpression({ kind: 'all' });
344
- for (const structure of structures) {
345
- const component = await plugin.builders.structure.tryCreateComponentFromExpression(structure.cell, all, `mol4agent-global-${globalComponentSeq += 1}`, { label: 'mol4agent global' });
346
- if (component === undefined)
347
- continue;
348
- const rep = await plugin.builders.structure.representation.addRepresentation(component, {
349
- type: (style.type ?? 'cartoon'),
350
- color: (style.color ?? 'chain-id'),
351
- ...(style.colorParams === undefined ? {} : { colorParams: style.colorParams }),
352
- });
353
- if (rep !== undefined)
354
- 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;
355
396
  }
356
397
  }
357
- if (added === 0) {
398
+ if (matched === 0) {
358
399
  return {
359
400
  ok: false,
360
401
  op: command.op,
361
- code: 'REPRESENT_FAILED',
362
- message: `Mol* did not create a representation for ${style.type ?? 'cartoon'}`,
402
+ code: 'NO_STRUCTURE',
403
+ message: `the ${command.target.kind} selector matched no atoms`,
363
404
  };
364
405
  }
365
- try {
366
- // The representation preset updates the existing tagged representations
367
- // in place. Removing the pre-command refs would remove those updates
368
- // (the refs are the same transforms), leaving a blank viewport.
369
- if (!polymerAndLigand && previousComponents.length > 0) {
370
- await plugin.managers.structure.hierarchy.remove(previousComponents, true);
371
- }
372
- }
373
- catch (reason) {
374
- console.warn('[mol4agent] could not remove the previous representation', reason);
375
- }
376
- plugin.canvas3d?.requestDraw();
377
- return { ok: true, op: command.op, message: `applied ${style.type ?? 'cartoon'} / ${style.color ?? 'chain-id'}` };
378
- }
379
- case 'select': {
380
- const compiled = compileSelector(command.target);
381
- const mode = command.mode ?? 'select';
382
- applyStructureInteractivity(plugin, {
383
- ...compiled,
384
- action: command.focus === true ? [mode, 'focus'] : mode,
385
- applyGranularity: true,
386
- });
387
406
  return { ok: true, op: command.op, message: `${mode}ed ${command.target.kind}` };
388
407
  }
389
408
  case 'clear-selection': {
@@ -393,13 +412,26 @@ async function executeCommand(plugin, command, hasStructure, theme) {
393
412
  }
394
413
  case 'focus': {
395
414
  if (command.target === undefined) {
396
- const structure = firstStructure(plugin);
397
- if (structure === undefined)
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)
398
421
  return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
399
- plugin.managers.camera.focusLoci(StructureElement.Loci.all(structure));
400
- return { ok: true, op: command.op, message: 'focused the whole structure' };
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);
430
+ }
431
+ if (loci.length === 0) {
432
+ return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: `the ${command.target.kind} selector matched no atoms` };
401
433
  }
402
- applyStructureInteractivity(plugin, { ...compileSelector(command.target), action: 'focus' });
434
+ plugin.managers.camera.focusLoci(loci);
403
435
  return { ok: true, op: command.op, message: `focused ${command.target.kind}` };
404
436
  }
405
437
  case 'camera': {
@@ -410,21 +442,31 @@ async function executeCommand(plugin, command, hasStructure, theme) {
410
442
  if (plugin.canvas3d === undefined) {
411
443
  return { ok: false, op: command.op, code: 'INVALID_COMMAND', message: 'canvas is unavailable' };
412
444
  }
413
- const color = command.color === 'theme' ? toColor(theme === 'dark' ? '#101418' : '#ffffff') : toColor(command.color);
414
- plugin.canvas3d.setProps({ renderer: { backgroundColor: color } });
445
+ const color = resolveColor(command.color === 'theme' ? (theme === 'dark' ? '#101418' : '#ffffff') : command.color);
446
+ plugin.canvas3d.setProps({ renderer: { backgroundColor: Color(color) } });
415
447
  plugin.canvas3d.requestDraw();
416
- return { ok: true, op: command.op, message: `background ${command.color}` };
448
+ return { ok: true, op: command.op, message: `background ${formatColor(color)}` };
417
449
  }
418
450
  case 'measure': {
419
- const structure = firstStructure(plugin);
420
- if (structure === undefined) {
421
- return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
422
- }
423
451
  const schemas = command.targets.map(selectorSchema);
424
452
  if (schemas.some(schema => schema === undefined)) {
425
453
  return invalid(command.op, 'measure targets must be chain/residue/comp/schema selectors, not semantic categories');
426
454
  }
427
- const loci = schemas.map(schema => StructureElement.Schema.toLoci(structure, schema));
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
+ }
428
470
  const manager = plugin.managers.structure.measurement;
429
471
  const needed = command.kind === 'distance' ? 2 : command.kind === 'angle' ? 3 : 4;
430
472
  if (loci.length !== needed)
@@ -441,23 +483,176 @@ async function executeCommand(plugin, command, hasStructure, theme) {
441
483
  const schema = selectorSchema(command.target);
442
484
  if (schema === undefined)
443
485
  return invalid(command.op, 'label targets must be chain/residue/comp/schema selectors');
444
- const structure = firstStructure(plugin);
445
- if (structure === undefined) {
446
- return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
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' };
447
489
  }
448
- const loci = StructureElement.Schema.toLoci(structure, schema);
449
490
  await plugin.managers.structure.measurement.addLabel(loci, command.text === undefined
450
491
  ? undefined
451
492
  : { visualParams: { customText: command.text } });
452
493
  return { ok: true, op: command.op, message: 'label added' };
453
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
+ }
454
652
  }
455
653
  }
456
- function selectionExpression(selector) {
457
- const compiled = compileSelector(selector);
458
- return 'elements' in compiled
459
- ? StructureElement.Schema.toExpression(compiled.elements)
460
- : compiled.expression(undefined);
654
+ function firstStructure(plugin) {
655
+ return plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
461
656
  }
462
657
  /** Stable key so repeated styles of one selection update the same component. */
463
658
  function selectionKey(selector) {
@@ -468,18 +663,144 @@ function selectionKey(selector) {
468
663
  }
469
664
  return `mol4agent-sel-${(hash >>> 0).toString(36)}`;
470
665
  }
471
- function firstStructure(plugin) {
472
- return plugin.managers.structure.hierarchy.current.structures[0]?.cell.obj?.data;
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));
473
793
  }
474
794
  function invalid(op, message) {
475
795
  return { ok: false, op, code: 'INVALID_COMMAND', message };
476
796
  }
477
- function toColor(value) {
478
- const trimmed = value.trim();
479
- if (/^#[0-9a-f]{6}$/iu.test(trimmed) || /^#[0-9a-f]{8}$/iu.test(trimmed)) {
480
- return Color(Number.parseInt(trimmed.slice(1), 16));
797
+ function resolveColor(value) {
798
+ try {
799
+ return parseColor(value);
800
+ }
801
+ catch (error) {
802
+ throw new Mol4AgentError('INVALID_COMMAND', error instanceof Error ? error.message : String(error));
481
803
  }
482
- return Color(0xffffff);
483
804
  }
484
805
  function decodeBase64(value) {
485
806
  const binary = atob(value);