model.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /**
  2. * Copyright (c) 2018-2019 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, ModelSymmetry, Queries, QueryContext, Structure, StructureQuery, StructureSelection as Sel, StructureSymmetry, QueryFn, StructureElement } from '../../../mol-model/structure';
  12. import { Assembly } from '../../../mol-model/structure/model/properties/symmetry';
  13. import { PluginContext } from '../../../mol-plugin/context';
  14. import { MolScriptBuilder } from '../../../mol-script/language/builder';
  15. import Expression from '../../../mol-script/language/expression';
  16. import { compile } from '../../../mol-script/runtime/query/compiler';
  17. import { StateObject, StateTransformer } from '../../../mol-state';
  18. import { RuntimeContext, Task } from '../../../mol-task';
  19. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  20. import { stringToWords } from '../../../mol-util/string';
  21. import { PluginStateObject as SO, PluginStateTransform } from '../objects';
  22. import { trajectoryFromGRO } from '../../../mol-model-formats/structure/gro';
  23. import { parseGRO } from '../../../mol-io/reader/gro/parser';
  24. import { shapeFromPly } from '../../../mol-model-formats/shape/ply';
  25. import { SymmetryOperator } from '../../../mol-math/geometry';
  26. import { ensureSecondaryStructure } from './helpers';
  27. import { Script } from '../../../mol-script/script';
  28. import { parse3DG } from '../../../mol-io/reader/3dg/parser';
  29. import { trajectoryFrom3DG } from '../../../mol-model-formats/structure/3dg';
  30. export { TrajectoryFromBlob };
  31. export { TrajectoryFromMmCif };
  32. export { TrajectoryFromPDB };
  33. export { TrajectoryFromGRO };
  34. export { TrajectoryFrom3DG };
  35. export { ModelFromTrajectory };
  36. export { StructureFromTrajectory };
  37. export { StructureFromModel };
  38. export { StructureAssemblyFromModel };
  39. export { StructureSymmetryFromModel };
  40. export { TransformStructureConformation };
  41. export { TransformStructureConformationByMatrix };
  42. export { StructureSelectionFromExpression };
  43. export { StructureSelectionFromScript };
  44. export { StructureSelectionFromBundle };
  45. export { StructureComplexElement };
  46. export { CustomModelProperties };
  47. export { CustomStructureProperties };
  48. type TrajectoryFromBlob = typeof TrajectoryFromBlob
  49. const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
  50. name: 'trajectory-from-blob',
  51. display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
  52. from: SO.Format.Blob,
  53. to: SO.Molecule.Trajectory
  54. })({
  55. apply({ a }) {
  56. return Task.create('Parse Format Blob', async ctx => {
  57. const models: Model[] = [];
  58. for (const e of a.data) {
  59. if (e.kind !== 'cif') continue;
  60. const block = e.data.blocks[0];
  61. const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
  62. if (xs.length === 0) throw new Error('No models found.');
  63. for (const x of xs) models.push(x);
  64. }
  65. const props = { label: `Trajectory`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  66. return new SO.Molecule.Trajectory(models, props);
  67. });
  68. }
  69. });
  70. type TrajectoryFromMmCif = typeof TrajectoryFromMmCif
  71. const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
  72. name: 'trajectory-from-mmcif',
  73. display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
  74. from: SO.Format.Cif,
  75. to: SO.Molecule.Trajectory,
  76. params(a) {
  77. if (!a) {
  78. return {
  79. 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.' }))
  80. };
  81. }
  82. const { blocks } = a.data;
  83. return {
  84. 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' }))
  85. };
  86. }
  87. })({
  88. isApplicable: a => a.data.blocks.length > 0,
  89. apply({ a, params }) {
  90. return Task.create('Parse mmCIF', async ctx => {
  91. const header = params.blockHeader || a.data.blocks[0].header;
  92. const block = a.data.blocks.find(b => b.header === header);
  93. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  94. const models = await trajectoryFromMmCIF(block).runInContext(ctx);
  95. if (models.length === 0) throw new Error('No models found.');
  96. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  97. return new SO.Molecule.Trajectory(models, props);
  98. });
  99. }
  100. });
  101. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  102. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  103. name: 'trajectory-from-pdb',
  104. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  105. from: [SO.Data.String],
  106. to: SO.Molecule.Trajectory
  107. })({
  108. apply({ a }) {
  109. return Task.create('Parse PDB', async ctx => {
  110. const parsed = await parsePDB(a.data, a.label).runInContext(ctx);
  111. if (parsed.isError) throw new Error(parsed.message);
  112. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  113. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  114. return new SO.Molecule.Trajectory(models, props);
  115. });
  116. }
  117. });
  118. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  119. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  120. name: 'trajectory-from-gro',
  121. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  122. from: [SO.Data.String],
  123. to: SO.Molecule.Trajectory
  124. })({
  125. apply({ a }) {
  126. return Task.create('Parse GRO', async ctx => {
  127. const parsed = await parseGRO(a.data).runInContext(ctx);
  128. if (parsed.isError) throw new Error(parsed.message);
  129. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  130. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  131. return new SO.Molecule.Trajectory(models, props);
  132. });
  133. }
  134. });
  135. type TrajectoryFrom3DG = typeof TrajectoryFrom3DG
  136. const TrajectoryFrom3DG = PluginStateTransform.BuiltIn({
  137. name: 'trajectory-from-3dg',
  138. display: { name: 'Parse 3DG', description: 'Parse 3DG string and create trajectory.' },
  139. from: [SO.Data.String],
  140. to: SO.Molecule.Trajectory
  141. })({
  142. apply({ a }) {
  143. return Task.create('Parse 3DG', async ctx => {
  144. const parsed = await parse3DG(a.data).runInContext(ctx);
  145. if (parsed.isError) throw new Error(parsed.message);
  146. const models = await trajectoryFrom3DG(parsed.result).runInContext(ctx);
  147. const props = { label: `${models[0].entry}`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  148. return new SO.Molecule.Trajectory(models, props);
  149. });
  150. }
  151. });
  152. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  153. type ModelFromTrajectory = typeof ModelFromTrajectory
  154. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  155. name: 'model-from-trajectory',
  156. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  157. from: SO.Molecule.Trajectory,
  158. to: SO.Molecule.Model,
  159. params: a => {
  160. if (!a) {
  161. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model' }) };
  162. }
  163. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.length, step: 1 }, { description: 'Model Index' })) }
  164. }
  165. })({
  166. isApplicable: a => a.data.length > 0,
  167. apply({ a, params }) {
  168. if (params.modelIndex < 0 || params.modelIndex >= a.data.length) throw new Error(`Invalid modelIndex ${params.modelIndex}`);
  169. const model = a.data[params.modelIndex];
  170. const label = `Model ${model.modelNum}`
  171. const description = a.data.length === 1 ? undefined : `Model ${params.modelIndex + 1} of ${a.data.length}`
  172. return new SO.Molecule.Model(model, { label, description });
  173. }
  174. });
  175. function structureDesc(s: Structure) {
  176. return s.elementCount === 1 ? '1 element' : `${s.elementCount} elements`
  177. }
  178. type StructureFromTrajectory = typeof StructureFromTrajectory
  179. const StructureFromTrajectory = PluginStateTransform.BuiltIn({
  180. name: 'structure-from-trajectory',
  181. display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
  182. from: SO.Molecule.Trajectory,
  183. to: SO.Molecule.Structure
  184. })({
  185. apply({ a }) {
  186. return Task.create('Build Structure', async ctx => {
  187. const s = Structure.ofTrajectory(a.data);
  188. const props = { label: 'Ensemble', description: structureDesc(s) };
  189. return new SO.Molecule.Structure(s, props);
  190. })
  191. }
  192. });
  193. type StructureFromModel = typeof StructureFromModel
  194. const StructureFromModel = PluginStateTransform.BuiltIn({
  195. name: 'structure-from-model',
  196. display: { name: 'Structure from Model', description: 'Create a molecular structure from the specified model.' },
  197. from: SO.Molecule.Model,
  198. to: SO.Molecule.Structure
  199. })({
  200. apply({ a }) {
  201. return Task.create('Build Structure', async ctx => {
  202. const s = Structure.ofModel(a.data);
  203. await ensureSecondaryStructure(s)
  204. const props = { label: 'Deposited', description: structureDesc(s) };
  205. return new SO.Molecule.Structure(s, props);
  206. })
  207. }
  208. });
  209. type StructureAssemblyFromModel = typeof StructureAssemblyFromModel
  210. const StructureAssemblyFromModel = PluginStateTransform.BuiltIn({
  211. name: 'structure-assembly-from-model',
  212. display: { name: 'Structure Assembly', description: 'Create a molecular structure assembly.' },
  213. from: SO.Molecule.Model,
  214. to: SO.Molecule.Structure,
  215. params(a) {
  216. if (!a) {
  217. return { id: PD.Optional(PD.Text('', { label: 'Assembly Id', description: 'Assembly Id. Value \'deposited\' can be used to specify deposited asymmetric unit.' })) };
  218. }
  219. const model = a.data;
  220. const ids = model.symmetry.assemblies.map(a => [a.id, `${a.id}: ${stringToWords(a.details)}`] as [string, string]);
  221. ids.push(['deposited', 'Deposited']);
  222. return {
  223. id: PD.Optional(PD.Select(ids[0][0], ids, { label: 'Asm Id', description: 'Assembly Id' })) };
  224. }
  225. })({
  226. apply({ a, params }, plugin: PluginContext) {
  227. return Task.create('Build Assembly', async ctx => {
  228. const model = a.data;
  229. let id = params.id;
  230. let asm: Assembly | undefined = void 0;
  231. // if no id is specified, use the 1st assembly.
  232. if (!id && model.symmetry.assemblies.length !== 0) {
  233. id = model.symmetry.assemblies[0].id;
  234. }
  235. if (model.symmetry.assemblies.length === 0) {
  236. if (id !== 'deposited') {
  237. plugin.log.warn(`Model '${a.data.entryId}' has no assembly, returning deposited structure.`);
  238. }
  239. } else {
  240. asm = ModelSymmetry.findAssembly(model, id || '');
  241. if (!asm) {
  242. plugin.log.warn(`Model '${a.data.entryId}' has no assembly called '${id}', returning deposited structure.`);
  243. }
  244. }
  245. const base = Structure.ofModel(model);
  246. if (!asm) {
  247. await ensureSecondaryStructure(base)
  248. const label = { label: 'Deposited', description: structureDesc(base) };
  249. return new SO.Molecule.Structure(base, label);
  250. }
  251. id = asm.id;
  252. const s = await StructureSymmetry.buildAssembly(base, id!).runInContext(ctx);
  253. await ensureSecondaryStructure(s)
  254. const props = { label: `Assembly ${id}`, description: structureDesc(s) };
  255. return new SO.Molecule.Structure(s, props);
  256. })
  257. }
  258. });
  259. type StructureSymmetryFromModel = typeof StructureSymmetryFromModel
  260. const StructureSymmetryFromModel = PluginStateTransform.BuiltIn({
  261. name: 'structure-symmetry-from-model',
  262. display: { name: 'Structure Symmetry', description: 'Create a molecular structure symmetry.' },
  263. from: SO.Molecule.Model,
  264. to: SO.Molecule.Structure,
  265. params(a) {
  266. return {
  267. ijkMin: PD.Vec3(Vec3.create(-1, -1, -1), { label: 'Min IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } }),
  268. ijkMax: PD.Vec3(Vec3.create(1, 1, 1), { label: 'Max IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } })
  269. }
  270. }
  271. })({
  272. apply({ a, params }, plugin: PluginContext) {
  273. return Task.create('Build Symmetry', async ctx => {
  274. const { ijkMin, ijkMax } = params
  275. const model = a.data;
  276. const base = Structure.ofModel(model);
  277. const s = await StructureSymmetry.buildSymmetryRange(base, ijkMin, ijkMax).runInContext(ctx);
  278. await ensureSecondaryStructure(s)
  279. const props = { label: `Symmetry [${ijkMin}] to [${ijkMax}]`, description: structureDesc(s) };
  280. return new SO.Molecule.Structure(s, props);
  281. })
  282. }
  283. });
  284. const _translation = Vec3.zero(), _m = Mat4.zero(), _n = Mat4.zero();
  285. type TransformStructureConformation = typeof TransformStructureConformation
  286. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  287. name: 'transform-structure-conformation',
  288. display: { name: 'Transform Conformation' },
  289. from: SO.Molecule.Structure,
  290. to: SO.Molecule.Structure,
  291. params: {
  292. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  293. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  294. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  295. }
  296. })({
  297. canAutoUpdate() {
  298. return true;
  299. },
  300. apply({ a, params }) {
  301. // TODO: optimze
  302. const center = a.data.boundary.sphere.center;
  303. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  304. Mat4.fromTranslation(_n, Vec3.add(_translation, center, params.translation));
  305. const rot = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * params.angle, Vec3.normalize(Vec3.zero(), params.axis));
  306. const m = Mat4.zero();
  307. Mat4.mul3(m, _n, rot, _m);
  308. const s = Structure.transform(a.data, m);
  309. const props = { label: `${a.label}`, description: `Transformed` };
  310. return new SO.Molecule.Structure(s, props);
  311. },
  312. interpolate(src, tar, t) {
  313. // TODO: optimize
  314. const u = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3.zero(), src.axis));
  315. Mat4.setTranslation(u, src.translation);
  316. const v = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3.zero(), tar.axis));
  317. Mat4.setTranslation(v, tar.translation);
  318. const m = SymmetryOperator.slerp(Mat4.zero(), u, v, t);
  319. const rot = Mat4.getRotation(Quat.zero(), m);
  320. const axis = Vec3.zero();
  321. const angle = Quat.getAxisAngle(axis, rot);
  322. const translation = Mat4.getTranslation(Vec3.zero(), m);
  323. return { axis, angle, translation };
  324. }
  325. });
  326. type TransformStructureConformationByMatrix = typeof TransformStructureConformation
  327. const TransformStructureConformationByMatrix = PluginStateTransform.BuiltIn({
  328. name: 'transform-structure-conformation-by-matrix',
  329. display: { name: 'Transform Conformation' },
  330. from: SO.Molecule.Structure,
  331. to: SO.Molecule.Structure,
  332. params: {
  333. matrix: PD.Value<Mat4>(Mat4.identity(), { isHidden: true })
  334. }
  335. })({
  336. canAutoUpdate() {
  337. return true;
  338. },
  339. apply({ a, params }) {
  340. const s = Structure.transform(a.data, params.matrix);
  341. const props = { label: `${a.label}`, description: `Transformed` };
  342. return new SO.Molecule.Structure(s, props);
  343. }
  344. });
  345. type StructureSelectionFromExpression = typeof StructureSelectionFromExpression
  346. const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  347. name: 'structure-selection-from-expression',
  348. display: { name: 'Structure Selection', description: 'Create a molecular structure from the specified expression.' },
  349. from: SO.Molecule.Structure,
  350. to: SO.Molecule.Structure,
  351. params: {
  352. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  353. label: PD.Optional(PD.Text('', { isHidden: true }))
  354. }
  355. })({
  356. apply({ a, params, cache }) {
  357. const compiled = compile<Sel>(params.expression);
  358. (cache as { compiled: QueryFn<Sel> }).compiled = compiled;
  359. (cache as { source: Structure }).source = a.data;
  360. const result = compiled(new QueryContext(a.data));
  361. const s = Sel.unionStructure(result);
  362. if (s.elementCount === 0) return StateObject.Null;
  363. const props = { label: `${params.label || 'Selection'}`, description: structureDesc(s) };
  364. return new SO.Molecule.Structure(s, props);
  365. },
  366. update: ({ a, b, oldParams, newParams, cache }) => {
  367. if (oldParams.expression !== newParams.expression) return StateTransformer.UpdateResult.Recreate;
  368. if ((cache as { source: Structure }).source === a.data) {
  369. return StateTransformer.UpdateResult.Unchanged;
  370. }
  371. (cache as { source: Structure }).source = a.data;
  372. if (updateStructureFromQuery((cache as { compiled: QueryFn<Sel> }).compiled, a.data, b, newParams.label)) {
  373. return StateTransformer.UpdateResult.Updated;
  374. }
  375. return StateTransformer.UpdateResult.Null;
  376. }
  377. });
  378. type StructureSelectionFromScript = typeof StructureSelectionFromScript
  379. const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
  380. name: 'structure-selection-from-script',
  381. display: { name: 'Structure Selection', description: 'Create a molecular structure from the specified script.' },
  382. from: SO.Molecule.Structure,
  383. to: SO.Molecule.Structure,
  384. params: {
  385. script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  386. label: PD.Optional(PD.Text(''))
  387. }
  388. })({
  389. apply({ a, params, cache }) {
  390. const query = Script.toQuery(params.script);
  391. (cache as { query: QueryFn<Sel> }).query = query;
  392. (cache as { source: Structure }).source = a.data;
  393. const result = query(new QueryContext(a.data));
  394. const s = Sel.unionStructure(result);
  395. const props = { label: `${params.label || 'Selection'}`, description: structureDesc(s) };
  396. return new SO.Molecule.Structure(s, props);
  397. },
  398. update: ({ a, b, oldParams, newParams, cache }) => {
  399. if (Script.areEqual(oldParams.script, newParams.script)) {
  400. return StateTransformer.UpdateResult.Recreate;
  401. }
  402. if ((cache as { source: Structure }).source === a.data) {
  403. return StateTransformer.UpdateResult.Unchanged;
  404. }
  405. (cache as { source: Structure }).source = a.data;
  406. updateStructureFromQuery((cache as { query: QueryFn<Sel> }).query, a.data, b, newParams.label);
  407. return StateTransformer.UpdateResult.Updated;
  408. }
  409. });
  410. function updateStructureFromQuery(query: QueryFn<Sel>, src: Structure, obj: SO.Molecule.Structure, label?: string) {
  411. const result = query(new QueryContext(src));
  412. const s = Sel.unionStructure(result);
  413. if (s.elementCount === 0) {
  414. return false;
  415. }
  416. obj.label = `${label || 'Selection'}`;
  417. obj.description = structureDesc(s);
  418. obj.data = s;
  419. return true;
  420. }
  421. type StructureSelectionFromBundle = typeof StructureSelectionFromBundle
  422. const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
  423. name: 'structure-selection-from-bundle',
  424. display: { name: 'Structure Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
  425. from: SO.Molecule.Structure,
  426. to: SO.Molecule.Structure,
  427. params: {
  428. bundle: PD.Value<StructureElement.Bundle>(StructureElement.Bundle.Empty, { isHidden: true }),
  429. label: PD.Optional(PD.Text('', { isHidden: true }))
  430. }
  431. })({
  432. apply({ a, params, cache }) {
  433. if (params.bundle.hash !== a.data.hashCode) {
  434. // Bundle not compatible with given structure, set to empty bundle
  435. params.bundle = StructureElement.Bundle.Empty
  436. }
  437. (cache as { source: Structure }).source = a.data;
  438. const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
  439. if (s.elementCount === 0) return StateObject.Null;
  440. const props = { label: `${params.label || 'Selection'}`, description: structureDesc(s) };
  441. return new SO.Molecule.Structure(s, props);
  442. },
  443. update: ({ a, b, oldParams, newParams, cache }) => {
  444. if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
  445. return StateTransformer.UpdateResult.Recreate;
  446. }
  447. if (newParams.bundle.hash !== a.data.hashCode) {
  448. // Bundle not compatible with given structure, set to empty bundle
  449. newParams.bundle = StructureElement.Bundle.Empty
  450. }
  451. if ((cache as { source: Structure }).source === a.data) {
  452. return StateTransformer.UpdateResult.Unchanged;
  453. }
  454. (cache as { source: Structure }).source = a.data;
  455. const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
  456. if (s.elementCount === 0) return StateTransformer.UpdateResult.Null;
  457. b.label = `${newParams.label || 'Selection'}`;
  458. b.description = structureDesc(s);
  459. b.data = s;
  460. return StateTransformer.UpdateResult.Updated;
  461. }
  462. });
  463. namespace StructureComplexElement {
  464. export type Types = 'atomic-sequence' | 'water' | 'atomic-het' | 'spheres'
  465. }
  466. const StructureComplexElementTypes: [StructureComplexElement.Types, StructureComplexElement.Types][] = ['atomic-sequence', 'water', 'atomic-het', 'spheres'].map(t => [t, t] as any);
  467. type StructureComplexElement = typeof StructureComplexElement
  468. const StructureComplexElement = PluginStateTransform.BuiltIn({
  469. name: 'structure-complex-element',
  470. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  471. from: SO.Molecule.Structure,
  472. to: SO.Molecule.Structure,
  473. params: { type: PD.Select<StructureComplexElement.Types>('atomic-sequence', StructureComplexElementTypes, { isHidden: true }) }
  474. })({
  475. apply({ a, params }) {
  476. // TODO: update function.
  477. let query: StructureQuery, label: string;
  478. switch (params.type) {
  479. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  480. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  481. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  482. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  483. default: throw new Error(`${params.type} is a not valid complex element.`);
  484. }
  485. const result = query(new QueryContext(a.data));
  486. const s = Sel.unionStructure(result);
  487. if (s.elementCount === 0) return StateObject.Null;
  488. return new SO.Molecule.Structure(s, { label, description: structureDesc(s) });
  489. }
  490. });
  491. type CustomModelProperties = typeof CustomModelProperties
  492. const CustomModelProperties = PluginStateTransform.BuiltIn({
  493. name: 'custom-model-properties',
  494. display: { name: 'Custom Model Properties' },
  495. from: SO.Molecule.Model,
  496. to: SO.Molecule.Model,
  497. params: (a, ctx: PluginContext) => {
  498. if (!a) return { properties: PD.MultiSelect([], [], { description: 'A list of property descriptor ids.' }) };
  499. return { properties: ctx.customModelProperties.getSelect(a.data) };
  500. }
  501. })({
  502. apply({ a, params }, ctx: PluginContext) {
  503. return Task.create('Custom Props', async taskCtx => {
  504. await attachModelProps(a.data, ctx, taskCtx, params.properties);
  505. return new SO.Molecule.Model(a.data, { label: 'Model Props', description: `${params.properties.length} Selected` });
  506. });
  507. }
  508. });
  509. async function attachModelProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, names: string[]) {
  510. for (const name of names) {
  511. try {
  512. const p = ctx.customModelProperties.get(name);
  513. await p.attach(model).runInContext(taskCtx);
  514. } catch (e) {
  515. ctx.log.warn(`Error attaching model prop '${name}': ${e}`);
  516. }
  517. }
  518. }
  519. type CustomStructureProperties = typeof CustomStructureProperties
  520. const CustomStructureProperties = PluginStateTransform.BuiltIn({
  521. name: 'custom-structure-properties',
  522. display: { name: 'Custom Structure Properties' },
  523. from: SO.Molecule.Structure,
  524. to: SO.Molecule.Structure,
  525. params: (a, ctx: PluginContext) => {
  526. if (!a) return { properties: PD.MultiSelect([], [], { description: 'A list of property descriptor ids.' }) };
  527. return { properties: ctx.customStructureProperties.getSelect(a.data) };
  528. }
  529. })({
  530. apply({ a, params }, ctx: PluginContext) {
  531. return Task.create('Custom Props', async taskCtx => {
  532. await attachStructureProps(a.data, ctx, taskCtx, params.properties);
  533. return new SO.Molecule.Structure(a.data, { label: 'Structure Props', description: `${params.properties.length} Selected` });
  534. });
  535. }
  536. });
  537. async function attachStructureProps(structure: Structure, ctx: PluginContext, taskCtx: RuntimeContext, names: string[]) {
  538. for (const name of names) {
  539. try {
  540. const p = ctx.customStructureProperties.get(name);
  541. await p.attach(structure).runInContext(taskCtx);
  542. } catch (e) {
  543. ctx.log.warn(`Error attaching structure prop '${name}': ${e}`);
  544. }
  545. }
  546. }
  547. export { ShapeFromPly }
  548. type ShapeFromPly = typeof ShapeFromPly
  549. const ShapeFromPly = PluginStateTransform.BuiltIn({
  550. name: 'shape-from-ply',
  551. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  552. from: SO.Format.Ply,
  553. to: SO.Shape.Provider,
  554. params(a) {
  555. return { };
  556. }
  557. })({
  558. apply({ a, params }) {
  559. return Task.create('Create shape from PLY', async ctx => {
  560. const shape = await shapeFromPly(a.data, params).runInContext(ctx)
  561. const props = { label: 'Shape' };
  562. return new SO.Shape.Provider(shape, props);
  563. });
  564. }
  565. });