@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/README.md CHANGED
@@ -25,8 +25,8 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
25
25
  - Input is always `StructureData { data: string | Uint8Array, format, binary?, label? }`.
26
26
  - `format` is explicit; core never inspects a suffix or a MIME type.
27
27
  - No filesystem, network, session, or harness package imports.
28
- - Commands are JSON-serializable; **loading is a method, not a command**, because
29
- adapter-owned bytes may not be serializable.
28
+ - Commands are JSON-serializable; **loading and adding structures are methods,
29
+ not commands**, because adapter-owned bytes may not be serializable.
30
30
  - `@gcszhn/mol4agent-core/parse` is pure and works in Node and the browser.
31
31
  - `@gcszhn/mol4agent-core/sources` is pure too: it turns an entry id into a
32
32
  download plan (`url`, optional JSON `indexField`, format, file name). Network
@@ -40,7 +40,7 @@ pnpm add @gcszhn/mol4agent-core molstar
40
40
  pnpm add react
41
41
  ```
42
42
 
43
- The package is published on npm as `@gcszhn/mol4agent-core@0.2.0`; inside this
43
+ The package is published on npm as `@gcszhn/mol4agent-core@0.4.0`; inside this
44
44
  monorepo, pnpm links the workspace copy instead. `molstar` and `react` are peer
45
45
  dependencies. The DSH adapter bundles Mol* into a single client script; a plain
46
46
  web app can use the package directly.
@@ -60,8 +60,8 @@ Package `exports` point at `lib`, and the npm `files` allowlist includes only
60
60
 
61
61
  | Import | Exports |
62
62
  |---|---|
63
- | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, source helpers, `summarizeStructure`, `compileSelector`, `selectorSchema` |
64
- | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `Mol4AgentError`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
63
+ | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, source helpers, `summarizeStructure`, `compileSelector`, `selectorSchema`, inspection helpers (`buildInspectResult`, `kindOfEntity`, `countCompIds`) |
64
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `InspectRequest` / `InspectResult` / `InspectTarget`, `Mol4AgentError`, `parseColor` / `formatColor` / `COLOR_SYNTAX`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` / `isInspectDetail` guards |
65
65
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`, `summarizePdbLike`, `summarizeCif`, `summarizeSdf`, `summarizeMol2`, `summarizeXyz`, `summarizeGro` |
66
66
  | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`, `SOURCE_DATABASE_INFO`, `resolveSource`, `normalizeSourceDb`, `readSourceIndexField`, and the `isSourceDatabase` guard |
67
67
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
@@ -78,6 +78,9 @@ const viewer = await createMolViewer({
78
78
  })
79
79
 
80
80
  await viewer.load({ data: bytes, format: 'pdb', label: '1crn.pdb' })
81
+ // Optional: add a second structure and align it to the first.
82
+ await viewer.addStructure({ data: otherBytes, format: 'pdb', label: 'target.pdb' }, { id: 'target' })
83
+ await viewer.execute({ op: 'align', reference: 'structure', target: 'target', method: 'tm-align' })
81
84
  await viewer.apply([
82
85
  { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } },
83
86
  { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true },
@@ -96,14 +99,19 @@ stylesheet once per viewer and removes it on `dispose()`.
96
99
  |---|---|---|
97
100
  | `container` | `HTMLElement` | Host element; the viewer fills it with `position:relative;width:100%;height:100%` |
98
101
  | `theme` | `'light' \| 'dark'` | Initial Mol* skin and canvas background |
99
- | `background` | `string` | Optional explicit canvas background |
102
+ | `background` | `string \| number` | Optional explicit canvas background (same colour syntax as `colorParams.value`) |
100
103
 
101
104
  ### `MolViewer`
102
105
 
103
106
  | Method | Signature | Meaning |
104
107
  |---|---|---|
105
- | `load` | `(data: StructureData, options?: { preset?: string }) => Promise<StructureSummary>` | Replace the displayed structure. Text formats passed as bytes are UTF-8 decoded; `binary` is respected. `preset` defaults to `default`; built-ins are `default`, `auto`, `illustrative`, `atomic-detail`, `polymer-and-ligand`, or an adapter-registered preset name. |
106
- | `summary` | `() => StructureSummary \| undefined` | Summary of the current structure, when loaded |
108
+ | `load` | `(data: StructureData, options?: { preset?: string; id?: string }) => Promise<StructureSummary>` | Replace the displayed scene. Clears previous structures, components, and measurements. Text formats passed as bytes are UTF-8 decoded; `binary` is respected. `preset` defaults to `default`; built-ins are `default`, `auto`, `illustrative`, `atomic-detail`, `polymer-and-ligand`, or an adapter-registered preset name. `id` defaults to `structure`. |
109
+ | `addStructure` | `(data: StructureData, options?: { preset?: string; id?: string }) => Promise<LoadedStructure>` | Add another structure without clearing the scene. The id must be unique; when omitted it becomes `structure-2`, `structure-3`, ... |
110
+ | `removeStructure` | `(id: string) => Promise<void>` | Remove one structure and its components |
111
+ | `listStructures` | `() => readonly LoadedStructure[]` | Structures in the scene, in load order |
112
+ | `summary` | `() => StructureSummary \| undefined` | Summary of the most recently loaded structure |
113
+ | `inspect` | `(request?: InspectRequest) => InspectResult` | Read the loaded structure and the way Mol* currently draws it; read-only, see [Inspection](#inspection) |
114
+ | `tmScore` | `(request: TmScoreRequest) => TmScoreResult` | Compute TM-align RMSD/TM-score for two selections without moving either; read-only |
107
115
  | `execute` | `(command: MolCommand) => Promise<CommandResult>` | Run one command; failures are returned as `{ ok: false, code, message }` |
108
116
  | `apply` | `(commands: readonly MolCommand[]) => Promise<readonly CommandResult[]>` | Run commands in order |
109
117
  | `capture` | `(options?: CaptureOptions) => Promise<Uint8Array>` | Render the viewport to PNG |
@@ -118,10 +126,10 @@ stylesheet once per viewer and removes it on `dispose()`.
118
126
  {
119
127
  canvas: { width, height, clientWidth, clientHeight },
120
128
  host: { clientWidth, clientHeight },
121
- structures: number,
129
+ structures: number, // Mol* structure hierarchy entries
122
130
  components: number,
123
131
  representations: number,
124
- atoms: number,
132
+ atoms: number, // sum of every loaded structure's summary
125
133
  }
126
134
  ```
127
135
 
@@ -160,14 +168,17 @@ can be stored in a session log, then replayed after `load()`.
160
168
 
161
169
  | `op` | Fields | Effect |
162
170
  |---|---|---|
163
- | `represent` | `style: StyleSpec`, optional `target` | Without `target`, replace the scene representation. For `cartoon` (or omitted `type`) core uses Mol*'s `polymer-and-ligand` preset so HETATM ligands stay visible. With `target`, add the representation only to that selection (a new Mol* component), leaving the rest untouched. `quality` is accepted but not applied yet. |
171
+ | `represent` | `style: StyleSpec`, optional `target`, optional `replace` | `replace` defaults to `true`: remove the current representations, then draw the new one. `target` only narrows which part the new representation covers; with `replace: true` the whole scene is still cleared first; when `target.structureId` is set, only that structure is cleared. `replace: false` keeps every existing representation and overlays the new one, on the whole structure or on `target` (a new Mol* component). For `cartoon` (or omitted `type`) core uses Mol*'s `polymer-and-ligand` preset so HETATM ligands stay visible. `quality` is accepted but not applied yet. |
164
172
  | `select` | `target`, `mode?: 'select' \| 'highlight'`, `focus?` | Apply Mol* selection interactivity; `focus` moves the camera |
165
173
  | `clear-selection` | `mode?` | Clear select/highlight interactivity |
166
174
  | `focus` | optional `target` | Focus camera on the selection or the whole structure |
167
175
  | `camera` | `action: 'reset'` | Reset the camera |
168
- | `background` | `color: string \| 'theme'` | Set the canvas background |
176
+ | `background` | `color: string \| number \| 'theme'` | Set the canvas background |
169
177
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`, `targets` 2/3/4 | Add a measurement |
170
178
  | `label` | `target`, optional `text` | Add a 3D label |
179
+ | `align` | `reference`, `target`, optional `method`, `referenceChain`, `targetChain` | Superpose target onto reference; `method` is `tm-align` (default) or `sequence` |
180
+ | `remove-structure` | `structureId` | Remove one structure from the scene |
181
+ | `visibility` | `structureId`, `visible` | Show/hide one structure without removing it |
171
182
 
172
183
  Examples:
173
184
 
@@ -184,6 +195,9 @@ Examples:
184
195
  { kind: 'residue', chain: 'A', index: 87 },
185
196
  ] }
