model.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { parseDcd } from '../../mol-io/reader/dcd/parser';
  8. import { parseGRO } from '../../mol-io/reader/gro/parser';
  9. import { parsePDB } from '../../mol-io/reader/pdb/parser';
  10. import { Mat4, Vec3 } from '../../mol-math/linear-algebra';
  11. import { shapeFromPly } from '../../mol-model-formats/shape/ply';
  12. import { coordinatesFromDcd } from '../../mol-model-formats/structure/dcd';
  13. import { trajectoryFromGRO } from '../../mol-model-formats/structure/gro';
  14. import { trajectoryFromMmCIF } from '../../mol-model-formats/structure/mmcif';
  15. import { trajectoryFromPDB } from '../../mol-model-formats/structure/pdb';
  16. import { topologyFromPsf } from '../../mol-model-formats/structure/psf';
  17. import { Coordinates, Model, Queries, QueryContext, Structure, StructureElement, StructureQuery, StructureSelection as Sel, Topology, ArrayTrajectory, Trajectory } from '../../mol-model/structure';
  18. import { PluginContext } from '../../mol-plugin/context';
  19. import { MolScriptBuilder } from '../../mol-script/language/builder';
  20. import Expression from '../../mol-script/language/expression';
  21. import { Script } from '../../mol-script/script';
  22. import { StateObject, StateTransformer } from '../../mol-state';
  23. import { RuntimeContext, Task } from '../../mol-task';
  24. import { deepEqual } from '../../mol-util';
  25. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  26. import { RootStructureDefinition } from '../helpers/root-structure';
  27. import { createStructureComponent, StructureComponentParams, updateStructureComponent } from '../helpers/structure-component';
  28. import { StructureQueryHelper } from '../helpers/structure-query';
  29. import { StructureSelectionQueries } from '../helpers/structure-selection-query';
  30. import { PluginStateObject as SO, PluginStateTransform } from '../objects';
  31. import { parseMol } from '../../mol-io/reader/mol/parser';
  32. import { trajectoryFromMol } from '../../mol-model-formats/structure/mol';
  33. import { trajectoryFromCifCore } from '../../mol-model-formats/structure/cif-core';
  34. import { trajectoryFromCube } from '../../mol-model-formats/structure/cube';
  35. import { parseMol2 } from '../../mol-io/reader/mol2/parser';
  36. import { trajectoryFromMol2 } from '../../mol-model-formats/structure/mol2';
  37. import { parseXtc } from '../../mol-io/reader/xtc/parser';
  38. import { coordinatesFromXtc } from '../../mol-model-formats/structure/xtc';
  39. export { CoordinatesFromDcd };
  40. export { CoordinatesFromXtc };
  41. export { TopologyFromPsf };
  42. export { TrajectoryFromModelAndCoordinates };
  43. export { TrajectoryFromBlob };
  44. export { TrajectoryFromMmCif };
  45. export { TrajectoryFromPDB };
  46. export { TrajectoryFromGRO };
  47. export { TrajectoryFromMOL };
  48. export { TrajectoryFromMOL2 };
  49. export { TrajectoryFromCube };
  50. export { TrajectoryFromCifCore };
  51. export { ModelFromTrajectory };
  52. export { StructureFromTrajectory };
  53. export { StructureFromModel };
  54. export { TransformStructureConformation };
  55. export { StructureSelectionFromExpression };
  56. export { MultiStructureSelectionFromExpression };
  57. export { StructureSelectionFromScript };
  58. export { StructureSelectionFromBundle };
  59. export { StructureComplexElement };
  60. export { StructureComponent };
  61. export { CustomModelProperties };
  62. export { CustomStructureProperties };
  63. export { ShapeFromPly };
  64. type CoordinatesFromDcd = typeof CoordinatesFromDcd
  65. const CoordinatesFromDcd = PluginStateTransform.BuiltIn({
  66. name: 'coordinates-from-dcd',
  67. display: { name: 'Parse DCD', description: 'Parse DCD binary data.' },
  68. from: [SO.Data.Binary],
  69. to: SO.Molecule.Coordinates
  70. })({
  71. apply({ a }) {
  72. return Task.create('Parse DCD', async ctx => {
  73. const parsed = await parseDcd(a.data).runInContext(ctx);
  74. if (parsed.isError) throw new Error(parsed.message);
  75. const coordinates = await coordinatesFromDcd(parsed.result).runInContext(ctx);
  76. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  77. });
  78. }
  79. });
  80. type CoordinatesFromXtc = typeof CoordinatesFromDcd
  81. const CoordinatesFromXtc = PluginStateTransform.BuiltIn({
  82. name: 'coordinates-from-xtc',
  83. display: { name: 'Parse XTC', description: 'Parse XTC binary data.' },
  84. from: [SO.Data.Binary],
  85. to: SO.Molecule.Coordinates
  86. })({
  87. apply({ a }) {
  88. return Task.create('Parse XTC', async ctx => {
  89. const parsed = await parseXtc(a.data).runInContext(ctx);
  90. if (parsed.isError) throw new Error(parsed.message);
  91. const coordinates = await coordinatesFromXtc(parsed.result).runInContext(ctx);
  92. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  93. });
  94. }
  95. });
  96. type TopologyFromPsf = typeof TopologyFromPsf
  97. const TopologyFromPsf = PluginStateTransform.BuiltIn({
  98. name: 'topology-from-psf',
  99. display: { name: 'PSF Topology', description: 'Parse PSF string data.' },
  100. from: [SO.Format.Psf],
  101. to: SO.Molecule.Topology
  102. })({
  103. apply({ a }) {
  104. return Task.create('Create Topology', async ctx => {
  105. const topology = await topologyFromPsf(a.data).runInContext(ctx);
  106. return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
  107. });
  108. }
  109. });
  110. async function getTrajectory(ctx: RuntimeContext, obj: StateObject, coordinates: Coordinates) {
  111. if (obj.type === SO.Molecule.Topology.type) {
  112. const topology = obj.data as Topology;
  113. return await Model.trajectoryFromTopologyAndCoordinates(topology, coordinates).runInContext(ctx);
  114. } else if (obj.type === SO.Molecule.Model.type) {
  115. const model = obj.data as Model;
  116. return Model.trajectoryFromModelAndCoordinates(model, coordinates);
  117. }
  118. throw new Error('no model/topology found');
  119. }
  120. type TrajectoryFromModelAndCoordinates = typeof TrajectoryFromModelAndCoordinates
  121. const TrajectoryFromModelAndCoordinates = PluginStateTransform.BuiltIn({
  122. name: 'trajectory-from-model-and-coordinates',
  123. display: { name: 'Trajectory from Topology & Coordinates', description: 'Create a trajectory from existing model/topology and coordinates.' },
  124. from: SO.Root,
  125. to: SO.Molecule.Trajectory,
  126. params: {
  127. modelRef: PD.Text('', { isHidden: true }),
  128. coordinatesRef: PD.Text('', { isHidden: true }),
  129. }
  130. })({
  131. apply({ params, dependencies }) {
  132. return Task.create('Create trajectory from model/topology and coordinates', async ctx => {
  133. const coordinates = dependencies![params.coordinatesRef].data as Coordinates;
  134. const trajectory = await getTrajectory(ctx, dependencies![params.modelRef], coordinates);
  135. const props = { label: 'Trajectory', description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
  136. return new SO.Molecule.Trajectory(trajectory, props);
  137. });
  138. }
  139. });
  140. type TrajectoryFromBlob = typeof TrajectoryFromBlob
  141. const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
  142. name: 'trajectory-from-blob',
  143. display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
  144. from: SO.Format.Blob,
  145. to: SO.Molecule.Trajectory
  146. })({
  147. apply({ a }) {
  148. return Task.create('Parse Format Blob', async ctx => {
  149. const models: Model[] = [];
  150. for (const e of a.data) {
  151. if (e.kind !== 'cif') continue;
  152. const block = e.data.blocks[0];
  153. const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
  154. if (xs.frameCount === 0) throw new Error('No models found.');
  155. for (let i = 0; i < xs.frameCount; i++) {
  156. const x = await Task.resolveInContext(xs.getFrameAtIndex(i), ctx);
  157. models.push(x);
  158. }
  159. }
  160. for (let i = 0; i < models.length; i++) {
  161. Model.TrajectoryInfo.set(models[i], { index: i, size: models.length });
  162. }
  163. const props = { label: 'Trajectory', description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  164. return new SO.Molecule.Trajectory(new ArrayTrajectory(models), props);
  165. });
  166. }
  167. });
  168. function trajectoryProps(trajectory: Trajectory) {
  169. const first = trajectory.representative;
  170. return { label: `${first.entry}`, description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
  171. }
  172. type TrajectoryFromMmCif = typeof TrajectoryFromMmCif
  173. const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
  174. name: 'trajectory-from-mmcif',
  175. display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
  176. from: SO.Format.Cif,
  177. to: SO.Molecule.Trajectory,
  178. params(a) {
  179. if (!a) {
  180. return {
  181. 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.' }))
  182. };
  183. }
  184. const { blocks } = a.data;
  185. return {
  186. blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, blocks.map(b => [b.header, b.header] as [string, string]), { description: 'Header of the block to parse' }))
  187. };
  188. }
  189. })({
  190. isApplicable: a => a.data.blocks.length > 0,
  191. apply({ a, params }) {
  192. return Task.create('Parse mmCIF', async ctx => {
  193. const header = params.blockHeader || a.data.blocks[0].header;
  194. const block = a.data.blocks.find(b => b.header === header);
  195. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  196. const models = await trajectoryFromMmCIF(block).runInContext(ctx);
  197. if (models.frameCount === 0) throw new Error('No models found.');
  198. const props = trajectoryProps(models);
  199. return new SO.Molecule.Trajectory(models, props);
  200. });
  201. }
  202. });
  203. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  204. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  205. name: 'trajectory-from-pdb',
  206. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  207. from: [SO.Data.String],
  208. to: SO.Molecule.Trajectory,
  209. params: {
  210. isPdbqt: PD.Boolean(false)
  211. }
  212. })({
  213. apply({ a, params }) {
  214. return Task.create('Parse PDB', async ctx => {
  215. const parsed = await parsePDB(a.data, a.label, params.isPdbqt).runInContext(ctx);
  216. if (parsed.isError) throw new Error(parsed.message);
  217. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  218. const props = trajectoryProps(models);
  219. return new SO.Molecule.Trajectory(models, props);
  220. });
  221. }
  222. });
  223. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  224. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  225. name: 'trajectory-from-gro',
  226. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  227. from: [SO.Data.String],
  228. to: SO.Molecule.Trajectory
  229. })({
  230. apply({ a }) {
  231. return Task.create('Parse GRO', async ctx => {
  232. const parsed = await parseGRO(a.data).runInContext(ctx);
  233. if (parsed.isError) throw new Error(parsed.message);
  234. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  235. const props = trajectoryProps(models);
  236. return new SO.Molecule.Trajectory(models, props);
  237. });
  238. }
  239. });
  240. type TrajectoryFromMOL = typeof TrajectoryFromMOL
  241. const TrajectoryFromMOL = PluginStateTransform.BuiltIn({
  242. name: 'trajectory-from-mol',
  243. display: { name: 'Parse MOL', description: 'Parse MOL string and create trajectory.' },
  244. from: [SO.Data.String],
  245. to: SO.Molecule.Trajectory
  246. })({
  247. apply({ a }) {
  248. return Task.create('Parse MOL', async ctx => {
  249. const parsed = await parseMol(a.data).runInContext(ctx);
  250. if (parsed.isError) throw new Error(parsed.message);
  251. const models = await trajectoryFromMol(parsed.result).runInContext(ctx);
  252. const props = trajectoryProps(models);
  253. return new SO.Molecule.Trajectory(models, props);
  254. });
  255. }
  256. });
  257. type TrajectoryFromMOL2 = typeof TrajectoryFromMOL
  258. const TrajectoryFromMOL2 = PluginStateTransform.BuiltIn({
  259. name: 'trajectory-from-mol2',
  260. display: { name: 'Parse MOL2', description: 'Parse MOL2 string and create trajectory.' },
  261. from: [SO.Data.String],
  262. to: SO.Molecule.Trajectory
  263. })({
  264. apply({ a }) {
  265. return Task.create('Parse MOL2', async ctx => {
  266. const parsed = await parseMol2(a.data, a.label).runInContext(ctx);
  267. if (parsed.isError) throw new Error(parsed.message);
  268. const models = await trajectoryFromMol2(parsed.result).runInContext(ctx);
  269. const props = trajectoryProps(models);
  270. return new SO.Molecule.Trajectory(models, props);
  271. });
  272. }
  273. });
  274. type TrajectoryFromCube = typeof TrajectoryFromCube
  275. const TrajectoryFromCube = PluginStateTransform.BuiltIn({
  276. name: 'trajectory-from-cube',
  277. display: { name: 'Parse Cube', description: 'Parse Cube file to create a trajectory.' },
  278. from: SO.Format.Cube,
  279. to: SO.Molecule.Trajectory
  280. })({
  281. apply({ a }) {
  282. return Task.create('Parse MOL', async ctx => {
  283. const models = await trajectoryFromCube(a.data).runInContext(ctx);
  284. const props = trajectoryProps(models);
  285. return new SO.Molecule.Trajectory(models, props);
  286. });
  287. }
  288. });
  289. type TrajectoryFromCifCore = typeof TrajectoryFromCifCore
  290. const TrajectoryFromCifCore = PluginStateTransform.BuiltIn({
  291. name: 'trajectory-from-cif-core',
  292. display: { name: 'Parse CIF Core', description: 'Identify and create all separate models in the specified CIF data block' },
  293. from: SO.Format.Cif,
  294. to: SO.Molecule.Trajectory,
  295. params(a) {
  296. if (!a) {
  297. return {
  298. 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.' }))
  299. };
  300. }
  301. const { blocks } = a.data;
  302. return {
  303. blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, blocks.map(b => [b.header, b.header] as [string, string]), { description: 'Header of the block to parse' }))
  304. };
  305. }
  306. })({
  307. apply({ a, params }) {
  308. return Task.create('Parse CIF Core', async ctx => {
  309. const header = params.blockHeader || a.data.blocks[0].header;
  310. const block = a.data.blocks.find(b => b.header === header);
  311. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  312. const models = await trajectoryFromCifCore(block).runInContext(ctx);
  313. if (models.frameCount === 0) throw new Error('No models found.');
  314. const props = trajectoryProps(models);
  315. return new SO.Molecule.Trajectory(models, props);
  316. });
  317. }
  318. });
  319. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  320. type ModelFromTrajectory = typeof ModelFromTrajectory
  321. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  322. name: 'model-from-trajectory',
  323. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  324. from: SO.Molecule.Trajectory,
  325. to: SO.Molecule.Model,
  326. params: a => {
  327. if (!a) {
  328. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model' }) };
  329. }
  330. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.frameCount, step: 1 }, { description: 'Model Index' })) };
  331. }
  332. })({
  333. isApplicable: a => a.data.frameCount > 0,
  334. apply({ a, params }) {
  335. return Task.create('Model from Trajectory', async ctx => {
  336. let modelIndex = params.modelIndex % a.data.frameCount;
  337. if (modelIndex < 0) modelIndex += a.data.frameCount;
  338. const model = await Task.resolveInContext(a.data.getFrameAtIndex(modelIndex), ctx);
  339. const label = `Model ${modelIndex + 1}`;
  340. let description = a.data.frameCount === 1 ? undefined : `of ${a.data.frameCount}`;
  341. return new SO.Molecule.Model(model, { label, description });
  342. });
  343. },
  344. dispose({ b }) {
  345. b?.data.customProperties.dispose();
  346. }
  347. });
  348. type StructureFromTrajectory = typeof StructureFromTrajectory
  349. const StructureFromTrajectory = PluginStateTransform.BuiltIn({
  350. name: 'structure-from-trajectory',
  351. display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
  352. from: SO.Molecule.Trajectory,
  353. to: SO.Molecule.Structure
  354. })({
  355. apply({ a }) {
  356. return Task.create('Build Structure', async ctx => {
  357. const s = await Structure.ofTrajectory(a.data, ctx);
  358. const props = { label: 'Ensemble', description: Structure.elementDescription(s) };
  359. return new SO.Molecule.Structure(s, props);
  360. });
  361. },
  362. dispose({ b }) {
  363. b?.data.customPropertyDescriptors.dispose();
  364. }
  365. });
  366. type StructureFromModel = typeof StructureFromModel
  367. const StructureFromModel = PluginStateTransform.BuiltIn({
  368. name: 'structure-from-model',
  369. display: { name: 'Structure', description: 'Create a molecular structure (model, assembly, or symmetry) from the specified model.' },
  370. from: SO.Molecule.Model,
  371. to: SO.Molecule.Structure,
  372. params(a) { return RootStructureDefinition.getParams(a && a.data); }
  373. })({
  374. canAutoUpdate({ oldParams, newParams }) {
  375. return RootStructureDefinition.canAutoUpdate(oldParams.type, newParams.type);
  376. },
  377. apply({ a, params }, plugin: PluginContext) {
  378. return Task.create('Build Structure', async ctx => {
  379. return RootStructureDefinition.create(plugin, ctx, a.data, params && params.type);
  380. });
  381. },
  382. update: ({ a, b, oldParams, newParams }) => {
  383. if (!deepEqual(oldParams, newParams)) return StateTransformer.UpdateResult.Recreate;
  384. if (b.data.model === a.data) return StateTransformer.UpdateResult.Unchanged;
  385. if (!Model.areHierarchiesEqual(a.data, b.data.model)) return StateTransformer.UpdateResult.Recreate;
  386. b.data = b.data.remapModel(a.data);
  387. return StateTransformer.UpdateResult.Updated;
  388. },
  389. dispose({ b }) {
  390. b?.data.customPropertyDescriptors.dispose();
  391. }
  392. });
  393. const _translation = Vec3(), _m = Mat4(), _n = Mat4();
  394. type TransformStructureConformation = typeof TransformStructureConformation
  395. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  396. name: 'transform-structure-conformation',
  397. display: { name: 'Transform Conformation' },
  398. isDecorator: true,
  399. from: SO.Molecule.Structure,
  400. to: SO.Molecule.Structure,
  401. params: {
  402. transform: PD.MappedStatic('components', {
  403. components: PD.Group({
  404. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  405. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  406. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  407. }, { isFlat: true }),
  408. matrix: PD.Group({
  409. data: PD.Mat4(Mat4.identity()),
  410. transpose: PD.Boolean(false)
  411. }, { isFlat: true })
  412. }, { label: 'Kind' })
  413. }
  414. })({
  415. canAutoUpdate({ newParams }) {
  416. return newParams.transform.name !== 'matrix';
  417. },
  418. apply({ a, params }) {
  419. // TODO: optimze
  420. // TODO: think of ways how to fast-track changes to this for animations
  421. const transform = Mat4();
  422. if (params.transform.name === 'components') {
  423. const { axis, angle, translation } = params.transform.params;
  424. const center = a.data.boundary.sphere.center;
  425. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  426. Mat4.fromTranslation(_n, Vec3.add(_translation, center, translation));
  427. const rot = Mat4.fromRotation(Mat4(), Math.PI / 180 * angle, Vec3.normalize(Vec3(), axis));
  428. Mat4.mul3(transform, _n, rot, _m);
  429. } else if (params.transform.name === 'matrix') {
  430. Mat4.copy(transform, params.transform.params.data);
  431. if (params.transform.params.transpose) Mat4.transpose(transform, transform);
  432. }
  433. const s = Structure.transform(a.data, transform);
  434. return new SO.Molecule.Structure(s, { label: a.label, description: `${a.description} [Transformed]` });
  435. },
  436. dispose({ b }) {
  437. b?.data.customPropertyDescriptors.dispose();
  438. }
  439. // interpolate(src, tar, t) {
  440. // // TODO: optimize
  441. // const u = Mat4.fromRotation(Mat4(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
  442. // Mat4.setTranslation(u, src.translation);
  443. // const v = Mat4.fromRotation(Mat4(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
  444. // Mat4.setTranslation(v, tar.translation);
  445. // const m = SymmetryOperator.slerp(Mat4(), u, v, t);
  446. // const rot = Mat4.getRotation(Quat.zero(), m);
  447. // const axis = Vec3();
  448. // const angle = Quat.getAxisAngle(axis, rot);
  449. // const translation = Mat4.getTranslation(Vec3(), m);
  450. // return { axis, angle, translation };
  451. // }
  452. });
  453. type StructureSelectionFromExpression = typeof StructureSelectionFromExpression
  454. const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  455. name: 'structure-selection-from-expression',
  456. display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
  457. from: SO.Molecule.Structure,
  458. to: SO.Molecule.Structure,
  459. params: {
  460. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  461. label: PD.Optional(PD.Text('', { isHidden: true }))
  462. }
  463. })({
  464. apply({ a, params, cache }) {
  465. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.expression);
  466. (cache as any).entry = entry;
  467. if (Sel.isEmpty(selection)) return StateObject.Null;
  468. const s = Sel.unionStructure(selection);
  469. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  470. return new SO.Molecule.Structure(s, props);
  471. },
  472. update: ({ a, b, oldParams, newParams, cache }) => {
  473. if (oldParams.expression !== newParams.expression) return StateTransformer.UpdateResult.Recreate;
  474. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  475. if (entry.currentStructure === a.data) {
  476. return StateTransformer.UpdateResult.Unchanged;
  477. }
  478. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  479. if (Sel.isEmpty(selection)) return StateTransformer.UpdateResult.Null;
  480. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  481. return StateTransformer.UpdateResult.Updated;
  482. },
  483. dispose({ b }) {
  484. b?.data.customPropertyDescriptors.dispose();
  485. }
  486. });
  487. type MultiStructureSelectionFromExpression = typeof MultiStructureSelectionFromExpression
  488. const MultiStructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  489. name: 'structure-multi-selection-from-expression',
  490. display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
  491. from: SO.Root,
  492. to: SO.Molecule.Structure.Selections,
  493. params: {
  494. selections: PD.ObjectList({
  495. key: PD.Text(void 0, { description: 'A unique key.' }),
  496. ref: PD.Text(),
  497. groupId: PD.Optional(PD.Text()),
  498. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.empty)
  499. }, e => e.ref, { isHidden: true }),
  500. isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
  501. label: PD.Optional(PD.Text('', { isHidden: true }))
  502. }
  503. })({
  504. apply({ params, cache, dependencies }) {
  505. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  506. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  507. let totalSize = 0;
  508. for (const sel of params.selections) {
  509. const { selection, entry } = StructureQueryHelper.createAndRun(dependencies![sel.ref].data as Structure, sel.expression);
  510. entries.set(sel.key, entry);
  511. const loci = Sel.toLociWithSourceUnits(selection);
  512. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  513. totalSize += StructureElement.Loci.size(loci);
  514. }
  515. (cache as object as any).entries = entries;
  516. const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
  517. return new SO.Molecule.Structure.Selections(selections, props);
  518. },
  519. update: ({ b, oldParams, newParams, cache, dependencies }) => {
  520. if (!!oldParams.isTransitive !== !!newParams.isTransitive) return StateTransformer.UpdateResult.Recreate;
  521. const cacheEntries = (cache as any).entries as Map<string, StructureQueryHelper.CacheEntry>;
  522. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  523. const current = new Map<string, SO.Molecule.Structure.SelectionEntry>();
  524. for (const e of b.data) current.set(e.key, e);
  525. let changed = false;
  526. let totalSize = 0;
  527. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  528. for (const sel of newParams.selections) {
  529. const structure = dependencies![sel.ref].data as Structure;
  530. let recreate = false;
  531. if (cacheEntries.has(sel.key)) {
  532. const entry = cacheEntries.get(sel.key)!;
  533. if (StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
  534. const loci = current.get(sel.key)!;
  535. if (loci.groupId !== sel.groupId) {
  536. loci.groupId = sel.groupId;
  537. changed = true;
  538. }
  539. entries.set(sel.key, entry);
  540. selections.push(loci);
  541. totalSize += StructureElement.Loci.size(loci.loci);
  542. continue;
  543. } if (entry.expression !== sel.expression) {
  544. recreate = true;
  545. } else {
  546. // TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
  547. let update = false;
  548. if (!!newParams.isTransitive) {
  549. if (Structure.areUnitIdsAndIndicesEqual(entry.originalStructure, structure)) {
  550. const selection = StructureQueryHelper.run(entry, entry.originalStructure);
  551. entry.currentStructure = structure;
  552. entries.set(sel.key, entry);
  553. const loci = StructureElement.Loci.remap(Sel.toLociWithSourceUnits(selection), structure);
  554. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  555. totalSize += StructureElement.Loci.size(loci);
  556. changed = true;
  557. } else {
  558. update = true;
  559. }
  560. } else {
  561. update = true;
  562. }
  563. if (update) {
  564. changed = true;
  565. const selection = StructureQueryHelper.updateStructure(entry, structure);
  566. entries.set(sel.key, entry);
  567. const loci = Sel.toLociWithSourceUnits(selection);
  568. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  569. totalSize += StructureElement.Loci.size(loci);
  570. }
  571. }
  572. } else {
  573. recreate = true;
  574. }
  575. if (recreate) {
  576. changed = true;
  577. // create new selection
  578. const { selection, entry } = StructureQueryHelper.createAndRun(structure, sel.expression);
  579. entries.set(sel.key, entry);
  580. const loci = Sel.toLociWithSourceUnits(selection);
  581. selections.push({ key: sel.key, loci });
  582. totalSize += StructureElement.Loci.size(loci);
  583. }
  584. }
  585. if (!changed) return StateTransformer.UpdateResult.Unchanged;
  586. (cache as object as any).entries = entries;
  587. b.data = selections;
  588. b.label = `${newParams.label || 'Multi-selection'}`;
  589. b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
  590. return StateTransformer.UpdateResult.Updated;
  591. }
  592. });
  593. type StructureSelectionFromScript = typeof StructureSelectionFromScript
  594. const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
  595. name: 'structure-selection-from-script',
  596. display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
  597. from: SO.Molecule.Structure,
  598. to: SO.Molecule.Structure,
  599. params: {
  600. script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  601. label: PD.Optional(PD.Text(''))
  602. }
  603. })({
  604. apply({ a, params, cache }) {
  605. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.script);
  606. (cache as any).entry = entry;
  607. const s = Sel.unionStructure(selection);
  608. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  609. return new SO.Molecule.Structure(s, props);
  610. },
  611. update: ({ a, b, oldParams, newParams, cache }) => {
  612. if (!Script.areEqual(oldParams.script, newParams.script)) {
  613. return StateTransformer.UpdateResult.Recreate;
  614. }
  615. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  616. if (entry.currentStructure === a.data) {
  617. return StateTransformer.UpdateResult.Unchanged;
  618. }
  619. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  620. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  621. return StateTransformer.UpdateResult.Updated;
  622. },
  623. dispose({ b }) {
  624. b?.data.customPropertyDescriptors.dispose();
  625. }
  626. });
  627. type StructureSelectionFromBundle = typeof StructureSelectionFromBundle
  628. const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
  629. name: 'structure-selection-from-bundle',
  630. display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
  631. from: SO.Molecule.Structure,
  632. to: SO.Molecule.Structure,
  633. params: {
  634. bundle: PD.Value<StructureElement.Bundle>(StructureElement.Bundle.Empty, { isHidden: true }),
  635. label: PD.Optional(PD.Text('', { isHidden: true }))
  636. }
  637. })({
  638. apply({ a, params, cache }) {
  639. if (params.bundle.hash !== a.data.hashCode) {
  640. return StateObject.Null;
  641. }
  642. (cache as { source: Structure }).source = a.data;
  643. const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
  644. if (s.elementCount === 0) return StateObject.Null;
  645. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  646. return new SO.Molecule.Structure(s, props);
  647. },
  648. update: ({ a, b, oldParams, newParams, cache }) => {
  649. if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
  650. return StateTransformer.UpdateResult.Recreate;
  651. }
  652. if (newParams.bundle.hash !== a.data.hashCode) {
  653. return StateTransformer.UpdateResult.Null;
  654. }
  655. if ((cache as { source: Structure }).source === a.data) {
  656. return StateTransformer.UpdateResult.Unchanged;
  657. }
  658. (cache as { source: Structure }).source = a.data;
  659. const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
  660. if (s.elementCount === 0) return StateTransformer.UpdateResult.Null;
  661. b.label = `${newParams.label || 'Selection'}`;
  662. b.description = Structure.elementDescription(s);
  663. b.data = s;
  664. return StateTransformer.UpdateResult.Updated;
  665. },
  666. dispose({ b }) {
  667. b?.data.customPropertyDescriptors.dispose();
  668. }
  669. });
  670. export const StructureComplexElementTypes = {
  671. 'polymer': 'polymer',
  672. 'protein': 'protein',
  673. 'nucleic': 'nucleic',
  674. 'water': 'water',
  675. 'branched': 'branched', // = carbs
  676. 'ligand': 'ligand',
  677. 'non-standard': 'non-standard',
  678. 'coarse': 'coarse',
  679. // Legacy
  680. 'atomic-sequence': 'atomic-sequence',
  681. 'atomic-het': 'atomic-het',
  682. 'spheres': 'spheres'
  683. } as const;
  684. export type StructureComplexElementTypes = keyof typeof StructureComplexElementTypes
  685. const StructureComplexElementTypeTuples = PD.objectToOptions(StructureComplexElementTypes);
  686. type StructureComplexElement = typeof StructureComplexElement
  687. const StructureComplexElement = PluginStateTransform.BuiltIn({
  688. name: 'structure-complex-element',
  689. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  690. from: SO.Molecule.Structure,
  691. to: SO.Molecule.Structure,
  692. params: { type: PD.Select<StructureComplexElementTypes>('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
  693. })({
  694. apply({ a, params }) {
  695. // TODO: update function.
  696. let query: StructureQuery, label: string;
  697. switch (params.type) {
  698. case 'polymer': query = StructureSelectionQueries.polymer.query; label = 'Polymer'; break;
  699. case 'protein': query = StructureSelectionQueries.protein.query; label = 'Protein'; break;
  700. case 'nucleic': query = StructureSelectionQueries.nucleic.query; label = 'Nucleic'; break;
  701. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  702. case 'branched': query = StructureSelectionQueries.branchedPlusConnected.query; label = 'Branched'; break;
  703. case 'ligand': query = StructureSelectionQueries.ligandPlusConnected.query; label = 'Ligand'; break;
  704. case 'non-standard': query = StructureSelectionQueries.nonStandardPolymer.query; label = 'Non-standard'; break;
  705. case 'coarse': query = StructureSelectionQueries.coarse.query; label = 'Coarse'; break;
  706. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  707. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  708. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  709. default: throw new Error(`${params.type} is a not valid complex element.`);
  710. }
  711. const result = query(new QueryContext(a.data));
  712. const s = Sel.unionStructure(result);
  713. if (s.elementCount === 0) return StateObject.Null;
  714. return new SO.Molecule.Structure(s, { label, description: Structure.elementDescription(s) });
  715. },
  716. dispose({ b }) {
  717. b?.data.customPropertyDescriptors.dispose();
  718. }
  719. });
  720. type StructureComponent = typeof StructureComponent
  721. const StructureComponent = PluginStateTransform.BuiltIn({
  722. name: 'structure-component',
  723. display: { name: 'Component', description: 'A molecular structure component.' },
  724. from: SO.Molecule.Structure,
  725. to: SO.Molecule.Structure,
  726. params: StructureComponentParams
  727. })({
  728. apply({ a, params, cache }) {
  729. return createStructureComponent(a.data, params, cache as any);
  730. },
  731. update: ({ a, b, oldParams, newParams, cache }) => {
  732. return updateStructureComponent(a.data, b, oldParams, newParams, cache as any);
  733. },
  734. dispose({ b }) {
  735. b?.data.customPropertyDescriptors.dispose();
  736. }
  737. });
  738. type CustomModelProperties = typeof CustomModelProperties
  739. const CustomModelProperties = PluginStateTransform.BuiltIn({
  740. name: 'custom-model-properties',
  741. display: { name: 'Custom Model Properties' },
  742. isDecorator: true,
  743. from: SO.Molecule.Model,
  744. to: SO.Molecule.Model,
  745. params: (a, ctx: PluginContext) => {
  746. return ctx.customModelProperties.getParams(a?.data);
  747. }
  748. })({
  749. apply({ a, params }, ctx: PluginContext) {
  750. return Task.create('Custom Props', async taskCtx => {
  751. await attachModelProps(a.data, ctx, taskCtx, params);
  752. return new SO.Molecule.Model(a.data, { label: a.label, description: a.description });
  753. });
  754. },
  755. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  756. return Task.create('Custom Props', async taskCtx => {
  757. b.data = a.data;
  758. b.label = a.label;
  759. b.description = a.description;
  760. for (const name of oldParams.autoAttach) {
  761. const property = ctx.customModelProperties.get(name);
  762. if (!property) continue;
  763. a.data.customProperties.reference(property.descriptor, false);
  764. }
  765. await attachModelProps(a.data, ctx, taskCtx, newParams);
  766. return StateTransformer.UpdateResult.Updated;
  767. });
  768. },
  769. dispose({ b }) {
  770. b?.data.customProperties.dispose();
  771. }
  772. });
  773. async function attachModelProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomModelProperties['createDefaultParams']>) {
  774. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  775. const { autoAttach, properties } = params;
  776. for (const name of Object.keys(properties)) {
  777. const property = ctx.customModelProperties.get(name);
  778. const props = properties[name];
  779. if (autoAttach.includes(name) || property.isHidden) {
  780. try {
  781. await property.attach(propertyCtx, model, props, true);
  782. } catch (e) {
  783. ctx.log.warn(`Error attaching model prop '${name}': ${e}`);
  784. }
  785. } else {
  786. property.set(model, props);
  787. }
  788. }
  789. }
  790. type CustomStructureProperties = typeof CustomStructureProperties
  791. const CustomStructureProperties = PluginStateTransform.BuiltIn({
  792. name: 'custom-structure-properties',
  793. display: { name: 'Custom Structure Properties' },
  794. isDecorator: true,
  795. from: SO.Molecule.Structure,
  796. to: SO.Molecule.Structure,
  797. params: (a, ctx: PluginContext) => {
  798. return ctx.customStructureProperties.getParams(a?.data.root);
  799. }
  800. })({
  801. apply({ a, params }, ctx: PluginContext) {
  802. return Task.create('Custom Props', async taskCtx => {
  803. await attachStructureProps(a.data.root, ctx, taskCtx, params);
  804. return new SO.Molecule.Structure(a.data, { label: a.label, description: a.description });
  805. });
  806. },
  807. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  808. if (a.data !== b.data) return StateTransformer.UpdateResult.Recreate;
  809. return Task.create('Custom Props', async taskCtx => {
  810. b.data = a.data;
  811. b.label = a.label;
  812. b.description = a.description;
  813. for (const name of oldParams.autoAttach) {
  814. const property = ctx.customStructureProperties.get(name);
  815. if (!property) continue;
  816. a.data.customPropertyDescriptors.reference(property.descriptor, false);
  817. }
  818. await attachStructureProps(a.data.root, ctx, taskCtx, newParams);
  819. return StateTransformer.UpdateResult.Updated;
  820. });
  821. },
  822. dispose({ b }) {
  823. b?.data.customPropertyDescriptors.dispose();
  824. }
  825. });
  826. async function attachStructureProps(structure: Structure, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomStructureProperties['createDefaultParams']>) {
  827. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  828. const { autoAttach, properties } = params;
  829. for (const name of Object.keys(properties)) {
  830. const property = ctx.customStructureProperties.get(name);
  831. const props = properties[name];
  832. if (autoAttach.includes(name) || property.isHidden) {
  833. try {
  834. await property.attach(propertyCtx, structure, props, true);
  835. } catch (e) {
  836. ctx.log.warn(`Error attaching structure prop '${name}': ${e}`);
  837. }
  838. } else {
  839. property.set(structure, props);
  840. }
  841. }
  842. }
  843. type ShapeFromPly = typeof ShapeFromPly
  844. const ShapeFromPly = PluginStateTransform.BuiltIn({
  845. name: 'shape-from-ply',
  846. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  847. from: SO.Format.Ply,
  848. to: SO.Shape.Provider,
  849. params(a) {
  850. return { };
  851. }
  852. })({
  853. apply({ a, params }) {
  854. return Task.create('Create shape from PLY', async ctx => {
  855. const shape = await shapeFromPly(a.data, params).runInContext(ctx);
  856. const props = { label: 'Shape' };
  857. return new SO.Shape.Provider(shape, props);
  858. });
  859. }
  860. });