molstar
Version:
A comprehensive macromolecular library.
1,061 lines • 57.2 kB
JavaScript
/**
* Copyright (c) 2018-2025 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @author Adam Midlik <midlik@gmail.com>
* @author Ludovic Autin <ludovic.autin@gmail.com>
*/
import { parseDcd } from '../../mol-io/reader/dcd/parser';
import { parseGRO } from '../../mol-io/reader/gro/parser';
import { parsePDB } from '../../mol-io/reader/pdb/parser';
import { Mat4, Vec3 } from '../../mol-math/linear-algebra';
import { shapeFromPly } from '../../mol-model-formats/shape/ply';
import { coordinatesFromDcd } from '../../mol-model-formats/structure/dcd';
import { trajectoryFromGRO } from '../../mol-model-formats/structure/gro';
import { trajectoryFromCCD, trajectoryFromMmCIF } from '../../mol-model-formats/structure/mmcif';
import { trajectoryFromPDB } from '../../mol-model-formats/structure/pdb';
import { topologyFromPsf } from '../../mol-model-formats/structure/psf';
import { Model, Queries, QueryContext, Structure, StructureElement, StructureSelection as Sel, ArrayTrajectory } from '../../mol-model/structure';
import { MolScriptBuilder } from '../../mol-script/language/builder';
import { Script } from '../../mol-script/script';
import { StateObject, StateTransformer } from '../../mol-state';
import { Task } from '../../mol-task';
import { deepEqual } from '../../mol-util';
import { ParamDefinition as PD } from '../../mol-util/param-definition';
import { RootStructureDefinition } from '../helpers/root-structure';
import { createStructureComponent, StructureComponentParams, updateStructureComponent } from '../helpers/structure-component';
import { StructureQueryHelper } from '../helpers/structure-query';
import { StructureSelectionQueries } from '../helpers/structure-selection-query';
import { PluginStateObject as SO, PluginStateTransform } from '../objects';
import { parseMol } from '../../mol-io/reader/mol/parser';
import { trajectoryFromMol } from '../../mol-model-formats/structure/mol';
import { trajectoryFromCifCore } from '../../mol-model-formats/structure/cif-core';
import { trajectoryFromCube } from '../../mol-model-formats/structure/cube';
import { parseMol2 } from '../../mol-io/reader/mol2/parser';
import { trajectoryFromMol2 } from '../../mol-model-formats/structure/mol2';
import { parseXtc } from '../../mol-io/reader/xtc/parser';
import { coordinatesFromXtc } from '../../mol-model-formats/structure/xtc';
import { parseXyz } from '../../mol-io/reader/xyz/parser';
import { trajectoryFromXyz } from '../../mol-model-formats/structure/xyz';
import { UnitStyles } from '../../mol-io/reader/lammps/schema';
import { parseLammpsData } from '../../mol-io/reader/lammps/data/parser';
import { trajectoryFromLammpsData } from '../../mol-model-formats/structure/lammps-data';
import { parseLammpsTrajectory } from '../../mol-io/reader/lammps/traj/parser';
import { coordinatesFromLammpsTrajectory, trajectoryFromLammpsTrajectory } from '../../mol-model-formats/structure/lammps-trajectory';
import { parseSdf } from '../../mol-io/reader/sdf/parser';
import { trajectoryFromSdf } from '../../mol-model-formats/structure/sdf';
import { assertUnreachable } from '../../mol-util/type-helpers';
import { parseTrr } from '../../mol-io/reader/trr/parser';
import { coordinatesFromTrr } from '../../mol-model-formats/structure/trr';
import { parseNctraj } from '../../mol-io/reader/nctraj/parser';
import { coordinatesFromNctraj } from '../../mol-model-formats/structure/nctraj';
import { topologyFromPrmtop } from '../../mol-model-formats/structure/prmtop';
import { topologyFromTop } from '../../mol-model-formats/structure/top';
export { CoordinatesFromDcd };
export { CoordinatesFromXtc };
export { CoordinatesFromTrr };
export { CoordinatesFromNctraj };
export { CoordinatesFromLammpstraj };
export { TopologyFromPsf };
export { TopologyFromPrmtop };
export { TopologyFromTop };
export { TrajectoryFromModelAndCoordinates };
export { TrajectoryFromBlob };
export { TrajectoryFromMmCif };
export { TrajectoryFromPDB };
export { TrajectoryFromGRO };
export { TrajectoryFromXYZ };
export { TrajectoryFromLammpsData };
export { TrajectoryFromLammpsTrajData };
export { TrajectoryFromMOL };
export { TrajectoryFromSDF };
export { TrajectoryFromMOL2 };
export { TrajectoryFromCube };
export { TrajectoryFromCifCore };
export { ModelFromTrajectory };
export { ModelWithCoordinates };
export { StructureFromTrajectory };
export { StructureFromModel };
export { TransformStructureConformation };
export { StructureSelectionFromExpression };
export { MultiStructureSelectionFromExpression };
export { MultiStructureSelectionFromBundle };
export { StructureSelectionFromScript };
export { StructureSelectionFromBundle };
export { StructureComplexElement };
export { StructureComponent };
export { CustomModelProperties };
export { CustomStructureProperties };
export { ShapeFromPly };
const CoordinatesFromDcd = PluginStateTransform.BuiltIn({
name: 'coordinates-from-dcd',
display: { name: 'Parse DCD', description: 'Parse DCD binary data.' },
from: [SO.Data.Binary],
to: SO.Molecule.Coordinates
})({
apply({ a }) {
return Task.create('Parse DCD', async (ctx) => {
const parsed = await parseDcd(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const coordinates = await coordinatesFromDcd(parsed.result).runInContext(ctx);
return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
});
}
});
const CoordinatesFromXtc = PluginStateTransform.BuiltIn({
name: 'coordinates-from-xtc',
display: { name: 'Parse XTC', description: 'Parse XTC binary data.' },
from: [SO.Data.Binary],
to: SO.Molecule.Coordinates
})({
apply({ a }) {
return Task.create('Parse XTC', async (ctx) => {
const parsed = await parseXtc(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const coordinates = await coordinatesFromXtc(parsed.result).runInContext(ctx);
return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
});
}
});
const CoordinatesFromTrr = PluginStateTransform.BuiltIn({
name: 'coordinates-from-trr',
display: { name: 'Parse TRR', description: 'Parse TRR binary data.' },
from: [SO.Data.Binary],
to: SO.Molecule.Coordinates
})({
apply({ a }) {
return Task.create('Parse TRR', async (ctx) => {
const parsed = await parseTrr(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const coordinates = await coordinatesFromTrr(parsed.result).runInContext(ctx);
return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
});
}
});
const CoordinatesFromNctraj = PluginStateTransform.BuiltIn({
name: 'coordinates-from-nctraj',
display: { name: 'Parse NCTRAJ', description: 'Parse NCTRAJ binary data.' },
from: [SO.Data.Binary],
to: SO.Molecule.Coordinates
})({
apply({ a }) {
return Task.create('Parse NCTRAJ', async (ctx) => {
const parsed = await parseNctraj(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const coordinates = await coordinatesFromNctraj(parsed.result).runInContext(ctx);
return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
});
}
});
const CoordinatesFromLammpstraj = PluginStateTransform.BuiltIn({
name: 'coordinates-from-lammpstraj',
display: { name: 'Parse LAMMPSTRAJ', description: 'Parse LAMMPSTRAJ data.' },
from: [SO.Data.String],
to: SO.Molecule.Coordinates
})({
apply({ a }) {
return Task.create('Parse LAMMPSTRAJ', async (ctx) => {
const parsed = await parseLammpsTrajectory(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const coordinates = await coordinatesFromLammpsTrajectory(parsed.result).runInContext(ctx);
return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
});
}
});
const TopologyFromPsf = PluginStateTransform.BuiltIn({
name: 'topology-from-psf',
display: { name: 'PSF Topology', description: 'Create topology from PSF.' },
from: [SO.Format.Psf],
to: SO.Molecule.Topology
})({
apply({ a }) {
return Task.create('Create Topology', async (ctx) => {
const topology = await topologyFromPsf(a.data).runInContext(ctx);
return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
});
}
});
const TopologyFromPrmtop = PluginStateTransform.BuiltIn({
name: 'topology-from-prmtop',
display: { name: 'PRMTOP Topology', description: 'Create topology from PRMTOP.' },
from: [SO.Format.Prmtop],
to: SO.Molecule.Topology
})({
apply({ a }) {
return Task.create('Create Topology', async (ctx) => {
const topology = await topologyFromPrmtop(a.data).runInContext(ctx);
return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
});
}
});
const TopologyFromTop = PluginStateTransform.BuiltIn({
name: 'topology-from-top',
display: { name: 'TOP Topology', description: 'Create topology from TOP.' },
from: [SO.Format.Top],
to: SO.Molecule.Topology
})({
apply({ a }) {
return Task.create('Create Topology', async (ctx) => {
const topology = await topologyFromTop(a.data).runInContext(ctx);
return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
});
}
});
async function getTrajectory(ctx, obj, coordinates) {
if (obj.type === SO.Molecule.Topology.type) {
const topology = obj.data;
return await Model.trajectoryFromTopologyAndCoordinates(topology, coordinates).runInContext(ctx);
}
else if (obj.type === SO.Molecule.Model.type) {
const model = obj.data;
return Model.trajectoryFromModelAndCoordinates(model, coordinates);
}
throw new Error('no model/topology found');
}
const TrajectoryFromModelAndCoordinates = PluginStateTransform.BuiltIn({
name: 'trajectory-from-model-and-coordinates',
display: { name: 'Trajectory from Topology & Coordinates', description: 'Create a trajectory from existing model/topology and coordinates.' },
from: SO.Root,
to: SO.Molecule.Trajectory,
params: {
modelRef: PD.Text('', { isHidden: true }),
coordinatesRef: PD.Text('', { isHidden: true }),
}
})({
apply({ params, dependencies }) {
return Task.create('Create trajectory from model/topology and coordinates', async (ctx) => {
const coordinates = dependencies[params.coordinatesRef].data;
const trajectory = await getTrajectory(ctx, dependencies[params.modelRef], coordinates);
const props = { label: 'Trajectory', description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
return new SO.Molecule.Trajectory(trajectory, props);
});
}
});
const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
name: 'trajectory-from-blob',
display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
from: SO.Format.Blob,
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse Format Blob', async (ctx) => {
const models = [];
for (const e of a.data) {
if (e.kind !== 'cif')
continue;
const block = e.data.blocks[0];
const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
if (xs.frameCount === 0)
throw new Error('No models found.');
for (let i = 0; i < xs.frameCount; i++) {
const x = await Task.resolveInContext(xs.getFrameAtIndex(i), ctx);
models.push(x);
}
}
for (let i = 0; i < models.length; i++) {
Model.TrajectoryInfo.set(models[i], { index: i, size: models.length });
}
const props = { label: 'Trajectory', description: `${models.length} model${models.length === 1 ? '' : 's'}` };
return new SO.Molecule.Trajectory(new ArrayTrajectory(models), props);
});
}
});
function trajectoryProps(trajectory) {
const first = trajectory.representative;
return { label: `${first.entry}`, description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
}
const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
name: 'trajectory-from-mmcif',
display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
from: SO.Format.Cif,
to: SO.Molecule.Trajectory,
params(a) {
if (!a) {
return {
loadAllBlocks: PD.Optional(PD.Boolean(false, { description: 'If True, ignore Block Header and Block Index parameters and parse all datablocks into a single trajectory.' })),
blockHeader: PD.Optional(PD.Text(void 0, { description: 'Header of the block to parse. If not specifed, Block Index parameter applies.', hideIf: p => p.loadAllBlocks === true })),
blockIndex: PD.Optional(PD.Numeric(0, { min: 0, step: 1 }, { description: 'Zero-based index of the block to parse. Only applies when Block Header parameter is not specified.', hideIf: p => p.loadAllBlocks === true || p.blockHeader })),
};
}
const { blocks } = a.data;
const headers = blocks.map(b => [b.header, b.header]);
headers.push(['', '[Use Block Index]']);
return {
loadAllBlocks: PD.Optional(PD.Boolean(false, { description: 'If True, ignore Block Header and Block Index parameters and parse all data blocks into a single trajectory.' })),
blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, headers, { description: 'Header of the block to parse. If not specifed, Block Index parameter applies.', hideIf: p => p.loadAllBlocks === true })),
blockIndex: PD.Optional(PD.Numeric(0, { min: 0, step: 1, max: blocks.length - 1 }, { description: 'Zero-based index of the block to parse. Only applies when Block Header parameter is not specified.', hideIf: p => p.loadAllBlocks === true || p.blockHeader })),
};
}
})({
isApplicable: a => a.data.blocks.length > 0,
apply({ a, params }) {
return Task.create('Parse mmCIF', async (ctx) => {
var _a;
let trajectory;
if (params.loadAllBlocks) {
const models = [];
for (const block of a.data.blocks) {
if (ctx.shouldUpdate) {
await ctx.update(`Parsing ${block.header}...`);
}
const t = await trajectoryFromMmCIF(block).runInContext(ctx);
for (let i = 0; i < t.frameCount; i++) {
models.push(await Task.resolveInContext(t.getFrameAtIndex(i), ctx));
}
}
trajectory = new ArrayTrajectory(models);
}
else {
const header = params.blockHeader || a.data.blocks[(_a = params.blockIndex) !== null && _a !== void 0 ? _a : 0].header;
const block = a.data.blocks.find(b => b.header === header);
if (!block)
throw new Error(`Data block '${[header]}' not found.`);
const isCcd = block.categoryNames.includes('chem_comp_atom') && !block.categoryNames.includes('atom_site') && !block.categoryNames.includes('ihm_sphere_obj_site') && !block.categoryNames.includes('ihm_gaussian_obj_site');
trajectory = isCcd ? await trajectoryFromCCD(block).runInContext(ctx) : await trajectoryFromMmCIF(block, a.data).runInContext(ctx);
}
if (trajectory.frameCount === 0)
throw new Error('No models found.');
const props = trajectoryProps(trajectory);
return new SO.Molecule.Trajectory(trajectory, props);
});
}
});
const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
name: 'trajectory-from-pdb',
display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory,
params: {
isPdbqt: PD.Boolean(false)
}
})({
apply({ a, params }) {
return Task.create('Parse PDB', async (ctx) => {
const parsed = await parsePDB(a.data, a.label, params.isPdbqt).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
name: 'trajectory-from-gro',
display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse GRO', async (ctx) => {
const parsed = await parseGRO(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromXYZ = PluginStateTransform.BuiltIn({
name: 'trajectory-from-xyz',
display: { name: 'Parse XYZ', description: 'Parse XYZ string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse XYZ', async (ctx) => {
const parsed = await parseXyz(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromXyz(parsed.result).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromLammpsData = PluginStateTransform.BuiltIn({
name: 'trajectory-from-lammps-data',
display: { name: 'Parse Lammps Data', description: 'Parse Lammps Data from string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory,
params: {
unitsStyle: PD.Select('real', PD.arrayToOptions(UnitStyles)),
}
})({
apply({ a, params }) {
return Task.create('Parse Lammps Data', async (ctx) => {
const parsed = await parseLammpsData(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromLammpsData(parsed.result, params.unitsStyle).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromLammpsTrajData = PluginStateTransform.BuiltIn({
name: 'trajectory-from-lammps-traj-data',
display: { name: 'Parse Lammps traj Data', description: 'Parse Lammps Traj Data string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory,
params: {
unitsStyle: PD.Select('real', PD.arrayToOptions(UnitStyles)),
}
})({
apply({ a, params }) {
return Task.create('Parse Lammps Data', async (ctx) => {
const parsed = await parseLammpsTrajectory(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromLammpsTrajectory(parsed.result, params.unitsStyle).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromMOL = PluginStateTransform.BuiltIn({
name: 'trajectory-from-mol',
display: { name: 'Parse MOL', description: 'Parse MOL string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse MOL', async (ctx) => {
const parsed = await parseMol(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromMol(parsed.result).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromSDF = PluginStateTransform.BuiltIn({
name: 'trajectory-from-sdf',
display: { name: 'Parse SDF', description: 'Parse SDF string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse SDF', async (ctx) => {
const parsed = await parseSdf(a.data).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = [];
for (const compound of parsed.result.compounds) {
const traj = await trajectoryFromSdf(compound).runInContext(ctx);
for (let i = 0; i < traj.frameCount; i++) {
models.push(await Task.resolveInContext(traj.getFrameAtIndex(i), ctx));
}
}
const traj = new ArrayTrajectory(models);
const props = trajectoryProps(traj);
return new SO.Molecule.Trajectory(traj, props);
});
}
});
const TrajectoryFromMOL2 = PluginStateTransform.BuiltIn({
name: 'trajectory-from-mol2',
display: { name: 'Parse MOL2', description: 'Parse MOL2 string and create trajectory.' },
from: [SO.Data.String],
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse MOL2', async (ctx) => {
const parsed = await parseMol2(a.data, a.label).runInContext(ctx);
if (parsed.isError)
throw new Error(parsed.message);
const models = await trajectoryFromMol2(parsed.result).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromCube = PluginStateTransform.BuiltIn({
name: 'trajectory-from-cube',
display: { name: 'Parse Cube', description: 'Parse Cube file to create a trajectory.' },
from: SO.Format.Cube,
to: SO.Molecule.Trajectory
})({
apply({ a }) {
return Task.create('Parse MOL', async (ctx) => {
const models = await trajectoryFromCube(a.data).runInContext(ctx);
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const TrajectoryFromCifCore = PluginStateTransform.BuiltIn({
name: 'trajectory-from-cif-core',
display: { name: 'Parse CIF Core', description: 'Identify and create all separate models in the specified CIF data block' },
from: SO.Format.Cif,
to: SO.Molecule.Trajectory,
params(a) {
if (!a) {
return {
blockHeader: PD.Optional(PD.Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.' }))
};
}
const { blocks } = a.data;
return {
blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, blocks.map(b => [b.header, b.header]), { description: 'Header of the block to parse' }))
};
}
})({
apply({ a, params }) {
return Task.create('Parse CIF Core', async (ctx) => {
const header = params.blockHeader || a.data.blocks[0].header;
const block = a.data.blocks.find(b => b.header === header);
if (!block)
throw new Error(`Data block '${[header]}' not found.`);
const models = await trajectoryFromCifCore(block).runInContext(ctx);
if (models.frameCount === 0)
throw new Error('No models found.');
const props = trajectoryProps(models);
return new SO.Molecule.Trajectory(models, props);
});
}
});
const plus1 = (v) => v + 1, minus1 = (v) => v - 1;
const ModelFromTrajectory = PluginStateTransform.BuiltIn({
name: 'model-from-trajectory',
display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
from: SO.Molecule.Trajectory,
to: SO.Molecule.Model,
params: a => {
if (!a) {
return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model', immediateUpdate: true }) };
}
return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.frameCount, step: 1 }, { description: 'Model Index', immediateUpdate: true })) };
}
})({
isApplicable: a => a.data.frameCount > 0,
apply({ a, params }) {
return Task.create('Model from Trajectory', async (ctx) => {
let modelIndex = params.modelIndex % a.data.frameCount;
if (modelIndex < 0)
modelIndex += a.data.frameCount;
const model = await Task.resolveInContext(a.data.getFrameAtIndex(modelIndex), ctx);
const label = `Model ${modelIndex + 1}`;
const description = a.data.frameCount === 1 ? undefined : `of ${a.data.frameCount}`;
return new SO.Molecule.Model(model, { label, description });
});
},
interpolate(a, b, t) {
const modelIndex = t >= 1 ? b.modelIndex : a.modelIndex + Math.floor((b.modelIndex - a.modelIndex + 1) * t);
return { modelIndex };
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customProperties.dispose();
}
});
const StructureFromTrajectory = PluginStateTransform.BuiltIn({
name: 'structure-from-trajectory',
display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
from: SO.Molecule.Trajectory,
to: SO.Molecule.Structure
})({
apply({ a }) {
return Task.create('Build Structure', async (ctx) => {
const s = await Structure.ofTrajectory(a.data, ctx);
const props = { label: 'Ensemble', description: Structure.elementDescription(s) };
return new SO.Molecule.Structure(s, props);
});
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
});
const StructureFromModel = PluginStateTransform.BuiltIn({
name: 'structure-from-model',
display: { name: 'Structure', description: 'Create a molecular structure (model, assembly, or symmetry) from the specified model.' },
from: SO.Molecule.Model,
to: SO.Molecule.Structure,
params(a) { return RootStructureDefinition.getParams(a && a.data); }
})({
canAutoUpdate({ oldParams, newParams }) {
return RootStructureDefinition.canAutoUpdate(oldParams.type, newParams.type);
},
apply({ a, params }, plugin) {
return Task.create('Build Structure', async (ctx) => {
return RootStructureDefinition.create(plugin, ctx, a.data, params && params.type);
});
},
update: ({ a, b, oldParams, newParams }) => {
if (!deepEqual(oldParams, newParams))
return StateTransformer.UpdateResult.Recreate;
if (b.data.model === a.data)
return StateTransformer.UpdateResult.Unchanged;
if (!Model.areHierarchiesEqual(a.data, b.data.model))
return StateTransformer.UpdateResult.Recreate;
b.data = b.data.remapModel(a.data);
return StateTransformer.UpdateResult.Updated;
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
});
const _translation = Vec3(), _m = Mat4(), _n = Mat4();
const TransformStructureConformation = PluginStateTransform.BuiltIn({
name: 'transform-structure-conformation',
display: { name: 'Transform Conformation' },
isDecorator: true,
from: SO.Molecule.Structure,
to: SO.Molecule.Structure,
params: {
transform: PD.MappedStatic('components', {
components: PD.Group({
axis: PD.Vec3(Vec3.create(1, 0, 0)),
angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
translation: PD.Vec3(Vec3.create(0, 0, 0)),
}, { isFlat: true }),
matrix: PD.Group({
data: PD.Mat4(Mat4.identity()),
transpose: PD.Boolean(false)
}, { isFlat: true })
}, { label: 'Kind' })
}
})({
canAutoUpdate({ newParams }) {
return newParams.transform.name !== 'matrix';
},
apply({ a, params }) {
// TODO: optimze
// TODO: think of ways how to fast-track changes to this for animations
const transform = Mat4();
if (params.transform.name === 'components') {
const { axis, angle, translation } = params.transform.params;
const center = a.data.boundary.sphere.center;
Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
Mat4.fromTranslation(_n, Vec3.add(_translation, center, translation));
const rot = Mat4.fromRotation(Mat4(), Math.PI / 180 * angle, Vec3.normalize(Vec3(), axis));
Mat4.mul3(transform, _n, rot, _m);
}
else if (params.transform.name === 'matrix') {
Mat4.copy(transform, params.transform.params.data);
if (params.transform.params.transpose)
Mat4.transpose(transform, transform);
}
const s = Structure.transform(a.data, transform);
return new SO.Molecule.Structure(s, { label: a.label, description: `${a.description} [Transformed]` });
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
// interpolate(src, tar, t) {
// // TODO: optimize
// const u = Mat4.fromRotation(Mat4(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
// Mat4.setTranslation(u, src.translation);
// const v = Mat4.fromRotation(Mat4(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
// Mat4.setTranslation(v, tar.translation);
// const m = SymmetryOperator.slerp(Mat4(), u, v, t);
// const rot = Mat4.getRotation(Quat.zero(), m);
// const axis = Vec3();
// const angle = Quat.getAxisAngle(axis, rot);
// const translation = Mat4.getTranslation(Vec3(), m);
// return { axis, angle, translation };
// }
});
const ModelWithCoordinates = PluginStateTransform.BuiltIn({
name: 'model-with-coordinates',
display: { name: 'Model With Coordinates', description: 'Updates the current model with provided coordinate frame' },
from: SO.Molecule.Model,
to: SO.Molecule.Model,
params: {
frameIndex: PD.Optional(PD.Numeric(0, undefined, { isHidden: true })),
frameCount: PD.Optional(PD.Numeric(1, undefined, { isHidden: true })),
atomicCoordinateFrame: PD.Optional(PD.Value(undefined, { isHidden: true })),
},
isDecorator: true,
})({
apply({ a, params }) {
var _a, _b;
if (!params.atomicCoordinateFrame) {
return a;
}
const model = { ...a.data, atomicConformation: Model.getAtomicConformationFromFrame(a.data, params.atomicCoordinateFrame) };
Model.TrajectoryInfo.set(model, { index: (_a = params.frameIndex) !== null && _a !== void 0 ? _a : 0, size: (_b = params.frameCount) !== null && _b !== void 0 ? _b : 1 });
return new SO.Molecule.Model(model, { label: a.label, description: a.description });
},
update: ({ a, b, oldParams, newParams }) => {
var _a, _b;
if (oldParams.atomicCoordinateFrame === newParams.atomicCoordinateFrame) {
return StateTransformer.UpdateResult.Unchanged;
}
if (!newParams.atomicCoordinateFrame) {
b.data = a.data;
}
else {
b.data = { ...b.data, atomicConformation: Model.getAtomicConformationFromFrame(b.data, newParams.atomicCoordinateFrame) };
}
Model.TrajectoryInfo.set(b.data, { index: (_a = newParams.frameIndex) !== null && _a !== void 0 ? _a : 0, size: (_b = newParams.frameCount) !== null && _b !== void 0 ? _b : 1 });
return StateTransformer.UpdateResult.Updated;
},
});
const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
name: 'structure-selection-from-expression',
display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
from: SO.Molecule.Structure,
to: SO.Molecule.Structure,
params: () => ({
expression: PD.Value(MolScriptBuilder.struct.generator.all, { isHidden: true }),
label: PD.Optional(PD.Text('', { isHidden: true }))
})
})({
apply({ a, params, cache }) {
const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.expression);
cache.entry = entry;
if (Sel.isEmpty(selection))
return StateObject.Null;
const s = Sel.unionStructure(selection);
const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
return new SO.Molecule.Structure(s, props);
},
update: ({ a, b, oldParams, newParams, cache }) => {
if (oldParams.expression !== newParams.expression)
return StateTransformer.UpdateResult.Recreate;
const entry = cache.entry;
if (entry.currentStructure === a.data) {
return StateTransformer.UpdateResult.Unchanged;
}
const selection = StructureQueryHelper.updateStructure(entry, a.data);
if (Sel.isEmpty(selection))
return StateTransformer.UpdateResult.Null;
StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
return StateTransformer.UpdateResult.Updated;
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
});
const MultiStructureSelectionFromExpression = PluginStateTransform.BuiltIn({
name: 'structure-multi-selection-from-expression',
display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
from: SO.Root,
to: SO.Molecule.Structure.Selections,
params: () => ({
selections: PD.ObjectList({
key: PD.Text(void 0, { description: 'A unique key.' }),
ref: PD.Text(),
groupId: PD.Optional(PD.Text()),
expression: PD.Value(MolScriptBuilder.struct.generator.empty)
}, e => e.ref, { isHidden: true }),
isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
label: PD.Optional(PD.Text('', { isHidden: true }))
})
})({
apply({ params, cache, dependencies }) {
const entries = new Map();
const selections = [];
let totalSize = 0;
for (const sel of params.selections) {
const { selection, entry } = StructureQueryHelper.createAndRun(dependencies[sel.ref].data, sel.expression);
entries.set(sel.key, entry);
const loci = Sel.toLociWithSourceUnits(selection);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
}
cache.entries = entries;
const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
return new SO.Molecule.Structure.Selections(selections, props);
},
update: ({ b, oldParams, newParams, cache, dependencies }) => {
if (!!oldParams.isTransitive !== !!newParams.isTransitive)
return StateTransformer.UpdateResult.Recreate;
const cacheEntries = cache.entries;
const entries = new Map();
const current = new Map();
for (const e of b.data)
current.set(e.key, e);
let changed = false;
let totalSize = 0;
const selections = [];
for (const sel of newParams.selections) {
const structure = dependencies[sel.ref].data;
let recreate = false;
if (cacheEntries.has(sel.key)) {
const entry = cacheEntries.get(sel.key);
if (StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
const loci = current.get(sel.key);
if (loci.groupId !== sel.groupId) {
loci.groupId = sel.groupId;
changed = true;
}
entries.set(sel.key, entry);
selections.push(loci);
totalSize += StructureElement.Loci.size(loci.loci);
continue;
}
if (entry.expression !== sel.expression) {
recreate = true;
}
else {
// TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
let update = false;
if (!!newParams.isTransitive) {
if (Structure.areUnitIdsAndIndicesEqual(entry.originalStructure, structure)) {
const selection = StructureQueryHelper.run(entry, entry.originalStructure);
entry.currentStructure = structure;
entries.set(sel.key, entry);
const loci = StructureElement.Loci.remap(Sel.toLociWithSourceUnits(selection), structure);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
changed = true;
}
else {
update = true;
}
}
else {
update = true;
}
if (update) {
changed = true;
const selection = StructureQueryHelper.updateStructure(entry, structure);
entries.set(sel.key, entry);
const loci = Sel.toLociWithSourceUnits(selection);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
}
}
}
else {
recreate = true;
}
if (recreate) {
changed = true;
// create new selection
const { selection, entry } = StructureQueryHelper.createAndRun(structure, sel.expression);
entries.set(sel.key, entry);
const loci = Sel.toLociWithSourceUnits(selection);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
}
}
if (!changed)
return StateTransformer.UpdateResult.Unchanged;
cache.entries = entries;
b.data = selections;
b.label = `${newParams.label || 'Multi-selection'}`;
b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
return StateTransformer.UpdateResult.Updated;
}
});
const MultiStructureSelectionFromBundle = PluginStateTransform.BuiltIn({
name: 'structure-multi-selection-from-bundle',
display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
from: SO.Root,
to: SO.Molecule.Structure.Selections,
params: () => ({
selections: PD.ObjectList({
key: PD.Text(void 0, { description: 'A unique key.' }),
ref: PD.Text(),
groupId: PD.Optional(PD.Text()),
bundle: PD.Value(StructureElement.Bundle.Empty),
}, e => e.ref, { isHidden: true }),
isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
label: PD.Optional(PD.Text('', { isHidden: true }))
})
})({
apply({ params, cache, dependencies }) {
const entries = new Map();
const selections = [];
let totalSize = 0;
for (const sel of params.selections) {
const source = dependencies[sel.ref].data;
const loci = StructureElement.Bundle.toLoci(sel.bundle, source);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
entries.set(sel.key, { source });
}
cache.entries = entries;
const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
return new SO.Molecule.Structure.Selections(selections, props);
},
update: ({ b, oldParams, newParams, cache, dependencies }) => {
if (!!oldParams.isTransitive !== !!newParams.isTransitive)
return StateTransformer.UpdateResult.Recreate;
const cacheEntries = cache.entries;
const entries = new Map();
const prevBundles = new Map();
for (const sel of oldParams.selections) {
prevBundles.set(sel.key, sel.bundle);
}
const current = new Map();
for (const e of b.data)
current.set(e.key, e);
let changed = false;
let totalSize = 0;
const selections = [];
for (const sel of newParams.selections) {
let recreate = false;
if (cacheEntries.has(sel.key)) {
const source = dependencies[sel.ref].data;
const entry = cacheEntries.get(sel.key);
const prev = prevBundles.get(sel.key);
if (prev && source === entry.source && sel.bundle.hash === entry.source.hashCode && StructureElement.Bundle.areEqual(sel.bundle, prev)) {
const loci = current.get(sel.key);
if (loci.groupId !== sel.groupId) {
loci.groupId = sel.groupId;
changed = true;
}
entries.set(sel.key, entry);
selections.push(loci);
totalSize += StructureElement.Loci.size(loci.loci);
continue;
}
recreate = true;
}
else {
recreate = true;
}
if (recreate) {
changed = true;
// create new selection
const source = dependencies[sel.ref].data;
const loci = StructureElement.Bundle.toLoci(sel.bundle, source);
selections.push({ key: sel.key, structureRef: sel.ref, loci, groupId: sel.groupId });
totalSize += StructureElement.Loci.size(loci);
entries.set(sel.key, { source });
}
}
if (!changed)
return StateTransformer.UpdateResult.Unchanged;
cache.entries = entries;
b.data = selections;
b.label = `${newParams.label || 'Multi-selection'}`;
b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
return StateTransformer.UpdateResult.Updated;
}
});
const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
name: 'structure-selection-from-script',
display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
from: SO.Molecule.Structure,
to: SO.Molecule.Structure,
params: () => ({
script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
label: PD.Optional(PD.Text(''))
})
})({
apply({ a, params, cache }) {
const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.script);
cache.entry = entry;
const s = Sel.unionStructure(selection);
const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
return new SO.Molecule.Structure(s, props);
},
update: ({ a, b, oldParams, newParams, cache }) => {
if (!Script.areEqual(oldParams.script, newParams.script)) {
return StateTransformer.UpdateResult.Recreate;
}
const entry = cache.entry;
if (entry.currentStructure === a.data) {
return StateTransformer.UpdateResult.Unchanged;
}
const selection = StructureQueryHelper.updateStructure(entry, a.data);
StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
return StateTransformer.UpdateResult.Updated;
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
});
const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
name: 'structure-selection-from-bundle',
display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
from: SO.Molecule.Structure,
to: SO.Molecule.Structure,
params: () => ({
bundle: PD.Value(StructureElement.Bundle.Empty, { isHidden: true }),
label: PD.Optional(PD.Text('', { isHidden: true }))
})
})({
apply({ a, params, cache }) {
if (params.bundle.hash !== a.data.hashCode) {
return StateObject.Null;
}
cache.source = a.data;
const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
if (s.elementCount === 0)
return StateObject.Null;
const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
return new SO.Molecule.Structure(s, props);
},
update: ({ a, b, oldParams, newParams, cache }) => {
if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
return StateTransformer.UpdateResult.Recreate;
}
if (newParams.bundle.hash !== a.data.hashCode) {
return StateTransformer.UpdateResult.Null;
}
if (cache.source === a.data) {
return StateTransformer.UpdateResult.Unchanged;
}
cache.source = a.data;
const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
if (s.elementCount === 0)
return StateTransformer.UpdateResult.Null;
b.label = `${newParams.label || 'Selection'}`;
b.description = Structure.elementDescription(s);
b.data = s;
return StateTransformer.UpdateResult.Updated;
},
dispose({ b }) {
b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
}
});
export const StructureComplexElementTypes = {
'polymer': 'polymer',
'protein': 'protein',
'nucleic': 'nucleic',
'water': 'water',
'branched': 'branched', // = carbs
'ligand': 'ligand',
'non-standard': 'non-standard',
'coarse': 'coarse',
// Legacy
'atomic-sequence': 'atomic-sequence',
'atomic-het': 'atomic-het',
'spheres': 'spheres'
};
const StructureComplexElementTypeTuples = PD.objectToOptions(StructureComplexElementTypes);
const StructureComplexElement = PluginStateTransform.BuiltIn({
name: 'structure-complex-element',
display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
from: SO.Molecule.Structure,
to: SO.Molecule.Structure,
params: { type: PD.Select('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
})({
apply({ a, params }) {
// TODO: update function.
let query, label;
switch (params.type) {
case 'polymer':
query = StructureSelectionQueries.polymer.query;
label = 'Polymer';
break;
case 'protein':
query = StructureSelectionQueries.protein.query;
label = 'Protein';
break;
case 'nucleic':
query = StructureSelectionQueries.nucleic.query;
label = 'Nucleic';
break;
case 'water':
query = Queries.internal.water();
label = 'Water';
break;
case 'branched':
query = StructureSelectionQueries.branchedPlusConnected.query;
label = 'Branched';
break;
c