186
197
  { op: 'label', target: { kind: 'ligand' }, text: 'ATP' }
198
+ { op: 'align', reference: 'structure', target: 'target', method: 'tm-align', referenceChain: 'A', targetChain: 'A' }
199
+ { op: 'visibility', structureId: 'target', visible: false }
200
+ { op: 'remove-structure', structureId: 'target' }
187
201
  ```
188
202
 
189
203
  ### `StyleSpec`
@@ -199,6 +213,32 @@ Examples:
199
213
  }
200
214
  ```
201
215
 
216
+ ### Colours
217
+
218
+ `color` selects a Mol* colour **theme** (`chain-id`, `element-symbol`, ...).
219
+ `colorParams.value` only affects the `uniform` theme; `color: "uniform"` alone
220
+ is a theme name, not a colour.
221
+
222
+ `colorParams.value` accepts one of:
223
+
224
+ | Form | Examples |
225
+ |---|---|
226
+ | CSS colour name (case-insensitive) | `red`, `lightgrey`, `rebeccapurple` |
227
+ | Hex, optionally with alpha | `#f00`, `#ff0000`, `#ff000080`, `#f008` |
228
+ | `0x` or bare hex | `0xB0B0B0`, `B0B0B0` |
229
+ | `rgb()` / `rgba()` | `rgb(255, 0, 0)`, `rgb(100%, 0%, 0%)`, `rgba(255, 0, 0, 0.5)` |
230
+ | 24-bit integer | `16711680`, `0xff0000` |
231
+
232
+ Alpha is accepted but ignored because Mol* colours and the canvas are opaque.
233
+ The `background` command and `capture({ background })` accept the same forms
234
+ (the command additionally accepts `'theme'`). Values that cannot be parsed
235
+ return `INVALID_COMMAND` instead of silently rendering black; a successful
236
+ `represent` echoes the resolved hex, for example
237
+ `Applied cartoon / uniform #ff0000 to polymer.`
238
+
239
+ Common values: red `0xff0000`, blue `0x0000ff`, white `0xffffff`, grey
240
+ `0x808080`, light grey `0xd3d3d3`.
241
+
202
242
  ### `CommandResult`
203
243
 
