model.ts 33 KB

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