structure.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 { PluginContext } from 'mol-plugin/context';
  8. import { StateAction, StateBuilder, StateSelection, StateTransformer, State } from 'mol-state';
  9. import { ParamDefinition as PD } from 'mol-util/param-definition';
  10. import { PluginStateObject } from '../objects';
  11. import { StateTransforms } from '../transforms';
  12. import { Download } from '../transforms/data';
  13. import { StructureRepresentation3DHelpers } from '../transforms/representation';
  14. import { CustomModelProperties, StructureSelection } from '../transforms/model';
  15. import { DataFormatProvider, guessCifVariant } from './data-format';
  16. import { FileInfo } from 'mol-util/file-info';
  17. import { Task } from 'mol-task';
  18. import { StructureElement } from 'mol-model/structure';
  19. export const MmcifProvider: DataFormatProvider<any> = {
  20. label: 'mmCIF',
  21. description: 'mmCIF',
  22. stringExtensions: ['cif', 'mmcif', 'mcif'],
  23. binaryExtensions: ['bcif'],
  24. isApplicable: (info: FileInfo, data: Uint8Array | string) => {
  25. if (info.ext === 'mmcif' || info.ext === 'mcif') return true
  26. // assume cif/bcif files that are not DensityServer CIF are mmCIF
  27. if (info.ext === 'cif' || info.ext === 'bcif') return guessCifVariant(info, data) !== 'dscif'
  28. return false
  29. },
  30. getDefaultBuilder: (ctx: PluginContext, data: StateBuilder.To<PluginStateObject.Data.Binary | PluginStateObject.Data.String>, state: State) => {
  31. return Task.create('mmCIF default builder', async taskCtx => {
  32. const traj = createModelTree(data, 'cif');
  33. await state.updateTree(createStructureTree(ctx, traj, false)).runInContext(taskCtx)
  34. })
  35. }
  36. }
  37. export const PdbProvider: DataFormatProvider<any> = {
  38. label: 'PDB',
  39. description: 'PDB',
  40. stringExtensions: ['pdb', 'ent'],
  41. binaryExtensions: [],
  42. isApplicable: (info: FileInfo, data: string) => {
  43. return info.ext === 'pdb' || info.ext === 'ent'
  44. },
  45. getDefaultBuilder: (ctx: PluginContext, data: StateBuilder.To<PluginStateObject.Data.String>, state: State) => {
  46. return Task.create('PDB default builder', async taskCtx => {
  47. const traj = createModelTree(data, 'pdb');
  48. await state.updateTree(createStructureTree(ctx, traj, false)).runInContext(taskCtx)
  49. })
  50. }
  51. }
  52. export const GroProvider: DataFormatProvider<any> = {
  53. label: 'GRO',
  54. description: 'GRO',
  55. stringExtensions: ['gro'],
  56. binaryExtensions: [],
  57. isApplicable: (info: FileInfo, data: string) => {
  58. return info.ext === 'gro'
  59. },
  60. getDefaultBuilder: (ctx: PluginContext, data: StateBuilder.To<PluginStateObject.Data.String>, state: State) => {
  61. return Task.create('GRO default builder', async taskCtx => {
  62. const traj = createModelTree(data, 'gro');
  63. await state.updateTree(createStructureTree(ctx, traj, false)).runInContext(taskCtx)
  64. })
  65. }
  66. }
  67. //
  68. const DownloadStructurePdbIdSourceOptions = PD.Group({
  69. supportProps: PD.Optional(PD.Boolean(false)),
  70. asTrajectory: PD.Optional(PD.Boolean(false, { description: 'Load all entries into a single trajectory.' }))
  71. });
  72. export { DownloadStructure };
  73. type DownloadStructure = typeof DownloadStructure
  74. const DownloadStructure = StateAction.build({
  75. from: PluginStateObject.Root,
  76. display: { name: 'Download Structure', description: 'Load a structure from the provided source and create its default Assembly and visual.' },
  77. params: {
  78. source: PD.MappedStatic('bcif-static', {
  79. 'pdbe-updated': PD.Group({
  80. id: PD.Text('1cbs', { label: 'Id' }),
  81. options: DownloadStructurePdbIdSourceOptions
  82. }, { isFlat: true }),
  83. 'rcsb': PD.Group({
  84. id: PD.Text('1tqn', { label: 'Id' }),
  85. options: DownloadStructurePdbIdSourceOptions
  86. }, { isFlat: true }),
  87. 'bcif-static': PD.Group({
  88. id: PD.Text('1tqn', { label: 'Id' }),
  89. options: DownloadStructurePdbIdSourceOptions
  90. }, { isFlat: true }),
  91. 'url': PD.Group({
  92. url: PD.Text(''),
  93. format: PD.Select('cif', [['cif', 'CIF'], ['pdb', 'PDB']]),
  94. isBinary: PD.Boolean(false),
  95. options: PD.Group({
  96. supportProps: PD.Optional(PD.Boolean(false))
  97. })
  98. }, { isFlat: true })
  99. }, {
  100. options: [
  101. ['pdbe-updated', 'PDBe Updated'],
  102. ['rcsb', 'RCSB'],
  103. ['bcif-static', 'BinaryCIF (static PDBe Updated)'],
  104. ['url', 'URL']
  105. ]
  106. })
  107. }
  108. })(({ params, state }, ctx: PluginContext) => {
  109. const b = state.build();
  110. const src = params.source;
  111. let downloadParams: StateTransformer.Params<Download>[];
  112. let supportProps = false, asTrajectory = false;
  113. switch (src.name) {
  114. case 'url':
  115. downloadParams = [{ url: src.params.url, isBinary: src.params.isBinary }];
  116. supportProps = !!src.params.options.supportProps;
  117. break;
  118. case 'pdbe-updated':
  119. downloadParams = getDownloadParams(src.params.id, id => `https://www.ebi.ac.uk/pdbe/static/entry/${id.toLowerCase()}_updated.cif`, id => `PDBe: ${id}`, false);
  120. supportProps = !!src.params.options.supportProps;
  121. asTrajectory = !!src.params.options.asTrajectory;
  122. break;
  123. case 'rcsb':
  124. downloadParams = getDownloadParams(src.params.id, id => `https://files.rcsb.org/download/${id.toUpperCase()}.cif`, id => `RCSB: ${id}`, false);
  125. supportProps = !!src.params.options.supportProps;
  126. asTrajectory = !!src.params.options.asTrajectory;
  127. break;
  128. case 'bcif-static':
  129. downloadParams = getDownloadParams(src.params.id, id => `https://webchem.ncbr.muni.cz/ModelServer/static/bcif/${id.toLowerCase()}`, id => `BinaryCIF: ${id}`, true);
  130. supportProps = !!src.params.options.supportProps;
  131. asTrajectory = !!src.params.options.asTrajectory;
  132. break;
  133. default: throw new Error(`${(src as any).name} not supported.`);
  134. }
  135. if (downloadParams.length > 0 && asTrajectory) {
  136. const traj = createSingleTrajectoryModel(downloadParams, b);
  137. createStructureTree(ctx, traj, supportProps);
  138. } else {
  139. for (const download of downloadParams) {
  140. const data = b.toRoot().apply(StateTransforms.Data.Download, download, { state: { isGhost: true } });
  141. const traj = createModelTree(data, src.name === 'url' ? src.params.format : 'cif');
  142. createStructureTree(ctx, traj, supportProps)
  143. }
  144. }
  145. return state.updateTree(b);
  146. });
  147. function getDownloadParams(src: string, url: (id: string) => string, label: (id: string) => string, isBinary: boolean): StateTransformer.Params<Download>[] {
  148. const ids = src.split(',').map(id => id.trim()).filter(id => !!id && id.length >= 4);
  149. const ret: StateTransformer.Params<Download>[] = [];
  150. for (const id of ids) {
  151. ret.push({ url: url(id), isBinary, label: label(id) })
  152. }
  153. return ret;
  154. }
  155. function createSingleTrajectoryModel(sources: StateTransformer.Params<Download>[], b: StateBuilder.Root) {
  156. return b.toRoot()
  157. .apply(StateTransforms.Data.DownloadBlob, {
  158. sources: sources.map((src, i) => ({ id: '' + i, url: src.url, isBinary: src.isBinary })),
  159. maxConcurrency: 6
  160. }).apply(StateTransforms.Data.ParseBlob, {
  161. formats: sources.map((_, i) => ({ id: '' + i, format: 'cif' as 'cif' }))
  162. })
  163. .apply(StateTransforms.Model.TrajectoryFromBlob)
  164. .apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 });
  165. }
  166. export function createModelTree(b: StateBuilder.To<PluginStateObject.Data.Binary | PluginStateObject.Data.String>, format: 'pdb' | 'cif' | 'gro' = 'cif') {
  167. let parsed: StateBuilder.To<PluginStateObject.Molecule.Trajectory>
  168. switch (format) {
  169. case 'cif':
  170. parsed = b.apply(StateTransforms.Data.ParseCif, void 0, { state: { isGhost: true } })
  171. .apply(StateTransforms.Model.TrajectoryFromMmCif, void 0, { state: { isGhost: true } })
  172. break
  173. case 'pdb':
  174. parsed = b.apply(StateTransforms.Model.TrajectoryFromPDB, void 0, { state: { isGhost: true } });
  175. break
  176. case 'gro':
  177. parsed = b.apply(StateTransforms.Model.TrajectoryFromGRO, void 0, { state: { isGhost: true } });
  178. break
  179. default:
  180. throw new Error('unsupported format')
  181. }
  182. return parsed.apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 });
  183. }
  184. function createStructureTree(ctx: PluginContext, b: StateBuilder.To<PluginStateObject.Molecule.Model>, supportProps: boolean) {
  185. let root = b;
  186. if (supportProps) {
  187. root = root.apply(StateTransforms.Model.CustomModelProperties);
  188. }
  189. const structure = root.apply(StateTransforms.Model.StructureAssemblyFromModel);
  190. complexRepresentation(ctx, structure);
  191. return root;
  192. }
  193. export function complexRepresentation(
  194. ctx: PluginContext, root: StateBuilder.To<PluginStateObject.Molecule.Structure>,
  195. params?: { hideSequence?: boolean, hideHET?: boolean, hideWater?: boolean, hideCoarse?: boolean; }
  196. ) {
  197. if (!params || !params.hideSequence) {
  198. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-sequence' })
  199. .apply(StateTransforms.Representation.StructureRepresentation3D,
  200. StructureRepresentation3DHelpers.getDefaultParamsStatic(ctx, 'cartoon'));
  201. }
  202. if (!params || !params.hideHET) {
  203. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-het' })
  204. .apply(StateTransforms.Representation.StructureRepresentation3D,
  205. StructureRepresentation3DHelpers.getDefaultParamsStatic(ctx, 'ball-and-stick'));
  206. }
  207. if (!params || !params.hideWater) {
  208. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'water' })
  209. .apply(StateTransforms.Representation.StructureRepresentation3D,
  210. StructureRepresentation3DHelpers.getDefaultParamsStatic(ctx, 'ball-and-stick', { alpha: 0.51 }));
  211. }
  212. if (!params || !params.hideCoarse) {
  213. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'spheres' })
  214. .apply(StateTransforms.Representation.StructureRepresentation3D,
  215. StructureRepresentation3DHelpers.getDefaultParamsStatic(ctx, 'spacefill'));
  216. }
  217. }
  218. export const CreateComplexRepresentation = StateAction.build({
  219. display: { name: 'Create Complex', description: 'Split the structure into Sequence/Water/Ligands/... ' },
  220. from: PluginStateObject.Molecule.Structure
  221. })(({ ref, state }, ctx: PluginContext) => {
  222. const root = state.build().to(ref);
  223. complexRepresentation(ctx, root);
  224. return state.updateTree(root);
  225. });
  226. export const UpdateTrajectory = StateAction.build({
  227. display: { name: 'Update Trajectory' },
  228. params: {
  229. action: PD.Select<'advance' | 'reset'>('advance', [['advance', 'Advance'], ['reset', 'Reset']]),
  230. by: PD.Optional(PD.Numeric(1, { min: -1, max: 1, step: 1 }))
  231. }
  232. })(({ params, state }) => {
  233. const models = state.selectQ(q => q.ofTransformer(StateTransforms.Model.ModelFromTrajectory));
  234. const update = state.build();
  235. if (params.action === 'reset') {
  236. for (const m of models) {
  237. update.to(m).update({ modelIndex: 0 });
  238. }
  239. } else {
  240. for (const m of models) {
  241. const parent = StateSelection.findAncestorOfType(state.tree, state.cells, m.transform.ref, [PluginStateObject.Molecule.Trajectory]);
  242. if (!parent || !parent.obj) continue;
  243. const traj = parent.obj;
  244. update.to(m).update(old => {
  245. let modelIndex = (old.modelIndex + params.by!) % traj.data.length;
  246. if (modelIndex < 0) modelIndex += traj.data.length;
  247. return { modelIndex };
  248. });
  249. }
  250. }
  251. return state.updateTree(update);
  252. });
  253. export const EnableModelCustomProps = StateAction.build({
  254. display: { name: 'Custom Properties', description: 'Enable the addition of custom properties to the model.' },
  255. from: PluginStateObject.Molecule.Model,
  256. params(a, ctx: PluginContext) {
  257. if (!a) return { properties: PD.MultiSelect([], [], { description: 'A list of property descriptor ids.' }) };
  258. return { properties: ctx.customModelProperties.getSelect(a.data) };
  259. },
  260. isApplicable(a, t, ctx: PluginContext) {
  261. return t.transformer !== CustomModelProperties;
  262. }
  263. })(({ ref, params, state }, ctx: PluginContext) => {
  264. const root = state.build().to(ref).insert(CustomModelProperties, params);
  265. return state.updateTree(root);
  266. });
  267. export const TransformStructureConformation = StateAction.build({
  268. display: { name: 'Transform Conformation' },
  269. from: PluginStateObject.Molecule.Structure,
  270. params: StateTransforms.Model.TransformStructureConformation.definition.params,
  271. })(({ ref, params, state }) => {
  272. const root = state.build().to(ref).insert(StateTransforms.Model.TransformStructureConformation, params as any);
  273. return state.updateTree(root);
  274. });
  275. export const StructureFromSelection = StateAction.build({
  276. display: { name: 'Selection Structure', description: 'Create a new Structure from the current selection.' },
  277. from: PluginStateObject.Molecule.Structure,
  278. params: {
  279. label: PD.Text()
  280. }
  281. // isApplicable(a, t, ctx: PluginContext) {
  282. // return t.transformer !== CustomModelProperties;
  283. // }
  284. })(({ a, ref, params, state }, plugin: PluginContext) => {
  285. const sel = plugin.helpers.structureSelection.get(a.data);
  286. if (sel.kind === 'empty-loci') return Task.constant('', void 0);
  287. const query = StructureElement.Loci.toScriptExpression(sel);
  288. const root = state.build().to(ref).apply(StructureSelection, { query, label: params.label });
  289. return state.updateTree(root);
  290. });