model.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 { parsePDB } from '../../../mol-io/reader/pdb/parser';
  8. import { Vec3, Mat4, Quat } from '../../../mol-math/linear-algebra';
  9. import { trajectoryFromMmCIF } from '../../../mol-model-formats/structure/mmcif';
  10. import { trajectoryFromPDB } from '../../../mol-model-formats/structure/pdb';
  11. import { Model, Queries, QueryContext, Structure, StructureQuery, StructureSelection as Sel, StructureElement, Coordinates, Topology } from '../../../mol-model/structure';
  12. import { PluginContext } from '../../../mol-plugin/context';
  13. import { MolScriptBuilder } from '../../../mol-script/language/builder';
  14. import Expression from '../../../mol-script/language/expression';
  15. import { StateObject, StateTransformer } from '../../../mol-state';
  16. import { RuntimeContext, Task } from '../../../mol-task';
  17. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  18. import { stringToWords } from '../../../mol-util/string';
  19. import { PluginStateObject as SO, PluginStateTransform } from '../objects';
  20. import { trajectoryFromGRO } from '../../../mol-model-formats/structure/gro';
  21. import { parseGRO } from '../../../mol-io/reader/gro/parser';
  22. import { shapeFromPly } from '../../../mol-model-formats/shape/ply';
  23. import { SymmetryOperator } from '../../../mol-math/geometry';
  24. import { Script } from '../../../mol-script/script';
  25. import { parse3DG } from '../../../mol-io/reader/3dg/parser';
  26. import { trajectoryFrom3DG } from '../../../mol-model-formats/structure/3dg';
  27. import { StructureSelectionQueries } from '../../util/structure-selection-helper';
  28. import { StructureQueryHelper } from '../../util/structure-query';
  29. import { ModelStructureRepresentation } from '../representation/model';
  30. import { parseDcd } from '../../../mol-io/reader/dcd/parser';
  31. import { coordinatesFromDcd } from '../../../mol-model-formats/structure/dcd';
  32. import { topologyFromPsf } from '../../../mol-model-formats/structure/psf';
  33. import { deepEqual } from '../../../mol-util';
  34. export { CoordinatesFromDcd };
  35. export { TopologyFromPsf };
  36. export { TrajectoryFromModelAndCoordinates };
  37. export { TrajectoryFromBlob };
  38. export { TrajectoryFromMmCif };
  39. export { TrajectoryFromPDB };
  40. export { TrajectoryFromGRO };
  41. export { TrajectoryFrom3DG };
  42. export { ModelFromTrajectory };
  43. export { StructureFromTrajectory };
  44. export { StructureFromModel };
  45. export { StructureAssemblyFromModel };
  46. export { TransformStructureConformation };
  47. export { TransformStructureConformationByMatrix };
  48. export { StructureSelectionFromExpression };
  49. export { MultiStructureSelectionFromExpression }
  50. export { StructureSelectionFromScript };
  51. export { StructureSelectionFromBundle };
  52. export { StructureComplexElement };
  53. export { CustomModelProperties };
  54. export { CustomStructureProperties };
  55. type CoordinatesFromDcd = typeof CoordinatesFromDcd
  56. const CoordinatesFromDcd = PluginStateTransform.BuiltIn({
  57. name: 'coordinates-from-dcd',
  58. display: { name: 'Parse DCD', description: 'Parse DCD binary data.' },
  59. from: [SO.Data.Binary],
  60. to: SO.Molecule.Coordinates
  61. })({
  62. apply({ a }) {
  63. return Task.create('Parse DCD', async ctx => {
  64. const parsed = await parseDcd(a.data).runInContext(ctx);
  65. if (parsed.isError) throw new Error(parsed.message);
  66. const coordinates = await coordinatesFromDcd(parsed.result).runInContext(ctx);
  67. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  68. });
  69. }
  70. });
  71. type TopologyFromPsf = typeof TopologyFromPsf
  72. const TopologyFromPsf = PluginStateTransform.BuiltIn({
  73. name: 'topology-from-psf',
  74. display: { name: 'PSF Topology', description: 'Parse PSF string data.' },
  75. from: [SO.Format.Psf],
  76. to: SO.Molecule.Topology
  77. })({
  78. apply({ a }) {
  79. return Task.create('Create Topology', async ctx => {
  80. const topology = await topologyFromPsf(a.data).runInContext(ctx);
  81. return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
  82. });
  83. }
  84. });
  85. async function getTrajectory(ctx: RuntimeContext, obj: StateObject, coordinates: Coordinates) {
  86. if (obj.type === SO.Molecule.Topology.type) {
  87. const topology = obj.data as Topology
  88. return await Model.trajectoryFromTopologyAndCoordinates(topology, coordinates).runInContext(ctx);
  89. } else if (obj.type === SO.Molecule.Model.type) {
  90. const model = obj.data as Model
  91. return Model.trajectoryFromModelAndCoordinates(model, coordinates);
  92. }
  93. throw new Error('no model/topology found')
  94. }
  95. type TrajectoryFromModelAndCoordinates = typeof TrajectoryFromModelAndCoordinates
  96. const TrajectoryFromModelAndCoordinates = PluginStateTransform.BuiltIn({
  97. name: 'trajectory-from-model-and-coordinates',
  98. display: { name: 'Trajectory from Topology & Coordinates', description: 'Create a trajectory from existing model/topology and coordinates.' },
  99. from: SO.Root,
  100. to: SO.Molecule.Trajectory,
  101. params: {
  102. modelRef: PD.Text('', { isHidden: true }),
  103. coordinatesRef: PD.Text('', { isHidden: true }),
  104. }
  105. })({
  106. apply({ params, dependencies }) {
  107. return Task.create('Create trajectory from model/topology and coordinates', async ctx => {
  108. const coordinates = dependencies![params.coordinatesRef].data as Coordinates
  109. const trajectory = await getTrajectory(ctx, dependencies![params.modelRef], coordinates);
  110. const props = { label: 'Trajectory', description: `${trajectory.length} model${trajectory.length === 1 ? '' : 's'}` };
  111. return new SO.Molecule.Trajectory(trajectory, props);
  112. });
  113. }
  114. });
  115. type TrajectoryFromBlob = typeof TrajectoryFromBlob
  116. const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
  117. name: 'trajectory-from-blob',
  118. display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
  119. from: SO.Format.Blob,
  120. to: SO.Molecule.Trajectory
  121. })({
  122. apply({ a }) {
  123. return Task.create('Parse Format Blob', async ctx => {
  124. const models: Model[] = [];
  125. for (const e of a.data) {
  126. if (e.kind !== 'cif') continue;
  127. const block = e.data.blocks[0];
  128. const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
  129. if (xs.length === 0) throw new Error('No models found.');
  130. for (const x of xs) models.push(x);
  131. }
  132. const props = { label: 'Trajectory', description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  133. return new SO.Molecule.Trajectory(models, props);
  134. });
  135. }
  136. });
  137. type TrajectoryFromMmCif = typeof TrajectoryFromMmCif
  138. const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
  139. name: 'trajectory-from-mmcif',
  140. display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
  141. from: SO.Format.Cif,
  142. to: SO.Molecule.Trajectory,
  143. params(a) {
  144. if (!a) {
  145. return {
  146. 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.' }))
  147. };
  148. }
  149. const { blocks } = a.data;
  150. return {
  151. 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' }))
  152. };
  153. }
  154. })({
  155. isApplicable: a => a.data.blocks.length > 0,
  156. apply({ a, params }) {
  157. return Task.create('Parse mmCIF', async ctx => {
  158. const header = params.blockHeader || a.data.blocks[0].header;
  159. const block = a.data.blocks.find(b => b.header === header);
  160. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  161. const models = await trajectoryFromMmCIF(block).runInContext(ctx);
  162. if (models.length === 0) throw new Error('No models found.');
  163. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  164. return new SO.Molecule.Trajectory(models, props);
  165. });
  166. }
  167. });
  168. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  169. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  170. name: 'trajectory-from-pdb',
  171. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  172. from: [SO.Data.String],
  173. to: SO.Molecule.Trajectory
  174. })({
  175. apply({ a }) {
  176. return Task.create('Parse PDB', async ctx => {
  177. const parsed = await parsePDB(a.data, a.label).runInContext(ctx);
  178. if (parsed.isError) throw new Error(parsed.message);
  179. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  180. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  181. return new SO.Molecule.Trajectory(models, props);
  182. });
  183. }
  184. });
  185. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  186. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  187. name: 'trajectory-from-gro',
  188. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  189. from: [SO.Data.String],
  190. to: SO.Molecule.Trajectory
  191. })({
  192. apply({ a }) {
  193. return Task.create('Parse GRO', async ctx => {
  194. const parsed = await parseGRO(a.data).runInContext(ctx);
  195. if (parsed.isError) throw new Error(parsed.message);
  196. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  197. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  198. return new SO.Molecule.Trajectory(models, props);
  199. });
  200. }
  201. });
  202. type TrajectoryFrom3DG = typeof TrajectoryFrom3DG
  203. const TrajectoryFrom3DG = PluginStateTransform.BuiltIn({
  204. name: 'trajectory-from-3dg',
  205. display: { name: 'Parse 3DG', description: 'Parse 3DG string and create trajectory.' },
  206. from: [SO.Data.String],
  207. to: SO.Molecule.Trajectory
  208. })({
  209. apply({ a }) {
  210. return Task.create('Parse 3DG', async ctx => {
  211. const parsed = await parse3DG(a.data).runInContext(ctx);
  212. if (parsed.isError) throw new Error(parsed.message);
  213. const models = await trajectoryFrom3DG(parsed.result).runInContext(ctx);
  214. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  215. return new SO.Molecule.Trajectory(models, props);
  216. });
  217. }
  218. });
  219. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  220. type ModelFromTrajectory = typeof ModelFromTrajectory
  221. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  222. name: 'model-from-trajectory',
  223. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  224. from: SO.Molecule.Trajectory,
  225. to: SO.Molecule.Model,
  226. params: a => {
  227. if (!a) {
  228. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model' }) };
  229. }
  230. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.length, step: 1 }, { description: 'Model Index' })) }
  231. }
  232. })({
  233. isApplicable: a => a.data.length > 0,
  234. apply({ a, params }) {
  235. if (params.modelIndex < 0 || params.modelIndex >= a.data.length) throw new Error(`Invalid modelIndex ${params.modelIndex}`);
  236. const model = a.data[params.modelIndex];
  237. const label = `Model ${model.modelNum}`
  238. const description = a.data.length === 1 ? undefined : `Model ${params.modelIndex + 1} of ${a.data.length}`
  239. return new SO.Molecule.Model(model, { label, description });
  240. }
  241. });
  242. type StructureFromTrajectory = typeof StructureFromTrajectory
  243. const StructureFromTrajectory = PluginStateTransform.BuiltIn({
  244. name: 'structure-from-trajectory',
  245. display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
  246. from: SO.Molecule.Trajectory,
  247. to: SO.Molecule.Structure
  248. })({
  249. apply({ a }) {
  250. return Task.create('Build Structure', async ctx => {
  251. const s = Structure.ofTrajectory(a.data);
  252. const props = { label: 'Ensemble', description: Structure.elementDescription(s) };
  253. return new SO.Molecule.Structure(s, props);
  254. })
  255. }
  256. });
  257. type StructureFromModel = typeof StructureFromModel
  258. const StructureFromModel = PluginStateTransform.BuiltIn({
  259. name: 'structure-from-model',
  260. display: { name: 'Structure', description: 'Create a molecular structure (deposited, assembly, or symmetry) from the specified model.' },
  261. from: SO.Molecule.Model,
  262. to: SO.Molecule.Structure,
  263. params(a) { return ModelStructureRepresentation.getParams(a && a.data); }
  264. })({
  265. apply({ a, params }, plugin: PluginContext) {
  266. return Task.create('Build Structure', async ctx => {
  267. return ModelStructureRepresentation.create(plugin, ctx, a.data, params && params.type);
  268. })
  269. },
  270. update: ({ a, b, oldParams, newParams }) => {
  271. if (!b.data.models.includes(a.data)) return StateTransformer.UpdateResult.Recreate;
  272. if (!deepEqual(oldParams, newParams)) return StateTransformer.UpdateResult.Recreate;
  273. return StateTransformer.UpdateResult.Unchanged;
  274. }
  275. });
  276. // TODO: deprecate this in favor of StructureFromModel
  277. type StructureAssemblyFromModel = typeof StructureAssemblyFromModel
  278. const StructureAssemblyFromModel = PluginStateTransform.BuiltIn({
  279. name: 'structure-assembly-from-model',
  280. display: { name: 'Structure Assembly', description: 'Create a molecular structure assembly.' },
  281. from: SO.Molecule.Model,
  282. to: SO.Molecule.Structure,
  283. params(a) {
  284. if (!a) {
  285. return { id: PD.Optional(PD.Text('', { label: 'Assembly Id', description: 'Assembly Id. Value \'deposited\' can be used to specify deposited asymmetric unit.' })) };
  286. }
  287. const model = a.data;
  288. const ids = model.symmetry.assemblies.map(a => [a.id, `${a.id}: ${stringToWords(a.details)}`] as [string, string]);
  289. ids.push(['deposited', 'Deposited']);
  290. return {
  291. id: PD.Optional(PD.Select(ids[0][0], ids, { label: 'Asm Id', description: 'Assembly Id' }))
  292. };
  293. }
  294. })({
  295. apply({ a, params }, plugin: PluginContext) {
  296. return Task.create('Build Assembly', async ctx => {
  297. return ModelStructureRepresentation.create(plugin, ctx, a.data, { name: 'assembly', params });
  298. })
  299. }
  300. });
  301. const _translation = Vec3(), _m = Mat4(), _n = Mat4();
  302. type TransformStructureConformation = typeof TransformStructureConformation
  303. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  304. name: 'transform-structure-conformation',
  305. display: { name: 'Transform Conformation' },
  306. from: SO.Molecule.Structure,
  307. to: SO.Molecule.Structure,
  308. params: {
  309. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  310. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  311. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  312. }
  313. })({
  314. canAutoUpdate() {
  315. return true;
  316. },
  317. apply({ a, params }) {
  318. // TODO: optimze
  319. const center = a.data.boundary.sphere.center;
  320. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  321. Mat4.fromTranslation(_n, Vec3.add(_translation, center, params.translation));
  322. const rot = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * params.angle, Vec3.normalize(Vec3.zero(), params.axis));
  323. const m = Mat4.zero();
  324. Mat4.mul3(m, _n, rot, _m);
  325. const s = Structure.transform(a.data, m);
  326. const props = { label: `${a.label}`, description: 'Transformed' };
  327. return new SO.Molecule.Structure(s, props);
  328. },
  329. interpolate(src, tar, t) {
  330. // TODO: optimize
  331. const u = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
  332. Mat4.setTranslation(u, src.translation);
  333. const v = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
  334. Mat4.setTranslation(v, tar.translation);
  335. const m = SymmetryOperator.slerp(Mat4.zero(), u, v, t);
  336. const rot = Mat4.getRotation(Quat.zero(), m);
  337. const axis = Vec3.zero();
  338. const angle = Quat.getAxisAngle(axis, rot);
  339. const translation = Mat4.getTranslation(Vec3.zero(), m);
  340. return { axis, angle, translation };
  341. }
  342. });
  343. type TransformStructureConformationByMatrix = typeof TransformStructureConformation
  344. const TransformStructureConformationByMatrix = PluginStateTransform.BuiltIn({
  345. name: 'transform-structure-conformation-by-matrix',
  346. display: { name: 'Transform Conformation' },
  347. from: SO.Molecule.Structure,
  348. to: SO.Molecule.Structure,
  349. params: {
  350. matrix: PD.Value<Mat4>(Mat4.identity(), { isHidden: true })
  351. }
  352. })({
  353. canAutoUpdate() {
  354. return true;
  355. },
  356. apply({ a, params }) {
  357. const s = Structure.transform(a.data, params.matrix);
  358. const props = { label: `${a.label}`, description: 'Transformed' };
  359. return new SO.Molecule.Structure(s, props);
  360. }
  361. });
  362. type StructureSelectionFromExpression = typeof StructureSelectionFromExpression
  363. const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  364. name: 'structure-selection-from-expression',
  365. display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
  366. from: SO.Molecule.Structure,
  367. to: SO.Molecule.Structure,
  368. params: {
  369. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  370. label: PD.Optional(PD.Text('', { isHidden: true }))
  371. }
  372. })({
  373. apply({ a, params, cache }) {
  374. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.expression);
  375. (cache as any).entry = entry;
  376. if (Sel.isEmpty(selection)) return StateObject.Null;
  377. const s = Sel.unionStructure(selection);
  378. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  379. return new SO.Molecule.Structure(s, props);
  380. },
  381. update: ({ a, b, oldParams, newParams, cache }) => {
  382. if (oldParams.expression !== newParams.expression) return StateTransformer.UpdateResult.Recreate;
  383. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  384. if (entry.currentStructure === a.data) {
  385. return StateTransformer.UpdateResult.Unchanged;
  386. }
  387. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  388. if (Sel.isEmpty(selection)) return StateTransformer.UpdateResult.Null;
  389. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  390. return StateTransformer.UpdateResult.Updated;
  391. }
  392. });
  393. type MultiStructureSelectionFromExpression = typeof MultiStructureSelectionFromExpression
  394. const MultiStructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  395. name: 'structure-multi-selection-from-expression',
  396. display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
  397. from: SO.Root,
  398. to: SO.Molecule.Structure.Selections,
  399. params: {
  400. selections: PD.ObjectList({
  401. key: PD.Text(void 0, { description: 'A unique key.' }),
  402. ref: PD.Text(),
  403. groupId: PD.Optional(PD.Text()),
  404. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.empty)
  405. }, e => e.ref, { isHidden: true }),
  406. isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
  407. label: PD.Optional(PD.Text('', { isHidden: true }))
  408. }
  409. })({
  410. apply({ params, cache, dependencies }) {
  411. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  412. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  413. let totalSize = 0;
  414. for (const sel of params.selections) {
  415. const { selection, entry } = StructureQueryHelper.createAndRun(dependencies![sel.ref].data as Structure, sel.expression);
  416. entries.set(sel.key, entry);
  417. const loci = Sel.toLociWithSourceUnits(selection);
  418. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  419. totalSize += StructureElement.Loci.size(loci);
  420. }
  421. (cache as object as any).entries = entries;
  422. // console.log(selections);
  423. const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
  424. return new SO.Molecule.Structure.Selections(selections, props);
  425. },
  426. update: ({ b, oldParams, newParams, cache, dependencies }) => {
  427. if (!!oldParams.isTransitive !== !!newParams.isTransitive) return StateTransformer.UpdateResult.Recreate;
  428. const cacheEntries = (cache as any).entries as Map<string, StructureQueryHelper.CacheEntry>;
  429. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  430. const current = new Map<string, SO.Molecule.Structure.SelectionEntry>();
  431. for (const e of b.data) current.set(e.key, e);
  432. let changed = false;
  433. let totalSize = 0;
  434. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  435. for (const sel of newParams.selections) {
  436. const structure = dependencies![sel.ref].data as Structure;
  437. let recreate = false;
  438. if (cacheEntries.has(sel.key)) {
  439. const entry = cacheEntries.get(sel.key)!;
  440. if (StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
  441. const loci = current.get(sel.key)!;
  442. if (loci.groupId !== sel.groupId) {
  443. loci.groupId = sel.groupId;
  444. changed = true;
  445. }
  446. entries.set(sel.key, entry);
  447. selections.push(loci);
  448. totalSize += StructureElement.Loci.size(loci.loci);
  449. continue;
  450. } if (entry.expression !== sel.expression) {
  451. recreate = true;
  452. } else {
  453. // TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
  454. let update = false;
  455. if (!!newParams.isTransitive) {
  456. if (Structure.areUnitAndIndicesEqual(entry.originalStructure, structure)) {
  457. const selection = StructureQueryHelper.run(entry, entry.originalStructure);
  458. entry.currentStructure = structure;
  459. entries.set(sel.key, entry);
  460. const loci = StructureElement.Loci.remap(Sel.toLociWithSourceUnits(selection), structure);
  461. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  462. totalSize += StructureElement.Loci.size(loci);
  463. changed = true;
  464. } else {
  465. update = true;
  466. }
  467. } else {
  468. update = true;
  469. }
  470. if (update) {
  471. changed = true;
  472. const selection = StructureQueryHelper.updateStructure(entry, structure);
  473. entries.set(sel.key, entry);
  474. const loci = Sel.toLociWithSourceUnits(selection);
  475. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  476. totalSize += StructureElement.Loci.size(loci);
  477. }
  478. }
  479. } else {
  480. recreate = true;
  481. }
  482. if (recreate) {
  483. changed = true;
  484. // create new selection
  485. const { selection, entry } = StructureQueryHelper.createAndRun(structure, sel.expression);
  486. entries.set(sel.key, entry);
  487. const loci = Sel.toLociWithSourceUnits(selection);
  488. selections.push({ key: sel.key, loci });
  489. totalSize += StructureElement.Loci.size(loci);
  490. }
  491. }
  492. if (!changed) return StateTransformer.UpdateResult.Unchanged;
  493. (cache as object as any).entries = entries;
  494. b.data = selections;
  495. b.label = `${newParams.label || 'Multi-selection'}`;
  496. b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
  497. // console.log('updated', selections);
  498. return StateTransformer.UpdateResult.Updated;
  499. }
  500. });
  501. type StructureSelectionFromScript = typeof StructureSelectionFromScript
  502. const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
  503. name: 'structure-selection-from-script',
  504. display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
  505. from: SO.Molecule.Structure,
  506. to: SO.Molecule.Structure,
  507. params: {
  508. script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  509. label: PD.Optional(PD.Text(''))
  510. }
  511. })({
  512. apply({ a, params, cache }) {
  513. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.script);
  514. (cache as any).entry = entry;
  515. const s = Sel.unionStructure(selection);
  516. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  517. return new SO.Molecule.Structure(s, props);
  518. },
  519. update: ({ a, b, oldParams, newParams, cache }) => {
  520. if (!Script.areEqual(oldParams.script, newParams.script)) {
  521. return StateTransformer.UpdateResult.Recreate;
  522. }
  523. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  524. if (entry.currentStructure === a.data) {
  525. return StateTransformer.UpdateResult.Unchanged;
  526. }
  527. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  528. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  529. return StateTransformer.UpdateResult.Updated;
  530. }
  531. });
  532. type StructureSelectionFromBundle = typeof StructureSelectionFromBundle
  533. const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
  534. name: 'structure-selection-from-bundle',
  535. display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
  536. from: SO.Molecule.Structure,
  537. to: SO.Molecule.Structure,
  538. params: {
  539. bundle: PD.Value<StructureElement.Bundle>(StructureElement.Bundle.Empty, { isHidden: true }),
  540. label: PD.Optional(PD.Text('', { isHidden: true }))
  541. }
  542. })({
  543. apply({ a, params, cache }) {
  544. if (params.bundle.hash !== a.data.hashCode) {
  545. // Bundle not compatible with given structure, set to empty bundle
  546. params.bundle = StructureElement.Bundle.Empty
  547. }
  548. (cache as { source: Structure }).source = a.data;
  549. const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
  550. if (s.elementCount === 0) return StateObject.Null;
  551. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  552. return new SO.Molecule.Structure(s, props);
  553. },
  554. update: ({ a, b, oldParams, newParams, cache }) => {
  555. if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
  556. return StateTransformer.UpdateResult.Recreate;
  557. }
  558. if (newParams.bundle.hash !== a.data.hashCode) {
  559. // Bundle not compatible with given structure, set to empty bundle
  560. newParams.bundle = StructureElement.Bundle.Empty
  561. }
  562. if ((cache as { source: Structure }).source === a.data) {
  563. return StateTransformer.UpdateResult.Unchanged;
  564. }
  565. (cache as { source: Structure }).source = a.data;
  566. const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
  567. if (s.elementCount === 0) return StateTransformer.UpdateResult.Null;
  568. b.label = `${newParams.label || 'Selection'}`;
  569. b.description = Structure.elementDescription(s);
  570. b.data = s;
  571. return StateTransformer.UpdateResult.Updated;
  572. }
  573. });
  574. export const StructureComplexElementTypes = {
  575. 'protein-or-nucleic': 'protein-or-nucleic',
  576. 'protein': 'protein',
  577. 'nucleic': 'nucleic',
  578. 'water': 'water',
  579. 'branched': 'branched', // = carbs
  580. 'ligand': 'ligand',
  581. 'modified': 'modified',
  582. 'coarse': 'coarse',
  583. // Legacy
  584. 'atomic-sequence': 'atomic-sequence',
  585. 'atomic-het': 'atomic-het',
  586. 'spheres': 'spheres'
  587. } as const
  588. export type StructureComplexElementTypes = keyof typeof StructureComplexElementTypes
  589. const StructureComplexElementTypeTuples = PD.objectToOptions(StructureComplexElementTypes);
  590. type StructureComplexElement = typeof StructureComplexElement
  591. const StructureComplexElement = PluginStateTransform.BuiltIn({
  592. name: 'structure-complex-element',
  593. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  594. from: SO.Molecule.Structure,
  595. to: SO.Molecule.Structure,
  596. params: { type: PD.Select<StructureComplexElementTypes>('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
  597. })({
  598. apply({ a, params }) {
  599. // TODO: update function.
  600. let query: StructureQuery, label: string;
  601. switch (params.type) {
  602. case 'protein-or-nucleic': query = StructureSelectionQueries.proteinOrNucleic.query; label = 'Sequence'; break;
  603. case 'protein': query = StructureSelectionQueries.protein.query; label = 'Protein'; break;
  604. case 'nucleic': query = StructureSelectionQueries.nucleic.query; label = 'Nucleic'; break;
  605. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  606. case 'branched': query = StructureSelectionQueries.branchedPlusConnected.query; label = 'Branched'; break;
  607. case 'ligand': query = StructureSelectionQueries.ligandPlusConnected.query; label = 'Ligand'; break;
  608. case 'modified': query = StructureSelectionQueries.modified.query; label = 'Modified'; break;
  609. case 'coarse': query = StructureSelectionQueries.coarse.query; label = 'Coarse'; break;
  610. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  611. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  612. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  613. default: throw new Error(`${params.type} is a not valid complex element.`);
  614. }
  615. const result = query(new QueryContext(a.data));
  616. const s = Sel.unionStructure(result);
  617. if (s.elementCount === 0) return StateObject.Null;
  618. return new SO.Molecule.Structure(s, { label, description: Structure.elementDescription(s) });
  619. }
  620. });
  621. type CustomModelProperties = typeof CustomModelProperties
  622. const CustomModelProperties = PluginStateTransform.BuiltIn({
  623. name: 'custom-model-properties',
  624. display: { name: 'Custom Properties' },
  625. from: SO.Molecule.Model,
  626. to: SO.Molecule.Model,
  627. params: (a, ctx: PluginContext) => {
  628. return ctx.customModelProperties.getParams(a?.data)
  629. }
  630. })({
  631. apply({ a, params }, ctx: PluginContext) {
  632. return Task.create('Custom Props', async taskCtx => {
  633. await attachModelProps(a.data, ctx, taskCtx, params);
  634. return new SO.Molecule.Model(a.data, { label: 'Model Props' });
  635. });
  636. }
  637. });
  638. async function attachModelProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomModelProperties['createDefaultParams']>) {
  639. const propertyCtx = { runtime: taskCtx, fetch: ctx.fetch }
  640. const { autoAttach, properties } = params
  641. for (const name of Object.keys(properties)) {
  642. const property = ctx.customModelProperties.get(name)
  643. const props = params[name as keyof typeof params]
  644. if (autoAttach.includes(name)) {
  645. try {
  646. await property.attach(propertyCtx, model, props)
  647. } catch (e) {
  648. ctx.log.warn(`Error attaching model prop '${name}': ${e}`);
  649. }
  650. } else {
  651. property.set(model, props)
  652. }
  653. }
  654. }
  655. type CustomStructureProperties = typeof CustomStructureProperties
  656. const CustomStructureProperties = PluginStateTransform.BuiltIn({
  657. name: 'custom-structure-properties',
  658. display: { name: 'Custom Structure Properties' },
  659. from: SO.Molecule.Structure,
  660. to: SO.Molecule.Structure,
  661. params: (a, ctx: PluginContext) => {
  662. return ctx.customStructureProperties.getParams(a?.data)
  663. }
  664. })({
  665. apply({ a, params }, ctx: PluginContext) {
  666. return Task.create('Custom Props', async taskCtx => {
  667. await attachStructureProps(a.data, ctx, taskCtx, params);
  668. return new SO.Molecule.Structure(a.data, { label: 'Structure Props' });
  669. });
  670. }
  671. });
  672. async function attachStructureProps(structure: Structure, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomStructureProperties['createDefaultParams']>) {
  673. const propertyCtx = { runtime: taskCtx, fetch: ctx.fetch }
  674. const { autoAttach, properties } = params
  675. for (const name of Object.keys(properties)) {
  676. const property = ctx.customStructureProperties.get(name)
  677. const props = params[name as keyof typeof params]
  678. if (autoAttach.includes(name)) {
  679. try {
  680. await property.attach(propertyCtx, structure, props)
  681. } catch (e) {
  682. ctx.log.warn(`Error attaching structure prop '${name}': ${e}`);
  683. }
  684. } else {
  685. property.set(structure, props)
  686. }
  687. }
  688. }
  689. export { ShapeFromPly }
  690. type ShapeFromPly = typeof ShapeFromPly
  691. const ShapeFromPly = PluginStateTransform.BuiltIn({
  692. name: 'shape-from-ply',
  693. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  694. from: SO.Format.Ply,
  695. to: SO.Shape.Provider,
  696. params(a) {
  697. return { };
  698. }
  699. })({
  700. apply({ a, params }) {
  701. return Task.create('Create shape from PLY', async ctx => {
  702. const shape = await shapeFromPly(a.data, params).runInContext(ctx)
  703. const props = { label: 'Shape' };
  704. return new SO.Shape.Provider(shape, props);
  705. });
  706. }
  707. });