204
244
  ```ts
@@ -209,7 +249,8 @@ type CommandResult =
209
249
 
210
250
  Error codes: `INVALID_COMMAND`, `UNSUPPORTED_FORMAT`, `UNSUPPORTED_REPRESENTATION`,
211
251
  `REPRESENT_FAILED`, `NO_STRUCTURE`, `LOAD_FAILED`, `CAPTURE_FAILED`,
212
- `SUMMARY_UNSUPPORTED`, `UNSUPPORTED_SOURCE`, `INVALID_ENTRY_ID`, `DISPOSED`.
252
+ `SUMMARY_UNSUPPORTED`, `UNSUPPORTED_SOURCE`, `INVALID_ENTRY_ID`, `DISPOSED`,
253
+ `UNKNOWN_STRUCTURE`, `DUPLICATE_STRUCTURE_ID`, `ALIGN_FAILED`, `TM_SCORE_FAILED`.
213
254
 
214
255
  ## Selectors
215
256
 
@@ -231,6 +272,12 @@ compiles them to Mol* selection queries or element schemas.
231
272
  | `{ kind: 'comp', compId }` | All residues with a component id |
232
273
  | `{ kind: 'schema', schema }` | Low-level subset of `StructureElement.Schema` |
233
274
 
275
+ Every variant accepts an optional `structureId` to target one structure in a
276
+ multi-structure scene. Omitted means "all loaded structures" for `select`/
277
+ `focus` and "the first matching structure" for `measure`/`label`; `represent`
278
+ with a `target` applies to each structure. This disambiguates two structures
279
+ that both contain chain `A`.
280
+
234
281
  `schema` fields: `auth_asym_id`, `label_asym_id`, `auth_seq_id`, `label_seq_id`,
235
282
  `label_comp_id`, `auth_comp_id`, `beg_auth_seq_id`, `end_auth_seq_id`,
236
283
  `beg_label_seq_id`, `end_label_seq_id`, `label_atom_id`, `auth_atom_id`,
@@ -243,6 +290,83 @@ const compiled = compileSelector({ kind: 'ligand' })
243
290
  const schema = selectorSchema({ kind: 'residues', chain: 'A', start: 10, end: 25 })
244
291
  ```
245
292
 
293
+ ## Inspection
294
+
295
+ `viewer.inspect(request)` reads the loaded structure and the way Mol* currently
296
+ draws it. It is the read counterpart of `execute`: nothing changes, and unlike a
297
+ replayed command log it samples **live** state, so a selection or style a human
298
+ made by clicking or through the Mol* panel is included. In a multi-structure
299
+ scene, a selector with `structureId` inspects only that structure, and
300
+ coordinates come from the transformed (aligned) structure when one is present.
301
+
302
+ ```ts
303
+ const summary = viewer.inspect()
304
+ // summary.counts → [{ compId: 'HOH', kind: 'water', residues: 103, atoms: 103 }, ...]
305
+
306
+ const residue = viewer.inspect({
307
+ target: { kind: 'residue', chain: 'E', index: 355 },
308
+ detail: 'atoms',
309
+ })
310
+ // residue.residueRows[0].atomRows → [{ name: 'PG', element: 'P', x: 16.223, ... }]
311
+ // residue.styles → [{ component: 'Structure', type: 'cartoon', color: 'chain-id',
312
+ // size: 'physical', baseColor: '#1b9e77', visibleColor: '#22bb5b',
313
+ // overlays: [{ source: 'selection', color: '#33ff1a', strength: 0.3 }] }]
314
+ // residue.appearance → { baseColor: '#1b9e77', visibleColor: '#22bb5b', overlays: [...] }
315
+
316
+ const selected = viewer.inspect({ target: { kind: 'selection' }, detail: 'residues' })
317
+ // selected.selection → { entries: 3, residues: 6, atoms: 74,
318
+ // groups: [{ residues: 4, atoms: 36 }, ...] }
319
+ ```
320
+
321
+ | Request field | Meaning |
322
+ |---|---|
323
+ | `target?` | Any [selector](#selectors), or `{ kind: 'selection' }` / `{ kind: 'focus' }` for the live selection manager / the last clicked location. Defaults to the whole structure. |
324
+ | `detail?` | `summary` (default): totals, per-component counts, and styles, no rows. `residues`: additionally residue rows. `atoms`: residue rows with per-atom coordinates. |
325
+ | `limit?` | Residue-row budget, default `DEFAULT_INSPECT_LIMIT` (200). Totals and counts always cover the whole target; `truncated` says whether rows were dropped. |
326
+
327
+ `InspectResult` fields: `target`, `detail`, `atoms`, `residues`, `chains`,
328
+ `models`, `counts`, `residueRows?`, `styles`, `appearance?`, `selection?`,
329
+ `focus?`, `truncated`. `counts` is always present and always complete: it
330
+ answers "how many waters / Cys / ligands" in the default call.
331
+
332
+ Rows carry structure identity (`chain`, `seqId` = auth numbering, `labelSeqId`,
333
+ `compId`, `kind`) and the drawn centre (`x`, `y`, `z`). Atom rows add `name`,
334
+ `element`, coordinates, and `occupancy` / `bFactor` / `altId` when the format
335
+ provides them. Coordinates come from the unit conformation, so they match where
336
+ Mol* draws the atom.
337
+
338
+ Each style reports the representation type, colour theme, size theme,
339
+ colour-theme parameters, `hidden` when Mol* is not drawing it, and both colours
340
+ that matter:
341
+
342
+ | Field | Meaning |
343
+ |---|---|
344
+ | `baseColor` | The colour the representation's own theme gives the inspected element. |
345
+ | `visibleColor` | The colour actually seen: overlays applied to `baseColor`. |
346
+ | `overlays` | The overlays that apply to the inspected element. |
347
+
348
+ Overlays are resolved from live viewer state, in this precedence:
349
+
350
+ 1. **overpaint** (`source: 'overpaint'`) replaces the theme colour for the
351
+ regions a Mol* overpaint layer covers — the last covering layer wins, and a
352
+ `clear` layer removes the paint below it;
353
+ 2. **selection** (`source: 'selection'`) then mixes over the result using
354
+ `canvas3d.props.renderer.selectColor` and `selectStrength`, matching Mol*'s
355
+ marker shader (`#33ff1a` at strength `0.3` in the default theme). A marker
356
+ that only outlines geometry is reported with `hidden: true` and does not
357
+ change `visibleColor`.
358
+
359
+ `appearance` reports the same pair for the target as a whole, using the last
360
+ drawn representation. Colours are sampled at one matched element of the target,
361
+ so under `chain-id` a multi-chain target reports the first chain's colour; query
362
+ the residue itself when its exact colour matters. Per-selection transparency,
363
+ emissive, and substance layers, and script-based overpaint layers, are not
364
+ resolved yet.
365
+
366
+ `inspect` throws `Mol4AgentError` with `NO_STRUCTURE` when nothing is loaded. An
367
+ empty selection or focus is a valid empty result. Low-resolution coarse
368
+ (sphere/gaussian) units have no atom hierarchy and are not listed.
369
+
246
370
  ## Summaries
247
371
 
248
372
  `summarizeStructure` parses bytes without a viewer. It is useful for `mol_info`
@@ -321,7 +445,7 @@ const png = await viewer.capture({
321
445
  width: 1024, // optional; default 1024
322
446
  height: 768, // optional; default 768
323
447
  transparent: true, // optional
324
- background: '#101418', // optional
448
+ background: '#101418', // optional; colour names and integers also work
325
449
  })
326
450
  ```
327
451
 
@@ -332,20 +456,24 @@ const png = await viewer.capture({
332
456
  selectors; semantic categories such as `ligand`/`protein` cannot be converted to
333
457
  a single atom position and return `INVALID_COMMAND`.
334
458
 
335
- Per-selection styling is additive:
459
+ Overlay a selection with `replace: false`:
336
460
 
337
461
  ```ts
338
462
  // gray cartoon for the rest
339
463
  { op: 'represent', style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0x808080 } } }
