@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.
@@ -0,0 +1,339 @@
1
+ import { StructureElement, StructureProperties, Unit } from 'molstar/lib/mol-model/structure';
2
+ import { StateTransforms } from 'molstar/lib/mol-plugin-state/transforms';
3
+ import { formatColor } from "./color.js";
4
+ import { buildInspectResult, resolveOverpaint, visibleColorOf, } from "./inspect.js";
5
+ import { extractResidues } from "./inspect-mol.js";
6
+ import { Mol4AgentError, } from "./protocol.js";
7
+ import { describeSelector, selectorExpression } from "./select.js";
8
+ /** Structure identity of one residue, independent of which representation draws it. */
9
+ function residueKeyOfLocation(location) {
10
+ return [
11
+ StructureProperties.chain.auth_asym_id(location),
12
+ StructureProperties.residue.auth_seq_id(location),
13
+ StructureProperties.residue.label_comp_id(location),
14
+ ].join('|');
15
+ }
16
+ function residueKeyOfRecord(record) {
17
+ return [record.chain, record.seqId, record.compId].join('|');
18
+ }
19
+ /** Atom identity independent of which structure instance holds it. */
20
+ function atomKeyOfLocation(location) {
21
+ return [
22
+ residueKeyOfLocation(location),
23
+ StructureProperties.atom.label_atom_id(location),
24
+ ].join('|');
25
+ }
26
+ /** Every atom of the given locations, keyed the same way as `atomKeyOfLocation`. */
27
+ function atomKeysOf(lociList) {
28
+ const keys = new Set();
29
+ for (const loci of lociList) {
30
+ StructureElement.Loci.forEachLocation(loci, location => {
31
+ if (Unit.isAtomic(location.unit))
32
+ keys.add(atomKeyOfLocation(location));
33
+ });
34
+ }
35
+ return keys;
36
+ }
37
+ /** Every loaded structure object in the viewer, skipping unbuilt hierarchy entries. */
38
+ function loadedStructures(plugin) {
39
+ const structures = [];
40
+ for (const ref of plugin.managers.structure.hierarchy.current.structures) {
41
+ // Prefer the decorated structure so coordinates match what the page shows
42
+ // after an alignment transform; it is the same object when untransformed.
43
+ const structure = ref.transform?.cell.obj?.data ?? ref.cell.obj?.data;
44
+ if (structure !== undefined)
45
+ structures.push(structure);
46
+ }
47
+ return structures;
48
+ }
49
+ function targetLocations(plugin, target, structuresFor) {
50
+ const scoped = target.kind !== 'selection' && target.kind !== 'focus' && target.structureId !== undefined;
51
+ const structures = scoped && structuresFor !== undefined
52
+ ? structuresFor(target.structureId)
53
+ : loadedStructures(plugin);
54
+ if (structures.length === 0)
55
+ throw new Mol4AgentError('NO_STRUCTURE', 'no structure is loaded');
56
+ if (target.kind === 'selection') {
57
+ const loci = [];
58
+ for (const entry of plugin.managers.structure.selection.entries.values()) {
59
+ if (!StructureElement.Loci.isEmpty(entry.selection))
60
+ loci.push(entry.selection);
61
+ }
62
+ return { label: 'selection', loci, structures };
63
+ }
64
+ if (target.kind === 'focus') {
65
+ const current = plugin.managers.structure.focus.current;
66
+ const empty = current === undefined || StructureElement.Loci.isEmpty(current.loci);
67
+ return { label: 'focus', loci: empty ? [] : [current.loci], structures };
68
+ }
69
+ if (target.kind === 'all') {
70
+ return { label: 'whole structure', loci: structures.map(structure => StructureElement.Loci.all(structure)), structures };
71
+ }
72
+ const expression = selectorExpression(target);
73
+ const loci = [];
74
+ for (const structure of structures) {
75
+ const selected = StructureElement.Loci.fromExpression(structure, expression);
76
+ if (!StructureElement.Loci.isEmpty(selected))
77
+ loci.push(selected);
78
+ }
79
+ const label = describeSelector(target);
80
+ return {
81
+ label: target.structureId === undefined ? label : `${label} [${target.structureId}]`,
82
+ loci,
83
+ structures,
84
+ };
85
+ }
86
+ /** Residue and atom totals of a set of locations, walked once. */
87
+ function totalsOf(loci) {
88
+ const records = extractResidues(loci).records;
89
+ let atoms = 0;
90
+ for (const record of records)
91
+ atoms += record.atoms.length;
92
+ return { atoms, residues: records.length };
93
+ }
94
+ /**
95
+ * Totals for one or more live selections.
96
+ *
97
+ * `entries` are reported one row each so disjoint selection entries stay
98
+ * distinguishable; the top-level totals are the union, which is smaller than
99
+ * the sum of the per-entry rows when entries overlap.
100
+ */
101
+ function summarize(input, withGroups = false) {
102
+ const loci = input.filter((entry) => entry !== undefined && !StructureElement.Loci.isEmpty(entry));
103
+ if (loci.length === 0)
104
+ return undefined;
105
+ const summary = { entries: loci.length, ...totalsOf(loci) };
106
+ if (!withGroups)
107
+ return summary;
108
+ const groups = loci.map(entry => totalsOf([entry]));
109
+ return { ...summary, groups };
110
+ }
111
+ /** Keep only JSON-safe theme parameters; Mol* params may hold objects and Colors. */
112
+ function safeColorParams(params) {
113
+ if (typeof params !== 'object' || params === null)
114
+ return undefined;
115
+ const safe = {};
116
+ for (const [key, value] of Object.entries(params)) {
117
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
118
+ safe[key] = value;
119
+ }
120
+ return Object.keys(safe).length === 0 ? undefined : safe;
121
+ }
122
+ /**
123
+ * Ask the representation's own color theme for the colour it paints at `location`.
124
+ *
125
+ * Themes needing custom properties (e.g. hydrophobicity) can fail outside a
126
+ * rendered scene; the style row still reports its theme name in that case.
127
+ */
128
+ function themeColor(plugin, colorTheme, params, location) {
129
+ try {
130
+ const provider = plugin.representation.structure.themes.colorThemeRegistry.get(colorTheme);
131
+ const theme = provider.factory({ structure: location.structure }, (params ?? provider.defaultValues));
132
+ if (typeof theme.color !== 'function')
133
+ return undefined;
134
+ return theme.color(location, false);
135
+ }
136
+ catch {
137
+ return undefined;
138
+ }
139
+ }
140
+ /** One location inside `structure` whose residue is part of the inspected target. */
141
+ function firstTargetLocation(structure, keys) {
142
+ let hit;
143
+ StructureElement.Loci.forEachLocation(StructureElement.Loci.all(structure), location => {
144
+ if (hit !== undefined || !Unit.isAtomic(location.unit))
145
+ return;
146
+ if (keys.has(residueKeyOfLocation(location)))
147
+ hit = StructureElement.Location.clone(location);
148
+ });
149
+ return hit;
150
+ }
151
+ /**
152
+ * Overpaint layers attached to one representation, in application order.
153
+ *
154
+ * Mol* stores overpaint as a transform layered on the representation, so these
155
+ * are its child transforms in the state tree. Script-based layers are skipped:
156
+ * resolving a Mol*Script selection needs the script engine, and the UI only
157
+ * ever writes bundle layers.
158
+ */
159
+ function overpaintLayers(plugin, representationRef) {
160
+ const tree = plugin.state.data.tree;
161
+ const children = tree.children.get(representationRef);
162
+ if (children === undefined)
163
+ return [];
164
+ const layers = [];
165
+ children.forEach(childRef => {
166
+ const transform = tree.transforms.get(childRef);
167
+ if (transform === undefined)
168
+ return;
169
+ if (transform.transformer !== StateTransforms.Representation.OverpaintStructureRepresentation3DFromBundle)
170
+ return;
171
+ const params = transform.params;
172
+ for (const layer of params?.layers ?? [])
173
+ layers.push(layer);
174
+ });
175
+ return layers;
176
+ }
177
+ /**
178
+ * Overpaint colour covering one atom of a representation, plus the overlay row.
179
+ *
180
+ * Layers apply in order: a layer whose bundle contains the atom sets the colour,
181
+ * and a `clear` layer resets it back to the theme colour. The atom is matched by
182
+ * structure identity, so a bundle built against the root structure still matches
183
+ * an atom seen through a component substructure.
184
+ */
185
+ function overpaintFor(plugin, representationRef, root, atomKey, label) {
186
+ const resolved = [];
187
+ for (const layer of overpaintLayers(plugin, representationRef)) {
188
+ try {
189
+ resolved.push({
190
+ keys: atomKeysOf([StructureElement.Bundle.toLoci(layer.bundle, root)]),
191
+ color: layer.color,
192
+ clear: layer.clear,
193
+ });
194
+ }
195
+ catch {
196
+ // A layer that cannot be resolved is skipped rather than failing the query.
197
+ }
198
+ }
199
+ const applied = resolveOverpaint(resolved, atomKey);
200
+ if (applied === undefined)
201
+ return { overlays: [] };
202
+ return {
203
+ color: applied,
204
+ overlays: [{ source: 'overpaint', color: formatColor(applied), label }],
205
+ };
206
+ }
207
+ function canvasMarker(plugin) {
208
+ const renderer = plugin.canvas3d?.props.renderer;
209
+ if (renderer === undefined)
210
+ return undefined;
211
+ return {
212
+ selectColor: renderer.selectColor,
213
+ selectStrength: typeof renderer.selectStrength === 'number' ? renderer.selectStrength : 0,
214
+ edgesOnly: renderer.colorMarker !== true,
215
+ };
216
+ }
217
+ /** The selection overlay for one atom, when that atom is currently selected. */
218
+ function selectionOverlayFor(marker, selectionKeys, atomKey) {
219
+ if (marker === undefined || selectionKeys === undefined || !selectionKeys.has(atomKey))
220
+ return undefined;
221
+ return {
222
+ source: 'selection',
223
+ color: formatColor(marker.selectColor),
224
+ strength: marker.selectStrength,
225
+ ...(marker.edgesOnly ? { hidden: true } : {}),
226
+ };
227
+ }
228
+ /**
229
+ * Representations that currently draw any residue of the target.
230
+ *
231
+ * Matching uses structure identity (chain, sequence id, component id) rather
232
+ * than unit instances, so the same residue in a symmetry copy or in a
233
+ * selection component still reports the style that colours it on screen.
234
+ */
235
+ function collectStyles(plugin, targetKeys, targetStructures, selectionKeys) {
236
+ const styles = [];
237
+ const marker = canvasMarker(plugin);
238
+ for (const structureRef of plugin.managers.structure.hierarchy.current.structures) {
239
+ const structure = structureRef.transform?.cell.obj?.data ?? structureRef.cell.obj?.data;
240
+ if (structure === undefined || !targetStructures.includes(structure))
241
+ continue;
242
+ for (const component of structureRef.components) {
243
+ const structure = component.cell.obj?.data;
244
+ if (structure === undefined)
245
+ continue;
246
+ const location = firstTargetLocation(structure, targetKeys);
247
+ if (location === undefined)
248
+ continue;
249
+ const atomKey = atomKeyOfLocation(location);
250
+ const label = component.cell.obj?.label ?? 'component';
251
+ const componentHidden = component.cell.transform.state.isHidden === true;
252
+ for (const representation of component.representations) {
253
+ const values = representation.cell.params?.values;
254
+ const type = typeof values?.type?.name === 'string' ? values.type.name : 'unknown';
255
+ const colorTheme = typeof values?.colorTheme?.name === 'string' ? values.colorTheme.name : 'unknown';
256
+ const sizeTheme = typeof values?.sizeTheme?.name === 'string' ? values.sizeTheme.name : 'unknown';
257
+ const params = values?.colorTheme?.params;
258
+ const colorParams = safeColorParams(params);
259
+ const baseColor = themeColor(plugin, colorTheme, params, location);
260
+ const overpaint = overpaintFor(plugin, representation.cell.transform.ref, structure.root, atomKey, type);
261
+ const selection = selectionOverlayFor(marker, selectionKeys, atomKey);
262
+ const overlays = [
263
+ ...overpaint.overlays,
264
+ ...(selection === undefined ? [] : [selection]),
265
+ ];
266
+ // `selection` only exists when a marker does, so the marker options and
267
+ // the selected flag stay consistent.
268
+ const visibleColor = visibleColorOf(baseColor, overpaint.color, selection !== undefined, marker === undefined
269
+ ? undefined
270
+ : { color: marker.selectColor, strength: marker.selectStrength, edgesOnly: marker.edgesOnly });
271
+ const hidden = componentHidden || representation.cell.transform.state.isHidden === true;
272
+ styles.push({
273
+ component: label,
274
+ type,
275
+ color: colorTheme,
276
+ size: sizeTheme,
277
+ ...(colorParams === undefined ? {} : { colorParams }),
278
+ ...(baseColor === undefined ? {} : { baseColor: formatColor(baseColor) }),
279
+ ...(visibleColor === undefined ? {} : { visibleColor: formatColor(visibleColor) }),
280
+ ...(overlays.length === 0 ? {} : { overlays }),
281
+ ...(hidden ? { hidden: true } : {}),
282
+ });
283
+ }
284
+ }
285
+ }
286
+ return styles;
287
+ }
288
+ /**
289
+ * Effective appearance of the target: the last drawn style and its overlays.
290
+ *
291
+ * Several representations can cover one target (e.g. a cartoon plus a selection
292
+ * component), so this reports the one drawn last rather than inventing a merged
293
+ * colour; per-representation values stay in `styles`.
294
+ */
295
+ function appearanceOf(styles) {
296
+ for (let index = styles.length - 1; index >= 0; index -= 1) {
297
+ const style = styles[index];
298
+ if (style === undefined || style.hidden === true)
299
+ continue;
300
+ return {
301
+ ...(style.baseColor === undefined ? {} : { baseColor: style.baseColor }),
302
+ ...(style.visibleColor === undefined ? {} : { visibleColor: style.visibleColor }),
303
+ overlays: style.overlays ?? [],
304
+ };
305
+ }
306
+ return { overlays: [] };
307
+ }
308
+ /**
309
+ * Inspect the loaded structure and the way the viewer draws it.
310
+ *
311
+ * Throws {@link Mol4AgentError} with `NO_STRUCTURE` when nothing is loaded; an
312
+ * empty selection or focus is a valid empty result instead of an error.
313
+ */
314
+ export function inspectViewer(plugin, request = {}, structuresFor) {
315
+ const target = targetLocations(plugin, request.target ?? { kind: 'all' }, structuresFor);
316
+ const detail = request.detail ?? 'summary';
317
+ // Resolving the target is what makes the totals describe the requested
318
+ // scope; the style probe additionally needs residue identity.
319
+ const extracted = extractResidues(target.loci);
320
+ const keys = new Set(extracted.records.map(residueKeyOfRecord));
321
+ const selectionLocis = [...plugin.managers.structure.selection.entries.values()].map(entry => entry.selection);
322
+ const selection = summarize(selectionLocis, true);
323
+ const focus = summarize([plugin.managers.structure.focus.current?.loci]);
324
+ const selectionKeys = selection === undefined ? undefined : atomKeysOf(selectionLocis);
325
+ const styles = collectStyles(plugin, keys, target.structures, selectionKeys);
326
+ return buildInspectResult({
327
+ target: target.label,
328
+ detail,
329
+ chains: extracted.chains,
330
+ models: extracted.models,
331
+ records: extracted.records,
332
+ styles,
333
+ // An empty target carries no appearance: nothing is drawn to describe.
334
+ ...(extracted.records.length === 0 ? {} : { appearance: appearanceOf(styles) }),
335
+ ...(selection === undefined ? {} : { selection }),
336
+ ...(focus === undefined ? {} : { focus }),
337
+ ...(request.limit === undefined ? {} : { limit: request.limit }),
338
+ });
339
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Inspection totals, rows, and counts for an already-extracted structure.
3
+ *
4
+ * Mol* extraction lives in `inspect-mol.ts` and the viewer wiring in
5
+ * `inspect-plugin.ts`. This module owns the aggregation so it stays free of
6
+ * Mol* and DOM imports and can be tested under plain Node.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/inspect
9
+ */
10
+ import { type InspectAppearance, type InspectAtom, type InspectCount, type InspectDetail, type InspectKind, type InspectResult, type InspectSelection, type InspectStyle, type InspectVector } from './protocol.ts';
11
+ /** One residue with every atom Mol* placed for it, before detail filtering. */
12
+ export interface ResidueRecord {
13
+ readonly chain: string;
14
+ readonly seqId: number;
15
+ readonly labelSeqId: number;
16
+ readonly compId: string;
17
+ readonly kind: InspectKind;
18
+ readonly center: InspectVector;
19
+ readonly atoms: readonly InspectAtom[];
20
+ }
21
+ /** Everything {@link buildInspectResult} needs; produced by the Mol* extractor. */
22
+ export interface InspectInput {
23
+ /** Human label of the queried target, e.g. `whole structure`. */
24
+ readonly target: string;
25
+ readonly detail: InspectDetail;
26
+ /** Distinct chain ids inside the target. */
27
+ readonly chains: readonly string[];
28
+ readonly models: number;
29
+ readonly records: readonly ResidueRecord[];
30
+ readonly styles: readonly InspectStyle[];
31
+ /** Effective look of the target; omitted for an empty target. */
32
+ readonly appearance?: InspectAppearance;
33
+ readonly selection?: InspectSelection;
34
+ readonly focus?: InspectSelection;
35
+ readonly limit?: number;
36
+ }
37
+ /** Whether a detail level lists residues at all. */
38
+ export declare function listsResidues(detail: InspectDetail): boolean;
39
+ /**
40
+ * Classify a residue from Mol*'s entity type plus entity subtype.
41
+ *
42
+ * Mol* reports ions and ligands both as entity type `non-polymer`, so the
43
+ * subtype is what separates them; this mirrors the "Ion" selection query in the
44
+ * official UI, which tests `entitySubtype === 'ion'`.
45
+ */
46
+ export declare function kindOfEntity(entityType: string | undefined, entitySubtype: string | undefined): InspectKind;
47
+ /** Mean of the given positions; the first one when the list is empty. */
48
+ export declare function centroid(points: readonly InspectVector[]): InspectVector;
49
+ /** Residue/atom totals per component id, complete regardless of the row budget. */
50
+ export declare function countCompIds(records: readonly ResidueRecord[]): InspectCount[];
51
+ /**
52
+ * Assemble one `InspectResult`.
53
+ *
54
+ * Totals and counts always cover the whole target; only the listed rows obey
55
+ * `limit`, and `truncated` says whether that budget dropped anything, so an
56
+ * agent can tell "200 residues" apart from "at least 200 residues". Counts are
57
+ * part of every detail level because they answer "how many waters / Cys" in the
58
+ * default call.
59
+ */
60
+ export declare function buildInspectResult(input: InspectInput): InspectResult;
61
+ /** One overpaint layer already resolved to the atoms it covers. */
62
+ export interface OverpaintLayerKeys {
63
+ readonly keys: ReadonlySet<string>;
64
+ readonly color: number;
65
+ /** Layer resets the colour under it instead of painting. */
66
+ readonly clear: boolean;
67
+ }
68
+ /**
69
+ * Colour left by the last overpaint layer that covers `atomKey`.
70
+ *
71
+ * Layers apply in order, and a `clear` layer removes what the layer below
72
+ * painted, so the effective colour is whatever the last covering layer set.
73
+ */
74
+ export declare function resolveOverpaint(layers: readonly OverpaintLayerKeys[], atomKey: string): number | undefined;
75
+ /** The canvas selection marker, mirroring `canvas3d.props.renderer`. */
76
+ export interface CanvasMarkerOptions {
77
+ readonly color: number;
78
+ readonly strength: number;
79
+ /** True when the marker only outlines geometry and does not tint its colour. */
80
+ readonly edgesOnly: boolean;
81
+ }
82
+ /**
83
+ * Colour actually visible for one atom.
84
+ *
85
+ * Overpaint replaces the colour its representation theme would give, then the
86
+ * selection marker mixes on top of that, matching Mol*'s marker shader.
87
+ */
88
+ export declare function visibleColorOf(baseColor: number | undefined, overpaintColor: number | undefined, selected: boolean, marker: CanvasMarkerOptions | undefined): number | undefined;
package/lib/inspect.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Inspection totals, rows, and counts for an already-extracted structure.
3
+ *
4
+ * Mol* extraction lives in `inspect-mol.ts` and the viewer wiring in
5
+ * `inspect-plugin.ts`. This module owns the aggregation so it stays free of
6
+ * Mol* and DOM imports and can be tested under plain Node.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/inspect
9
+ */
10
+ import { DEFAULT_INSPECT_LIMIT, } from "./protocol.js";
11
+ import { mixColor } from "./color.js";
12
+ /** Row budget bounds: an agent asking for 0 or 10^9 must not break the result. */
13
+ const MIN_LIMIT = 1;
14
+ const MAX_LIMIT = 5_000;
15
+ /** Ordering used for count rows: solvent first, polymer last. */
16
+ const KIND_ORDER = {
17
+ water: 0,
18
+ ion: 1,
19
+ ligand: 2,
20
+ polymer: 3,
21
+ other: 4,
22
+ };
23
+ /** Whether a detail level lists residues at all. */
24
+ export function listsResidues(detail) {
25
+ return detail === 'residues' || detail === 'atoms';
26
+ }
27
+ /**
28
+ * Classify a residue from Mol*'s entity type plus entity subtype.
29
+ *
30
+ * Mol* reports ions and ligands both as entity type `non-polymer`, so the
31
+ * subtype is what separates them; this mirrors the "Ion" selection query in the
32
+ * official UI, which tests `entitySubtype === 'ion'`.
33
+ */
34
+ export function kindOfEntity(entityType, entitySubtype) {
35
+ if (entityType === 'water')
36
+ return 'water';
37
+ if (entitySubtype === 'ion')
38
+ return 'ion';
39
+ if (entityType === 'polymer' || entityType === 'branched' || entityType === 'macrolide')
40
+ return 'polymer';
41
+ if (entityType === 'non-polymer')
42
+ return 'ligand';
43
+ return 'other';
44
+ }
45
+ /** Mean of the given positions; the first one when the list is empty. */
46
+ export function centroid(points) {
47
+ const first = points[0];
48
+ if (first === undefined)
49
+ return { x: 0, y: 0, z: 0 };
50
+ let x = 0;
51
+ let y = 0;
52
+ let z = 0;
53
+ for (const point of points) {
54
+ x += point.x;
55
+ y += point.y;
56
+ z += point.z;
57
+ }
58
+ const count = points.length;
59
+ return { x: x / count, y: y / count, z: z / count };
60
+ }
61
+ /** Residue/atom totals per component id, complete regardless of the row budget. */
62
+ export function countCompIds(records) {
63
+ const merged = new Map();
64
+ for (const record of records) {
65
+ const existing = merged.get(record.compId);
66
+ if (existing === undefined) {
67
+ merged.set(record.compId, { kind: record.kind, residues: 1, atoms: record.atoms.length });
68
+ }
69
+ else {
70
+ existing.residues += 1;
71
+ existing.atoms += record.atoms.length;
72
+ }
73
+ }
74
+ return [...merged.entries()]
75
+ .map(([compId, totals]) => ({ compId, ...totals }))
76
+ .sort((left, right) => {
77
+ const byKind = KIND_ORDER[left.kind] - KIND_ORDER[right.kind];
78
+ if (byKind !== 0)
79
+ return byKind;
80
+ if (left.residues !== right.residues)
81
+ return right.residues - left.residues;
82
+ return left.compId < right.compId ? -1 : left.compId > right.compId ? 1 : 0;
83
+ });
84
+ }
85
+ /** Round a coordinate to the precision an agent can act on (0.001 A). */
86
+ function round(value) {
87
+ return Math.round(value * 1000) / 1000;
88
+ }
89
+ function roundVector(vector) {
90
+ return { x: round(vector.x), y: round(vector.y), z: round(vector.z) };
91
+ }
92
+ function residueRow(record, withAtoms) {
93
+ const center = roundVector(record.center);
94
+ return {
95
+ chain: record.chain,
96
+ seqId: record.seqId,
97
+ labelSeqId: record.labelSeqId,
98
+ compId: record.compId,
99
+ kind: record.kind,
100
+ atoms: record.atoms.length,
101
+ ...center,
102
+ ...(withAtoms
103
+ ? {
104
+ atomRows: record.atoms.map(atom => ({
105
+ name: atom.name,
106
+ element: atom.element,
107
+ x: round(atom.x),
108
+ y: round(atom.y),
109
+ z: round(atom.z),
110
+ ...(atom.occupancy === undefined ? {} : { occupancy: round(atom.occupancy) }),
111
+ ...(atom.bFactor === undefined ? {} : { bFactor: round(atom.bFactor) }),
112
+ ...(atom.altId === undefined ? {} : { altId: atom.altId }),
113
+ })),
114
+ }
115
+ : {}),
116
+ };
117
+ }
118
+ function clampLimit(limit) {
119
+ const requested = limit === undefined || !Number.isFinite(limit) ? DEFAULT_INSPECT_LIMIT : Math.floor(limit);
120
+ return Math.max(MIN_LIMIT, Math.min(MAX_LIMIT, requested));
121
+ }
122
+ /** Sort residues into a stable chain/sequence order for the model to read. */
123
+ function compareRecords(left, right) {
124
+ if (left.chain !== right.chain)
125
+ return left.chain < right.chain ? -1 : 1;
126
+ if (left.seqId !== right.seqId)
127
+ return left.seqId - right.seqId;
128
+ return left.compId < right.compId ? -1 : left.compId > right.compId ? 1 : 0;
129
+ }
130
+ /**
131
+ * Assemble one `InspectResult`.
132
+ *
133
+ * Totals and counts always cover the whole target; only the listed rows obey
134
+ * `limit`, and `truncated` says whether that budget dropped anything, so an
135
+ * agent can tell "200 residues" apart from "at least 200 residues". Counts are
136
+ * part of every detail level because they answer "how many waters / Cys" in the
137
+ * default call.
138
+ */
139
+ export function buildInspectResult(input) {
140
+ const limit = clampLimit(input.limit);
141
+ const ordered = [...input.records].sort(compareRecords);
142
+ const atomCount = ordered.reduce((total, record) => total + record.atoms.length, 0);
143
+ const withAtoms = input.detail === 'atoms';
144
+ const rows = listsResidues(input.detail) ? ordered.slice(0, limit) : undefined;
145
+ return {
146
+ target: input.target,
147
+ detail: input.detail,
148
+ atoms: atomCount,
149
+ residues: ordered.length,
150
+ chains: input.chains.length,
151
+ models: input.models,
152
+ counts: countCompIds(ordered),
153
+ ...(rows === undefined ? {} : { residueRows: rows.map(record => residueRow(record, withAtoms)) }),
154
+ styles: input.styles,
155
+ ...(input.appearance === undefined ? {} : { appearance: input.appearance }),
156
+ ...(input.selection === undefined ? {} : { selection: input.selection }),
157
+ ...(input.focus === undefined ? {} : { focus: input.focus }),
158
+ truncated: rows !== undefined && ordered.length > rows.length,
159
+ };
160
+ }
161
+ /**
162
+ * Colour left by the last overpaint layer that covers `atomKey`.
163
+ *
164
+ * Layers apply in order, and a `clear` layer removes what the layer below
165
+ * painted, so the effective colour is whatever the last covering layer set.
166
+ */
167
+ export function resolveOverpaint(layers, atomKey) {
168
+ let applied;
169
+ for (const layer of layers) {
170
+ if (!layer.keys.has(atomKey))
171
+ continue;
172
+ applied = layer.clear ? undefined : layer.color;
173
+ }
174
+ return applied;
175
+ }
176
+ /**
177
+ * Colour actually visible for one atom.
178
+ *
179
+ * Overpaint replaces the colour its representation theme would give, then the
180
+ * selection marker mixes on top of that, matching Mol*'s marker shader.
181
+ */
182
+ export function visibleColorOf(baseColor, overpaintColor, selected, marker) {
183
+ const effective = overpaintColor ?? baseColor;
184
+ if (effective === undefined)
185
+ return undefined;
186
+ if (!selected || marker === undefined || marker.edgesOnly)
187
+ return effective;
188
+ return mixColor(effective, marker.color, marker.strength);
189
+ }