model.ts 18 KB

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