340
- // red sticks for one interface range
464
+ // red sticks for one interface range, keeping the cartoon
341
465
  { op: 'represent',
342
466
  style: { type: 'ball-and-stick', color: 'uniform', colorParams: { value: 0xff0000 } },
343
- target: { kind: 'residues', chain: 'A', start: 28, end: 54 } }
467
+ target: { kind: 'residues', chain: 'A', start: 28, end: 54 },
468
+ replace: false }
344
469
  ```
345
470
 
346
471
  A global `cartoon` uses the `polymer-and-ligand` preset; `colorParams` is passed
347
- through its theme so `uniform` colors work. A targeted `represent` creates a
348
- separate selection component and does not remove other representations.
472
+ through its theme so `uniform` colors work. A targeted `represent` with
473
+ `replace: false` creates a separate selection component and leaves the rest of
474
+ the scene untouched. Without `replace: false` a targeted `represent` replaces
475
+ the scene like any other command, so the target only limits the new
476
+ representation's coverage.
349
477
 
350
478
  ## React binding
351
479
 
@@ -397,6 +525,59 @@ sequenceDiagram
397
525
  - The DSH adapter bundles core into one client script; see
398
526
  [`packages/deepseek-harness`](../deepseek-harness).
399
527
 
528
+ ## TM-score and RMSD
529
+
530
+ `tmScore()` compares two selections without changing the scene. It is useful
531
+ for scoring chains or regions that were never aligned, or for a read-only check
532
+ after an alignment.
533
+
534
+ ```ts
535
+ const score = viewer.tmScore({
536
+ reference: { kind: 'chain', chain: 'B', structureId: 'reference' },
537
+ target: { kind: 'chain', chain: 'A', structureId: 'target' },
538
+ })
539
+ // { method: 'tm-align', rmsd, tmScoreA, tmScoreB, alignedLength,
540
+ // referenceAtoms, targetAtoms, reference, target }
541
+ ```
542
+
543
+ Both selections are reduced to polymer trace atoms (CA/C4'/P). `rmsd` is
544
+ measured after TM-align's optimal superposition of the aligned trace atoms, not
545
+ in the current camera frame. This is the structure-level `tmAlign` wrapper from
546
+ Mol* (`mol-model/structure/structure/util/tm-align`), not a separate
547
+ reimplementation; no transform is applied to the viewer.
548
+
549
+ ## Multiple structures and alignment
550
+
551
+ `load()` starts a fresh scene; `addStructure()` appends another structure to the
552
+ same Mol* scene. Every structure keeps its own id, components, representations,
553
+ visibility, and measurements.
554
+
555
+ ```ts
556
+ await viewer.load({ data: referenceBytes, format: 'pdb', label: '7czd.pdb' }, { id: 'reference' })
557
+ await viewer.addStructure({ data: targetBytes, format: 'pdb', label: '4zqk.pdb' }, { id: 'target' })
558
+ await viewer.execute({
559
+ op: 'represent',
560
+ style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0xef4444 } },
561
+ target: { kind: 'all', structureId: 'target' },
562
+ })
563
+ const aligned = await viewer.execute({
564
+ op: 'align',
565
+ reference: 'reference',
566
+ target: 'target',
567
+ method: 'tm-align',
568
+ referenceChain: 'B',
569
+ targetChain: 'A',
570
+ })
571
+ // aligned.data: { method, rmsd, alignedLength, tmScoreA, tmScoreB }
572
+ ```
573
+
574
+ Both methods use Mol*'s own superposition utilities
575
+ (`mol-model/structure/structure/util/{superposition,tm-align}`) and its
576
+ `TransformStructureConformation` decorator; no alignment or rendering engine is
577
+ reimplemented here. Alignment moves the target using the polymer trace (CA/C4'/P),
578
+ leaves the reference fixed, and frames the aligned pair. When the reference is already transformed, its
579
+ displayed coordinate system is composed into the target transform.
580
+
400
581
  See [`docs/architecture.md`](../../docs/architecture.md) for the overall
401
582
  architecture; implementation details live in this package's README/AGENTS and
402
583
  in [`packages/deepseek-harness/README.md`](../deepseek-harness/README.md) for
package/README_zh.md CHANGED
@@ -25,7 +25,7 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
25
25
  - 输入永远是 `StructureData { data: string | Uint8Array, format, binary?, label? }`。
26
26
  - `format` 显式给出;core 从不检查后缀或 MIME。
27
27
  - 不引用文件系统、网络、session 或任何 harness 包。
28
- - 命令是 JSON 可序列化的;**加载是方法,不是命令**,因为适配包持有的字节
28
+ - 命令是 JSON 可序列化的;**加载/添加结构是方法,不是命令**,因为适配包持有的字节
29
29
  不一定可序列化。
30
30
  - `@gcszhn/mol4agent-core/parse` 是纯函数,Node 和浏览器都能用。
31
31
  - `@gcszhn/mol4agent-core/sources` 同样是纯函数:把条目 id 变成下载计划
@@ -40,7 +40,7 @@ pnpm add @gcszhn/mol4agent-core molstar
40
40
  pnpm add react
41
41
  ```
