model.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 } 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 { parseMolScript } from 'mol-script/language/parser';
  25. import { transpileMolScript } from 'mol-script/script/mol-script/symbols';
  26. import { shapeFromPly } from 'mol-model-formats/shape/ply';
  27. import { SymmetryOperator } from 'mol-math/geometry';
  28. export { TrajectoryFromBlob };
  29. export { TrajectoryFromMmCif };
  30. export { TrajectoryFromPDB };
  31. export { TrajectoryFromGRO };
  32. export { ModelFromTrajectory };
  33. export { StructureFromModel };
  34. export { StructureAssemblyFromModel };
  35. export { StructureSymmetryFromModel };
  36. export { TransformStructureConformation }
  37. export { StructureSelection };
  38. export { UserStructureSelection };
  39. export { StructureComplexElement };
  40. export { CustomModelProperties };
  41. type TrajectoryFromBlob = typeof TrajectoryFromBlob
  42. const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
  43. name: 'trajectory-from-blob',
  44. display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
  45. from: SO.Format.Blob,
  46. to: SO.Molecule.Trajectory
  47. })({
  48. apply({ a }) {
  49. return Task.create('Parse Format Blob', async ctx => {
  50. const models: Model[] = [];
  51. for (const e of a.data) {
  52. if (e.kind !== 'cif') continue;
  53. const block = e.data.blocks[0];
  54. const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
  55. if (xs.length === 0) throw new Error('No models found.');
  56. for (const x of xs) models.push(x);
  57. }
  58. const props = { label: `Trajectory`, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  59. return new SO.Molecule.Trajectory(models, props);
  60. });
  61. }
  62. });
  63. type TrajectoryFromMmCif = typeof TrajectoryFromMmCif
  64. const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
  65. name: 'trajectory-from-mmcif',
  66. display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
  67. from: SO.Format.Cif,
  68. to: SO.Molecule.Trajectory,
  69. params(a) {
  70. if (!a) {
  71. return {
  72. 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.' }))
  73. };
  74. }
  75. const { blocks } = a.data;
  76. return {
  77. 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' }))
  78. };
  79. }
  80. })({
  81. isApplicable: a => a.data.blocks.length > 0,
  82. apply({ a, params }) {
  83. return Task.create('Parse mmCIF', async ctx => {
  84. const header = params.blockHeader || a.data.blocks[0].header;
  85. const block = a.data.blocks.find(b => b.header === header);
  86. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  87. const models = await trajectoryFromMmCIF(block).runInContext(ctx);
  88. if (models.length === 0) throw new Error('No models found.');
  89. const props = { label: models[0].label, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  90. return new SO.Molecule.Trajectory(models, props);
  91. });
  92. }
  93. });
  94. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  95. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  96. name: 'trajectory-from-pdb',
  97. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  98. from: [SO.Data.String],
  99. to: SO.Molecule.Trajectory
  100. })({
  101. apply({ a }) {
  102. return Task.create('Parse PDB', async ctx => {
  103. const parsed = await parsePDB(a.data).runInContext(ctx);
  104. if (parsed.isError) throw new Error(parsed.message);
  105. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  106. const props = { label: models[0].label, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  107. return new SO.Molecule.Trajectory(models, props);
  108. });
  109. }
  110. });
  111. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  112. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  113. name: 'trajectory-from-gro',
  114. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  115. from: [SO.Data.String],
  116. to: SO.Molecule.Trajectory
  117. })({
  118. apply({ a }) {
  119. return Task.create('Parse GRO', async ctx => {
  120. const parsed = await parseGRO(a.data).runInContext(ctx);
  121. if (parsed.isError) throw new Error(parsed.message);
  122. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  123. const props = { label: models[0].label, description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  124. return new SO.Molecule.Trajectory(models, props);
  125. });
  126. }
  127. });
  128. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  129. type ModelFromTrajectory = typeof ModelFromTrajectory
  130. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  131. name: 'model-from-trajectory',
  132. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  133. from: SO.Molecule.Trajectory,
  134. to: SO.Molecule.Model,
  135. params: a => {
  136. if (!a) {
  137. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model' }) };
  138. }
  139. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.length, step: 1 }, { description: 'Model Index' })) }
  140. }
  141. })({
  142. isApplicable: a => a.data.length > 0,
  143. apply({ a, params }) {
  144. if (params.modelIndex < 0 || params.modelIndex >= a.data.length) throw new Error(`Invalid modelIndex ${params.modelIndex}`);
  145. const model = a.data[params.modelIndex];
  146. const props = a.data.length === 1
  147. ? { label: `${model.label}` }
  148. : { label: `${model.label}:${model.modelNum}`, description: `Model ${params.modelIndex + 1} of ${a.data.length}` };
  149. return new SO.Molecule.Model(model, props);
  150. }
  151. });
  152. type StructureFromModel = typeof StructureFromModel
  153. const StructureFromModel = PluginStateTransform.BuiltIn({
  154. name: 'structure-from-model',
  155. display: { name: 'Structure from Model', description: 'Create a molecular structure from the specified model.' },
  156. from: SO.Molecule.Model,
  157. to: SO.Molecule.Structure
  158. })({
  159. apply({ a }) {
  160. let s = Structure.ofModel(a.data);
  161. const props = { label: a.data.label, description: s.elementCount === 1 ? '1 element' : `${s.elementCount} elements` };
  162. return new SO.Molecule.Structure(s, props);
  163. }
  164. });
  165. function structureDesc(s: Structure) {
  166. return s.elementCount === 1 ? '1 element' : `${s.elementCount} elements`;
  167. }
  168. type StructureAssemblyFromModel = typeof StructureAssemblyFromModel
  169. const StructureAssemblyFromModel = PluginStateTransform.BuiltIn({
  170. name: 'structure-assembly-from-model',
  171. display: { name: 'Structure Assembly', description: 'Create a molecular structure assembly.' },
  172. from: SO.Molecule.Model,
  173. to: SO.Molecule.Structure,
  174. params(a) {
  175. if (!a) {
  176. return { id: PD.Optional(PD.Text('', { label: 'Assembly Id', description: 'Assembly Id. Value \'deposited\' can be used to specify deposited asymmetric unit.' })) };
  177. }
  178. const model = a.data;
  179. const ids = model.symmetry.assemblies.map(a => [a.id, `${a.id}: ${stringToWords(a.details)}`] as [string, string]);
  180. ids.push(['deposited', 'Deposited']);
  181. return { id: PD.Optional(PD.Select(ids[0][0], ids, { label: 'Asm Id', description: 'Assembly Id' })) };
  182. }
  183. })({
  184. apply({ a, params }, plugin: PluginContext) {
  185. return Task.create('Build Assembly', async ctx => {
  186. const model = a.data;
  187. let id = params.id;
  188. let asm: Assembly | undefined = void 0;
  189. // if no id is specified, use the 1st assembly.
  190. if (!id && model.symmetry.assemblies.length !== 0) {
  191. id = model.symmetry.assemblies[0].id;
  192. }
  193. if (model.symmetry.assemblies.length === 0) {
  194. if (id !== 'deposited') {
  195. plugin.log.warn(`Model '${a.data.label}' has no assembly, returning deposited structure.`);
  196. }
  197. } else {
  198. asm = ModelSymmetry.findAssembly(model, id || '');
  199. if (!asm) {
  200. plugin.log.warn(`Model '${a.data.label}' has no assembly called '${id}', returning deposited structure.`);
  201. }
  202. }
  203. const base = Structure.ofModel(model);
  204. if (!asm) {
  205. const label = { label: a.data.label, description: structureDesc(base) };
  206. return new SO.Molecule.Structure(base, label);
  207. }
  208. id = asm.id;
  209. const s = await StructureSymmetry.buildAssembly(base, id!).runInContext(ctx);
  210. const props = { label: `Assembly ${id}`, description: structureDesc(s) };
  211. return new SO.Molecule.Structure(s, props);
  212. })
  213. }
  214. });
  215. type StructureSymmetryFromModel = typeof StructureSymmetryFromModel
  216. const StructureSymmetryFromModel = PluginStateTransform.BuiltIn({
  217. name: 'structure-symmetry-from-model',
  218. display: { name: 'Structure Symmetry', description: 'Create a molecular structure symmetry.' },
  219. from: SO.Molecule.Model,
  220. to: SO.Molecule.Structure,
  221. params(a) {
  222. return {
  223. ijkMin: PD.Vec3(Vec3.create(-1, -1, -1), { label: 'Min IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } }),
  224. ijkMax: PD.Vec3(Vec3.create(1, 1, 1), { label: 'Max IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } })
  225. }
  226. }
  227. })({
  228. apply({ a, params }, plugin: PluginContext) {
  229. return Task.create('Build Symmetry', async ctx => {
  230. const { ijkMin, ijkMax } = params
  231. const model = a.data;
  232. const base = Structure.ofModel(model);
  233. const s = await StructureSymmetry.buildSymmetryRange(base, ijkMin, ijkMax).runInContext(ctx);
  234. const props = { label: `Symmetry [${ijkMin}] to [${ijkMax}]`, description: structureDesc(s) };
  235. return new SO.Molecule.Structure(s, props);
  236. })
  237. }
  238. });
  239. const _translation = Vec3.zero(), _m = Mat4.zero(), _n = Mat4.zero();
  240. type TransformStructureConformation = typeof TransformStructureConformation
  241. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  242. name: 'transform-structure-conformation',
  243. display: { name: 'Transform Conformation' },
  244. from: SO.Molecule.Structure,
  245. to: SO.Molecule.Structure,
  246. params: {
  247. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  248. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  249. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  250. }
  251. })({
  252. canAutoUpdate() {
  253. return true;
  254. },
  255. apply({ a, params }) {
  256. // TODO: optimze
  257. const center = a.data.boundary.sphere.center;
  258. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  259. Mat4.fromTranslation(_n, Vec3.add(_translation, center, params.translation));
  260. const rot = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * params.angle, Vec3.normalize(Vec3.zero(), params.axis));
  261. const m = Mat4.zero();
  262. Mat4.mul3(m, _n, rot, _m);
  263. const s = Structure.transform(a.data, m);
  264. const props = { label: `${a.label}`, description: `Transformed` };
  265. return new SO.Molecule.Structure(s, props);
  266. },
  267. interpolate(src, tar, t) {
  268. // TODO: optimize
  269. const u = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3.zero(), src.axis));
  270. Mat4.setTranslation(u, src.translation);
  271. const v = Mat4.fromRotation(Mat4.zero(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3.zero(), tar.axis));
  272. Mat4.setTranslation(v, tar.translation);
  273. const m = SymmetryOperator.slerp(Mat4.zero(), u, v, t);
  274. const rot = Mat4.getRotation(Quat.zero(), m);
  275. const axis = Vec3.zero();
  276. const angle = Quat.getAxisAngle(axis, rot);
  277. const translation = Mat4.getTranslation(Vec3.zero(), m);
  278. return { axis, angle, translation };
  279. }
  280. });
  281. type StructureSelection = typeof StructureSelection
  282. const StructureSelection = PluginStateTransform.BuiltIn({
  283. name: 'structure-selection',
  284. display: { name: 'Structure Selection', description: 'Create a molecular structure from the specified query expression.' },
  285. from: SO.Molecule.Structure,
  286. to: SO.Molecule.Structure,
  287. params: {
  288. query: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  289. label: PD.Optional(PD.Text('', { isHidden: true }))
  290. }
  291. })({
  292. apply({ a, params, cache }) {
  293. const compiled = compile<Sel>(params.query);
  294. (cache as { compiled: QueryFn<Sel> }).compiled = compiled;
  295. (cache as { source: Structure }).source = a.data;
  296. const result = compiled(new QueryContext(a.data));
  297. const s = Sel.unionStructure(result);
  298. if (s.elementCount === 0) return StateObject.Null;
  299. const props = { label: `${params.label || 'Selection'}`, description: structureDesc(s) };
  300. return new SO.Molecule.Structure(s, props);
  301. },
  302. update: ({ a, b, oldParams, newParams, cache }) => {
  303. if (oldParams.query !== newParams.query) return StateTransformer.UpdateResult.Recreate;
  304. if ((cache as { source: Structure }).source === a.data) {
  305. return StateTransformer.UpdateResult.Unchanged;
  306. }
  307. (cache as { source: Structure }).source = a.data;
  308. if (updateStructureFromQuery((cache as { compiled: QueryFn<Sel> }).compiled, a.data, b, newParams.label)) {
  309. return StateTransformer.UpdateResult.Updated;
  310. }
  311. return StateTransformer.UpdateResult.Null;
  312. }
  313. });
  314. type UserStructureSelection = typeof UserStructureSelection
  315. const UserStructureSelection = PluginStateTransform.BuiltIn({
  316. name: 'user-structure-selection',
  317. display: { name: 'Structure Selection', description: 'Create a molecular structure from the specified query expression.' },
  318. from: SO.Molecule.Structure,
  319. to: SO.Molecule.Structure,
  320. params: {
  321. query: PD.ScriptExpression({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  322. label: PD.Optional(PD.Text(''))
  323. }
  324. })({
  325. apply({ a, params, cache }) {
  326. const parsed = parseMolScript(params.query.expression);
  327. if (parsed.length === 0) throw new Error('No query');
  328. const query = transpileMolScript(parsed[0]);
  329. const compiled = compile<Sel>(query);
  330. (cache as { compiled: QueryFn<Sel> }).compiled = compiled;
  331. (cache as { source: Structure }).source = a.data;
  332. const result = compiled(new QueryContext(a.data));
  333. const s = Sel.unionStructure(result);
  334. const props = { label: `${params.label || 'Selection'}`, description: structureDesc(s) };
  335. return new SO.Molecule.Structure(s, props);
  336. },
  337. update: ({ a, b, oldParams, newParams, cache }) => {
  338. if (oldParams.query.language !== newParams.query.language || oldParams.query.expression !== newParams.query.expression) {
  339. return StateTransformer.UpdateResult.Recreate;
  340. }
  341. if ((cache as { source: Structure }).source === a.data) {
  342. return StateTransformer.UpdateResult.Unchanged;
  343. }
  344. (cache as { source: Structure }).source = a.data;
  345. updateStructureFromQuery((cache as { compiled: QueryFn<Sel> }).compiled, a.data, b, newParams.label);
  346. return StateTransformer.UpdateResult.Updated;
  347. }
  348. });
  349. function updateStructureFromQuery(query: QueryFn<Sel>, src: Structure, obj: SO.Molecule.Structure, label?: string) {
  350. const result = query(new QueryContext(src));
  351. const s = Sel.unionStructure(result);
  352. if (s.elementCount === 0) {
  353. return false;
  354. }
  355. obj.label = `${label || 'Selection'}`;
  356. obj.description = structureDesc(s);
  357. obj.data = s;
  358. return true;
  359. }
  360. namespace StructureComplexElement {
  361. export type Types = 'atomic-sequence' | 'water' | 'atomic-het' | 'spheres'
  362. }
  363. const StructureComplexElementTypes: [StructureComplexElement.Types, StructureComplexElement.Types][] = ['atomic-sequence', 'water', 'atomic-het', 'spheres'].map(t => [t, t] as any);
  364. type StructureComplexElement = typeof StructureComplexElement
  365. const StructureComplexElement = PluginStateTransform.BuiltIn({
  366. name: 'structure-complex-element',
  367. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  368. from: SO.Molecule.Structure,
  369. to: SO.Molecule.Structure,
  370. params: { type: PD.Select<StructureComplexElement.Types>('atomic-sequence', StructureComplexElementTypes, { isHidden: true }) }
  371. })({
  372. apply({ a, params }) {
  373. // TODO: update function.
  374. let query: StructureQuery, label: string;
  375. switch (params.type) {
  376. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  377. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  378. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  379. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  380. default: throw new Error(`${params.type} is a not valid complex element.`);
  381. }
  382. const result = query(new QueryContext(a.data));
  383. const s = Sel.unionStructure(result);
  384. if (s.elementCount === 0) return StateObject.Null;
  385. return new SO.Molecule.Structure(s, { label, description: structureDesc(s) });
  386. }
  387. });
  388. type CustomModelProperties = typeof CustomModelProperties
  389. const CustomModelProperties = PluginStateTransform.BuiltIn({
  390. name: 'custom-model-properties',
  391. display: { name: 'Custom Model Properties' },
  392. from: SO.Molecule.Model,
  393. to: SO.Molecule.Model,
  394. params: (a, ctx: PluginContext) => {
  395. if (!a) return { properties: PD.MultiSelect([], [], { description: 'A list of property descriptor ids.' }) };
  396. return { properties: ctx.customModelProperties.getSelect(a.data) };
  397. }
  398. })({
  399. apply({ a, params }, ctx: PluginContext) {
  400. return Task.create('Custom Props', async taskCtx => {
  401. await attachProps(a.data, ctx, taskCtx, params.properties);
  402. return new SO.Molecule.Model(a.data, { label: 'Props', description: `${params.properties.length} Selected` });
  403. });
  404. }
  405. });
  406. async function attachProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, names: string[]) {
  407. for (const name of names) {
  408. const p = ctx.customModelProperties.get(name);
  409. await p.attach(model).runInContext(taskCtx);
  410. }
  411. }
  412. export { ShapeFromPly }
  413. type ShapeFromPly = typeof ShapeFromPly
  414. const ShapeFromPly = PluginStateTransform.BuiltIn({
  415. name: 'shape-from-ply',
  416. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  417. from: SO.Format.Ply,
  418. to: SO.Shape.Provider,
  419. params(a) {
  420. return { };
  421. }
  422. })({
  423. apply({ a, params }) {
  424. return Task.create('Create shape from PLY', async ctx => {
  425. const shape = await shapeFromPly(a.data, params).runInContext(ctx)
  426. const props = { label: 'Shape' };
  427. return new SO.Shape.Provider(shape, props);
  428. });
  429. }
  430. });