42
42
 
43
- 本包已发布到 npm(`@gcszhn/mol4agent-core@0.2.0`);在 monorepo 内 pnpm 会链接
43
+ 本包已发布到 npm(`@gcszhn/mol4agent-core@0.4.0`);在 monorepo 内 pnpm 会链接
44
44
  workspace 版本。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
45
45
  打进单个 client bundle;普通 web 应用可以直接使用本包。
46
46
 
@@ -58,8 +58,8 @@ Package `exports` 指向 `lib`,npm `files` 只包含 `lib` 和 README;`src/`
58
58
 
59
59
  | Import | 导出 |
60
60
  |---|---|
61
- | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、source 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
62
- | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
61
+ | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、source 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema`、查询辅助函数(`buildInspectResult`、`kindOfEntity`、`countCompIds`) |
62
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`InspectRequest` / `InspectResult` / `InspectTarget`、`Mol4AgentError`、`parseColor` / `formatColor` / `COLOR_SYNTAX`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` / `isInspectDetail` 守卫 |
63
63
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`、`summarizePdbLike`、`summarizeCif`、`summarizeSdf`、`summarizeMol2`、`summarizeXyz`、`summarizeGro` |
64
64
  | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`、`SOURCE_DATABASE_INFO`、`resolveSource`、`normalizeSourceDb`、`readSourceIndexField`,以及 `isSourceDatabase` 守卫 |
65
65
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`、`Mol4AgentViewerHandle`、`Mol4AgentScene` |
@@ -76,6 +76,9 @@ const viewer = await createMolViewer({
76
76
  })
77
77
 
78
78
  await viewer.load({ data: bytes, format: 'pdb', label: '1crn.pdb' })
79
+ // 可选:把第二个结构加入同一场景并做结构叠合。
80
+ await viewer.addStructure({ data: otherBytes, format: 'pdb', label: 'target.pdb' }, { id: 'target' })
81
+ await viewer.execute({ op: 'align', reference: 'structure', target: 'target', method: 'tm-align' })
79
82
  await viewer.apply([
80
83
  { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } },
81
84
  { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true },
@@ -94,14 +97,19 @@ viewer.dispose()
94
97
  |---|---|---|
95
98
  | `container` | `HTMLElement` | 宿主元素;viewer 用 `position:relative;width:100%;height:100%` 填满 |
96
99
  | `theme` | `'light' \| 'dark'` | 初始 Mol* 皮肤和画布背景 |
97
- | `background` | `string` | 可选,显式指定画布背景 |
100
+ | `background` | `string \| number` | 可选,显式指定画布背景(颜色语法同 `colorParams.value`) |
98
101
 
99
102
  ### `MolViewer`
100
103
 
101
104
  | 方法 | 签名 | 含义 |
102
105
  |---|---|---|
103
- | `load` | `(data: StructureData, options?: { preset?: string }) => Promise<StructureSummary>` | 替换当前结构。文本 format 以字节传入时会做 UTF-8 解码;`binary` 会被尊重。`preset` 默认 `default`;内置值有 `default`、`auto`、`illustrative`、`atomic-detail`、`polymer-and-ligand`,也可以传适配包注册的自定义 preset 名。 |
106
+ | `load` | `(data: StructureData, options?: { preset?: string; id?: string }) => Promise<StructureSummary>` | 替换整个场景,并清空旧结构、component 和测量。文本 format 以字节传入时会做 UTF-8 解码;`binary` 会被尊重。`preset` 默认 `default`;内置值有 `default`、`auto`、`illustrative`、`atomic-detail`、`polymer-and-ligand`,也可以传适配包注册的自定义 preset 名。`id` 默认 `structure`。 |
107
+ | `addStructure` | `(data: StructureData, options?: { preset?: string; id?: string }) => Promise<LoadedStructure>` | 向当前场景追加结构,不清空已有结构。id 必须唯一;省略时为 `structure-2`、`structure-3`…… |
108
+ | `removeStructure` | `(id: string) => Promise<void>` | 移除一个结构及其 component |
109
+ | `listStructures` | `() => readonly LoadedStructure[]` | 按加载顺序列出场景中的结构 |
104
110
  | `summary` | `() => StructureSummary \| undefined` | 当前结构的摘要(若已加载) |
111
+ | `inspect` | `(request?: InspectRequest) => InspectResult` | 读取已加载结构和 Mol* 当前绘制方式;只读,见[查询](#查询) |
112
+ | `tmScore` | `(request: TmScoreRequest) => TmScoreResult` | 只读计算两个选择的 TM-align RMSD/TM-score,不移动任何结构 |
105
113
  | `execute` | `(command: MolCommand) => Promise<CommandResult>` | 执行一条命令;失败返回 `{ ok: false, code, message }` |
106
114
  | `apply` | `(commands: readonly MolCommand[]) => Promise<readonly CommandResult[]>` | 按顺序执行多条命令 |
107
115
  | `capture` | `(options?: CaptureOptions) => Promise<Uint8Array>` | 把当前视图渲染成 PNG |
@@ -116,10 +124,10 @@ viewer.dispose()
116
124
  {
117
125
  canvas: { width, height, clientWidth, clientHeight },
118
126
  host: { clientWidth, clientHeight },
119
- structures: number,
127
+ structures: number, // Mol* 结构层级条目数
120
128
  components: number,
121
129
  representations: number,
122
- atoms: number,
130
+ atoms: number, // 所有已加载结构 summary 的原子数之和
123
131
  }
124
132
  ```
125
133
 
@@ -157,14 +165,17 @@ interface StructureData {
157
165
 
158
166
  | `op` | 字段 | 效果 |
159
167
  |---|---|---|
160
- | `represent` | `style: StyleSpec`,可选 `target` | 不传 `target` 时替换整个场景的表示。`type` 为 `cartoon` 或省略时,core 用 Mol* 的 `polymer-and-ligand` preset,保证 HETATM 配体仍然可见。传 `target` 时只为该选择添加表示(新建 Mol* component),其余保持不变。`quality` 协议里有字段,但目前尚未生效。 |
168
+ | `represent` | `style: StyleSpec`,可选 `target`,可选 `replace` | `replace` 默认 `true`:先删除当前表示,再绘制新表示。`target` 只限定新表示覆盖哪部分;`replace: true` 时整个场景仍会先被清空;若 `target.structureId` 已指定,则只清空该结构。`replace: false` 保留所有已有表示并叠加新表示,可作用于整个结构,也可作用于 `target`(新建 Mol* component)。`type` 为 `cartoon` 或省略时,core 用 Mol* 的 `polymer-and-ligand` preset,保证 HETATM 配体仍然可见。`quality` 协议里有字段,但目前尚未生效。 |
161
169
  | `select` | `target`,`mode?: 'select' \| 'highlight'`,`focus?` | 应用 Mol* 选择交互;`focus` 会移动镜头 |
162
170
  | `clear-selection` | `mode?` | 清除 select/highlight 交互 |
163
171
  | `focus` | 可选 `target` | 聚焦选择或整个结构 |
164
172
  | `camera` | `action: 'reset'` | 重置镜头 |
165
- | `background` | `color: string \| 'theme'` | 设置画布背景 |
173
+ | `background` | `color: string \| number \| 'theme'` | 设置画布背景 |
166
174
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`,`targets` 2/3/4 个 | 添加测量 |
167
175
  | `label` | `target`,可选 `text` | 添加 3D 标签 |
176
+ | `align` | `reference`、`target`,可选 `method`、`referenceChain`、`targetChain` | 把 target 叠合到 reference;`method` 为 `tm-align`(默认)或 `sequence` |
177
+ | `remove-structure` | `structureId` | 从场景移除一个结构 |
178
+ | `visibility` | `structureId`、`visible` | 显示/隐藏一个结构,但不移除 |
168
179
 
169
180
  示例:
170
181
 
@@ -181,6 +192,9 @@ interface StructureData {
181
192
  { kind: 'residue', chain: 'A', index: 87 },
182
193
  ] }
183
194
  { op: 'label', target: { kind: 'ligand' }, text: 'ATP' }
195
+ { op: 'align', reference: 'structure', target: 'target', method: 'tm-align', referenceChain: 'A', targetChain: 'A' }
196
+ { op: 'visibility', structureId: 'target', visible: false }
197
+ { op: 'remove-structure', structureId: 'target' }
184
198
  ```
185
199
 
186
200
  ### `StyleSpec`
@@ -196,6 +210,30 @@ interface StructureData {
196
210
  }
197
211
  ```
198
212
 
213
+ ### 颜色
214
+
215
+ `color` 选择 Mol* 的颜色**主题**(`chain-id`、`element-symbol` 等);
216
+ `colorParams.value` 只对 `uniform` 主题生效。单独写 `color: "uniform"` 只是主题
217
+ 名,不是具体颜色。
218
+
219
+ `colorParams.value` 接受以下形式:
220
+
221
+ | 形式 | 示例 |
222
+ |---|---|
223
+ | CSS 颜色名(大小写不敏感) | `red`、`lightgrey`、`rebeccapurple` |
224
+ | 十六进制,可带 alpha | `#f00`、`#ff0000`、`#ff000080`、`#f008` |
225
+ | `0x` 或裸十六进制 | `0xB0B0B0`、`B0B0B0` |
226
+ | `rgb()` / `rgba()` | `rgb(255, 0, 0)`、`rgb(100%, 0%, 0%)`、`rgba(255, 0, 0, 0.5)` |
227
+ | 24 位整数 | `16711680`、`0xff0000` |
228
+
229
+ alpha 会被接受但忽略,因为 Mol* 颜色与画布都是不透明的。`background` 命令与
230
+ `capture({ background })` 接受相同形式(命令还额外接受 `'theme'`)。无法解析的
231
+ 值返回 `INVALID_COMMAND`,不会再静默渲染成黑色;成功的 `represent` 会回显解析后
232
+ 的十六进制颜色,例如 `Applied cartoon / uniform #ff0000 to polymer.`。
233
+
234
+ 常用值:红 `0xff0000`、蓝 `0x0000ff`、白 `0xffffff`、灰 `0x808080`、
235
+ 浅灰 `0xd3d3d3`。
236
+
199
237
  ### `CommandResult`
200
238
 
201
239
  ```ts
@@ -206,7 +244,8 @@ type CommandResult =
206
244
 
207
245
  错误码:`INVALID_COMMAND`、`UNSUPPORTED_FORMAT`、`UNSUPPORTED_REPRESENTATION`、
208
246
  `REPRESENT_FAILED`、`NO_STRUCTURE`、`LOAD_FAILED`、`CAPTURE_FAILED`、
209
- `SUMMARY_UNSUPPORTED`、`UNSUPPORTED_SOURCE`、`INVALID_ENTRY_ID`、`DISPOSED`。
247
+ `SUMMARY_UNSUPPORTED`、`UNSUPPORTED_SOURCE`、`INVALID_ENTRY_ID`、`DISPOSED`、
248
+ `UNKNOWN_STRUCTURE`、`DUPLICATE_STRUCTURE_ID`、`ALIGN_FAILED`、`TM_SCORE_FAILED`。
210
249
 
211
250
  ## 选择器
212
251
 
@@ -228,6 +267,10 @@ query 或 element schema。
228
267
  | `{ kind: 'comp', compId }` | 指定 component id 的所有残基 |
229
268
  | `{ kind: 'schema', schema }` | 底层 `StructureElement.Schema` 子集 |
230
269
 
270
+ 每个变体都接受可选的 `structureId`,用于在多结构场景中指定某一个结构。省略时:
271
+ `select`/`focus` 作用于所有已加载结构,`measure`/`label` 取第一个匹配的结构,
272
+ 带 `target` 的 `represent` 逐个结构应用。这样可以区分两个都含链 `A` 的结构。
273
+
231
274
  `schema` 字段:`auth_asym_id`、`label_asym_id`、`auth_seq_id`、`label_seq_id`、
232
275
  `label_comp_id`、`auth_comp_id`、`beg_auth_seq_id`、`end_auth_seq_id`、
233
276
  `beg_label_seq_id`、`end_label_seq_id`、`label_atom_id`、`auth_atom_id`、
@@ -240,6 +283,76 @@ const compiled = compileSelector({ kind: 'ligand' })
240
283
  const schema = selectorSchema({ kind: 'residues', chain: 'A', start: 10, end: 25 })
241
284
  ```
242
285
 
286
+ ## 查询
287
+
288
+ `viewer.inspect(request)` 读取已加载结构以及 Mol* 当前的绘制方式。它是
289
+ `execute` 的读侧对应物:不改变任何状态,而且不像回放的命令日志那样只反映
290
+ agent 自己的操作,它采样的是**实时**状态,因此人通过点击或 Mol* 面板做出的
291
+ 选择和样式也会被读到。多结构场景中,带 `structureId` 的选择器只检查该结构;
292
+ 如果结构已有叠合变换,坐标取变换后的当前显示位置。
293
+
294
+ ```ts
295
+ const summary = viewer.inspect()
296
+ // summary.counts → [{ compId: 'HOH', kind: 'water', residues: 103, atoms: 103 }, ...]
297
+
298
+ const residue = viewer.inspect({
299
+ target: { kind: 'residue', chain: 'E', index: 355 },
300
+ detail: 'atoms',
301
+ })
302
+ // residue.residueRows[0].atomRows → [{ name: 'PG', element: 'P', x: 16.223, ... }]
303
+ // residue.styles → [{ component: 'Structure', type: 'cartoon', color: 'chain-id',
304
+ // size: 'physical', baseColor: '#1b9e77', visibleColor: '#22bb5b',
305
+ // overlays: [{ source: 'selection', color: '#33ff1a', strength: 0.3 }] }]
306
+ // residue.appearance → { baseColor: '#1b9e77', visibleColor: '#22bb5b', overlays: [...] }
307
+
308
+ const selected = viewer.inspect({ target: { kind: 'selection' }, detail: 'residues' })
309
+ // selected.selection → { entries: 3, residues: 6, atoms: 74,
310
+ // groups: [{ residues: 4, atoms: 36 }, ...] }
311
+ ```
312
+
313
+ | 请求字段 | 含义 |
314
+ |---|---|
315
+ | `target?` | 任意[选择器](#选择器),或 `{ kind: 'selection' }` / `{ kind: 'focus' }`(当前选择管理器 / 最后一次点击的位置)。缺省为整个结构。 |
316
+ | `detail?` | `summary`(默认):总数、按 component 的计数与样式,不含行;`residues`:再加残基行;`atoms`:残基行 + 每个原子的坐标。 |
317
+ | `limit?` | 残基行上限,默认 `DEFAULT_INSPECT_LIMIT`(200)。总数和 counts 始终覆盖整个 target,`truncated` 表示行是否被截断。 |
318
+
319
+ `InspectResult` 字段:`target`、`detail`、`atoms`、`residues`、`chains`、
320
+ `models`、`counts`、`residueRows?`、`styles`、`appearance?`、`selection?`、
321
+ `focus?`、`truncated`。`counts` 总是存在且总是完整:默认调用即可回答「多少个水 /
322
+ Cys / 配体」。
323
+
324
+ 行里带结构身份(`chain`、`seqId` 为 author 编号、`labelSeqId`、`compId`、
325
+ `kind`)和绘制中心坐标(`x`、`y`、`z`)。原子行额外有 `name`、`element`、
326
+ 坐标,以及格式提供时的 `occupancy` / `bFactor` / `altId`。坐标取自 unit
327
+ conformation,也就是 Mol* 实际绘制的位置。
328
+
329
+ 每条样式给出表示类型、配色主题、尺寸主题、配色主题参数、`hidden`(该表示当前
330
+ 未被绘制),以及两个关键颜色:
331
+
332
+ | 字段 | 含义 |
333
+ |---|---|
334
+ | `baseColor` | 该表示自身配色主题给这个元素的颜色。 |
335
+ | `visibleColor` | 实际看到的颜色:在 `baseColor` 上叠加 overlay 之后的结果。 |
336
+ | `overlays` | 作用在该元素上的叠加层。 |
337
+
338
+ 叠加层来自实时 viewer 状态,优先级如下:
339
+
340
+ 1. **overpaint**(`source: 'overpaint'`)替换主题色,覆盖 Mol* overpaint 图层
341
+ 覆盖的区域——最后命中的图层生效,`clear` 图层会清掉下面的涂色;
342
+ 2. **selection**(`source: 'selection'`)再把画布选择标记混到上面,使用
343
+ `canvas3d.props.renderer.selectColor` 与 `selectStrength`,与 Mol* 的
344
+ marker shader 一致(默认主题下是 `#33ff1a`、强度 `0.3`)。只描边、不改变体
345
+ 色的标记会以 `hidden: true` 报出,且不影响 `visibleColor`。
346
+
347
+ `appearance` 用最后绘制的那个表示给出 target 整体上的同一对颜色。颜色只在
348
+ target 的一个命中元素上采样,所以 `chain-id` 下多链 target 报的是第一条链的
349
+ 颜色;要某个残基的准确颜色就直接查询该残基。按选择叠加的 transparency /
350
+ emissive / substance,以及基于 script 的 overpaint 图层,暂未解析。
351
+
352
+ 没有加载结构时 `inspect` 抛 `Mol4AgentError`(`NO_STRUCTURE`);空选择或空
353
+ focus 是合法的空结果。低分辨率的粗粒化(sphere/gaussian)unit 没有原子层级,
354
+ 不会列出。
355
+
243
356
  ## 摘要
244
357
 
245
358
  `summarizeStructure` 不需要 viewer,直接从字节解析,适合 `mol_info` 或在
@@ -326,20 +439,22 @@ const png = await viewer.capture({
326
439
  `schema` 选择器;`ligand`/`protein` 这类语义类别无法转换成单个原子位置,
327
440
  会返回 `INVALID_COMMAND`。
328
441
 
329
- 按选择着色是叠加的:
442
+ 按选择叠加表示需要显式传 `replace: false`:
330
443
 
331
444
  ```ts
332
445
  // 其余区域:灰色卡通
333
446
  { op: 'represent', style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0x808080 } } }
334
- // 某段界面残基:红色球棍
447
+ // 某段界面残基:红色球棍,保留卡通
335
448
  { op: 'represent',
336
449
  style: { type: 'ball-and-stick', color: 'uniform', colorParams: { value: 0xff0000 } },
337
- target: { kind: 'residues', chain: 'A', start: 28, end: 54 } }
450
+ target: { kind: 'residues', chain: 'A', start: 28, end: 54 },
451
+ replace: false }
338
452
  ```
339
453
 
340
454
  全局 `cartoon` 使用 `polymer-and-ligand` preset;`colorParams` 会传入它的
341
- theme,所以 `uniform` 颜色可用。带 `target` 的 `represent` 会创建独立的
342
- selection component,不会删除其他表示。
455
+ theme,所以 `uniform` 颜色可用。带 `target` 且 `replace: false` 的 `represent`
456
+ 会创建独立的 selection component,不删除场景其余表示;不传 `replace: false`
457
+ 时,带 `target` 的命令同样会替换场景,`target` 只限定新表示的覆盖范围。
343
458
 
344
459
  ## React 绑定
345
460
 
@@ -390,6 +505,56 @@ sequenceDiagram
390
505
  - DSH 适配包把 core 打进单个 client bundle;见
391
506
  [`packages/deepseek-harness`](../deepseek-harness)。
392
507
 
508
+ ## TM-score 与 RMSD
509
+
510
+ `tmScore()` 比较两个选择但不改变场景,适合给从未叠合过的链/区域打分,或在
511
+ 叠合后做只读复核。
512
+
513
+ ```ts
514
+ const score = viewer.tmScore({
515
+ reference: { kind: 'chain', chain: 'B', structureId: 'reference' },
516
+ target: { kind: 'chain', chain: 'A', structureId: 'target' },
517
+ })
518
+ // { method: 'tm-align', rmsd, tmScoreA, tmScoreB, alignedLength,
519
+ // referenceAtoms, targetAtoms, reference, target }
520
+ ```
521
+
522
+ 两个选择都会归约为聚合物 trace(CA/C4'/P)。`rmsd` 是 TM-align 在对齐后的
523
+ trace 上做最优叠合后的 RMSD,不是当前相机坐标系下的 RMSD。计算复用 Mol* 的
524
+ structure-level `tmAlign`(`mol-model/structure/structure/util/tm-align`),
525
+ 不另写算法,也不会对 viewer 施加变换。
526
+
527
+ ## 多结构与结构叠合
528
+
529
+ `load()` 打开全新场景;`addStructure()` 把另一个结构追加到同一个 Mol* 场景。
530
+ 每个结构保留自己的 id、component、表示、可见性和测量。
531
+
532
+ ```ts
533
+ await viewer.load({ data: referenceBytes, format: 'pdb', label: '7czd.pdb' }, { id: 'reference' })
534
+ await viewer.addStructure({ data: targetBytes, format: 'pdb', label: '4zqk.pdb' }, { id: 'target' })
535
+ await viewer.execute({
536
+ op: 'represent',
537
+ style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0xef4444 } },
538
+ target: { kind: 'all', structureId: 'target' },
539
+ })
540
+ const aligned = await viewer.execute({
541
+ op: 'align',
542
+ reference: 'reference',
543
+ target: 'target',
544
+ method: 'tm-align',
545
+ referenceChain: 'B',
546
+ targetChain: 'A',
547
+ })
548
+ // aligned.data: { method, rmsd, alignedLength, tmScoreA, tmScoreB }
549
+ ```
550
+
551
+ 两个方法都复用 Mol* 自带的叠合工具
552
+ (`mol-model/structure/structure/util/{superposition,tm-align}`)和
553
+ `TransformStructureConformation` 装饰器,没有另写叠合或渲染引擎。叠合使用
554
+ 聚合物 trace(CA/C4'/P)移动 target,reference 保持不动,并把镜头框到叠合后的
555
+ 一对结构上;如果 reference 本身
556
+ 已经被变换,则把其当前坐标系合入 target 的变换。
557
+
393
558
  总体架构见 [`docs/architecture_zh.md`](../../docs/architecture_zh.md);具体实现见本包
394
559
  README/AGENTS,DSH agent 接口见
395
560
  [`packages/deepseek-harness/README_zh.md`](../deepseek-harness/README_zh.md)。