preset.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { PluginContext } from 'molstar/lib/mol-plugin/context';
  7. import { ParamDefinition as PD } from 'molstar/lib/mol-util/param-definition';
  8. import { TrajectoryHierarchyPresetProvider } from 'molstar/lib/mol-plugin-state/builder/structure/hierarchy-preset';
  9. import { ValidationReportGeometryQualityPreset } from 'molstar/lib/extensions/rcsb/validation-report/behavior';
  10. import { AssemblySymmetryPreset } from 'molstar/lib/extensions/rcsb/assembly-symmetry/behavior';
  11. import { PluginStateObject } from 'molstar/lib/mol-plugin-state/objects';
  12. import { RootStructureDefinition } from 'molstar/lib/mol-plugin-state/helpers/root-structure';
  13. import { StructureRepresentationPresetProvider } from 'molstar/lib/mol-plugin-state/builder/structure/representation-preset';
  14. import { StructureElement } from 'molstar/lib/mol-model/structure';
  15. import { ViewerState } from '../types';
  16. import {
  17. StateSelection,
  18. StateObjectSelector,
  19. StateObject,
  20. StateTransformer
  21. } from 'molstar/lib/mol-state';
  22. import { Mat4 } from 'molstar/lib/mol-math/linear-algebra';
  23. import { CustomStructureProperties } from 'molstar/lib/mol-plugin-state/transforms/model';
  24. import { FlexibleStructureFromModel } from './superpose/flexible-structure';
  25. import { PluginCommands } from 'molstar/lib/mol-plugin/commands';
  26. import { InteractivityManager } from 'molstar/lib/mol-plugin-state/manager/interactivity';
  27. import { MembraneOrientationPreset } from 'molstar/lib/extensions/anvil/behavior';
  28. import { setSubtreeVisibility } from 'molstar/lib/mol-plugin/behavior/static/state';
  29. import { VolumeStreaming } from 'molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/behavior';
  30. import {
  31. InitVolumeStreaming,
  32. VolumeStreamingVisual
  33. } from 'molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/transformers';
  34. import {
  35. createSelectionExpressions,
  36. normalizeTargets,
  37. SelectionExpression,
  38. Target,
  39. targetToLoci,
  40. toRange
  41. } from './selection';
  42. import { RcsbSuperpositionRepresentationPreset } from './superpose/preset';
  43. import {
  44. AssemblySymmetryDataProvider,
  45. AssemblySymmetryProvider
  46. } from 'molstar/lib/extensions/rcsb/assembly-symmetry/prop';
  47. import { Task } from 'molstar/lib/mol-task';
  48. type BaseProps = {
  49. assemblyId?: string
  50. modelIndex?: number
  51. }
  52. type ColorProp = {
  53. name: 'color',
  54. value: number,
  55. targets: Target[]
  56. };
  57. export type PropsetProps = {
  58. kind: 'prop-set',
  59. targets?: (Target & {
  60. matrix?: Mat4
  61. })[],
  62. representation: ColorProp[]
  63. } & BaseProps
  64. export type EmptyProps = {
  65. kind: 'empty'
  66. } & BaseProps
  67. type ValidationProps = {
  68. kind: 'validation'
  69. colorTheme?: string
  70. showClashes?: boolean
  71. } & BaseProps
  72. type StandardProps = {
  73. kind: 'standard'
  74. } & BaseProps
  75. type SymmetryProps = {
  76. kind: 'symmetry'
  77. symmetryIndex?: number
  78. } & BaseProps
  79. type FeatureProps = {
  80. kind: 'feature'
  81. target: Target
  82. } & BaseProps
  83. type DensityProps = {
  84. kind: 'density'
  85. } & BaseProps
  86. type MembraneProps = {
  87. kind: 'membrane',
  88. } & BaseProps
  89. type FeatureDensityProps = {
  90. kind: 'feature-density',
  91. target: Target,
  92. radius?: number,
  93. hiddenChannels?: string[]
  94. } & BaseProps
  95. export type MotifProps = {
  96. kind: 'motif',
  97. label?: string,
  98. targets: Target[],
  99. color?: number
  100. } & BaseProps
  101. export type PresetProps = ValidationProps | StandardProps | SymmetryProps | FeatureProps | DensityProps | PropsetProps |
  102. MembraneProps | FeatureDensityProps | MotifProps | EmptyProps;
  103. const RcsbParams = () => ({
  104. preset: PD.Value<PresetProps>({ kind: 'standard', assemblyId: '' }, { isHidden: true })
  105. });
  106. type StructureObject = StateObjectSelector<PluginStateObject.Molecule.Structure, StateTransformer<StateObject<any, StateObject.Type<any>>, StateObject<any, StateObject.Type<any>>, any>>
  107. const CommonParams = StructureRepresentationPresetProvider.CommonParams;
  108. export const RcsbPreset = TrajectoryHierarchyPresetProvider({
  109. id: 'preset-trajectory-rcsb',
  110. display: { name: 'RCSB' },
  111. isApplicable: () => true,
  112. params: RcsbParams,
  113. async apply(trajectory, params, plugin) {
  114. const builder = plugin.builders.structure;
  115. const p = params.preset;
  116. const modelParams = { modelIndex: p.modelIndex || 0 };
  117. // jump through some hoops to determine the unknown assemblyId of query selections
  118. if (p.kind === 'motif') determineAssemblyId(trajectory, p);
  119. const structureParams: RootStructureDefinition.Params = { name: 'model', params: {} };
  120. if (p.assemblyId && p.assemblyId !== '' && p.assemblyId !== '0') {
  121. Object.assign(structureParams, {
  122. name: 'assembly',
  123. params: { id: p.assemblyId }
  124. } as RootStructureDefinition.Params);
  125. }
  126. const model = await builder.createModel(trajectory, modelParams);
  127. const modelProperties = await builder.insertModelProperties(model);
  128. let structure: StructureObject | undefined = undefined;
  129. let structureProperties: StructureObject | undefined = undefined;
  130. let unitcell: StateObjectSelector | undefined = undefined;
  131. // If flexible transformation is allowed, we may need to create a single structure component
  132. // from transformed substructures
  133. const allowsFlexTransform = p.kind === 'prop-set';
  134. if (!allowsFlexTransform) {
  135. structure = await builder.createStructure(modelProperties || model, structureParams);
  136. structureProperties = await builder.insertStructureProperties(structure);
  137. // hide unit cell when dealing with motifs
  138. if (p.kind !== 'motif') {
  139. unitcell = await builder.tryCreateUnitcell(modelProperties, undefined, { isHidden: true });
  140. }
  141. }
  142. let representation: StructureRepresentationPresetProvider.Result | undefined = undefined;
  143. if (p.kind === 'prop-set') {
  144. // This creates a single structure from selections/transformations as specified
  145. const _structure = plugin.state.data.build().to(modelProperties)
  146. .apply(FlexibleStructureFromModel, { targets: p.targets });
  147. structure = await _structure.commit();
  148. const _structureProperties = plugin.state.data.build().to(structure)
  149. .apply(CustomStructureProperties);
  150. structureProperties = await _structureProperties.commit();
  151. // adding coloring lookup scheme
  152. structure.data!.inheritedPropertyData.colors = Object.create(null);
  153. for (const repr of p.representation) {
  154. if (repr.name === 'color') {
  155. const colorValue = repr.value;
  156. const targets = repr.targets;
  157. for (const target of targets) {
  158. if (!target.labelAsymId) continue;
  159. if (!structure.data!.inheritedPropertyData.colors[target.labelAsymId])
  160. structure.data!.inheritedPropertyData.colors[target.labelAsymId] = new Map();
  161. const residues: number[] = (target.labelSeqRange) ? toRange(target.labelSeqRange.beg, target.labelSeqRange.end) : [];
  162. for (const num of residues) {
  163. structure.data!.inheritedPropertyData.colors[target.labelAsymId].set(num, colorValue);
  164. }
  165. }
  166. }
  167. }
  168. // At this we have a structure that contains only the transformed substructres,
  169. // creating structure selections to have multiple components per each flexible part
  170. const entryId = model.data!.entryId;
  171. let selectionExpressions: SelectionExpression[] = [];
  172. if (p.targets) {
  173. for (const target of p.targets) {
  174. selectionExpressions = selectionExpressions.concat(createSelectionExpressions(entryId, target));
  175. }
  176. } else {
  177. selectionExpressions = selectionExpressions.concat(createSelectionExpressions(entryId));
  178. }
  179. const params = {
  180. ignoreHydrogens: CommonParams.ignoreHydrogens.defaultValue,
  181. quality: CommonParams.quality.defaultValue,
  182. theme: { globalName: 'superpose', focus: { name: 'superpose' } },
  183. selectionExpressions: selectionExpressions
  184. };
  185. representation = await plugin.builders.structure.representation.applyPreset<any>(structureProperties!, RcsbSuperpositionRepresentationPreset, params);
  186. } else if (p.kind === 'motif' && structure?.obj) {
  187. // let's force ASM_1 for motifs (as we use this contract in the rest of the stack)
  188. // TODO should ASM_1 be the default, seems like we'd run into problems when selecting ligands that are e.g. ambiguous with asym_id & seq_id alone?
  189. const targets = normalizeTargets(p.targets, structure!.obj.data);
  190. let selectionExpressions = createSelectionExpressions(p.label || model.data!.entryId, targets);
  191. const globalExpressions = createSelectionExpressions(p.label || model.data!.entryId); // global reps, to be hidden
  192. selectionExpressions = selectionExpressions.concat(globalExpressions.map(e => { return { ...e, isHidden: true }; }));
  193. if (p.color) {
  194. selectionExpressions = selectionExpressions.map(e => { return { ...e, color: p.color }; });
  195. }
  196. const params = {
  197. ignoreHydrogens: true,
  198. quality: CommonParams.quality.defaultValue,
  199. selectionExpressions: selectionExpressions
  200. };
  201. representation = await plugin.builders.structure.representation.applyPreset<any>(structureProperties!, RcsbSuperpositionRepresentationPreset, params);
  202. } else if (p.kind === 'validation') {
  203. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, ValidationReportGeometryQualityPreset);
  204. } else if (p.kind === 'symmetry' && structure?.obj) {
  205. const data = structure!.obj.data;
  206. if (!AssemblySymmetryDataProvider.get(data).value) {
  207. await plugin.runTask(Task.create('Assembly Symmetry', async runtime => {
  208. const propCtx = { runtime, assetManager: plugin.managers.asset };
  209. await AssemblySymmetryDataProvider.attach(propCtx, data);
  210. await AssemblySymmetryProvider.attach(propCtx, data, { symmetryIndex: p.symmetryIndex });
  211. }));
  212. }
  213. representation = await plugin.builders.structure.representation.applyPreset<any>(structureProperties!, AssemblySymmetryPreset);
  214. ViewerState(plugin).collapsed.next({
  215. ...ViewerState(plugin).collapsed.value,
  216. custom: false
  217. });
  218. } else if (p.kind === 'empty') {
  219. console.warn('Using empty representation');
  220. } else if (p.kind === 'membrane') {
  221. try {
  222. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, MembraneOrientationPreset);
  223. // reset the camera because the membranes render 1st and the structure might not be fully visible
  224. requestAnimationFrame(() => plugin.canvas3d?.requestCameraReset());
  225. } catch (error) {
  226. const msg = 'Membrane calculation failed! - This can happen for tiny structures with only a dozen of residues.';
  227. plugin.log.error(msg);
  228. console.error(msg);
  229. console.error(error);
  230. // fall back to default representation to show something
  231. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, 'auto');
  232. }
  233. } else {
  234. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, 'auto');
  235. }
  236. if ((p.kind === 'feature' || p.kind === 'feature-density') && structure?.obj) {
  237. let loci = targetToLoci(p.target, structure!.obj.data);
  238. // if requested: then don't force first residue
  239. const chainMode = !!p.target.extendToChain;
  240. // HELP-16678: check for rare case where ligand is not present in requested assembly
  241. if (loci.elements.length === 0 && !!p.assemblyId) {
  242. // switch to Model (a.k.a. show coordinates independent of assembly)
  243. const { selection } = plugin.managers.structure.hierarchy;
  244. const s = selection.structures[0];
  245. await plugin.managers.structure.hierarchy.updateStructure(s, { ...params, preset: { ...params.preset, assemblyId: void 0 } });
  246. // update loci
  247. loci = targetToLoci(p.target, structure!.obj.data);
  248. }
  249. const target = chainMode ? loci : StructureElement.Loci.firstResidue(loci);
  250. if (p.kind === 'feature-density') {
  251. await initVolumeStreaming(plugin, structure, { overrideRadius: p.radius || 0, hiddenChannels: p.hiddenChannels || ['fo-fc(+ve)', 'fo-fc(-ve)'] });
  252. }
  253. plugin.managers.structure.focus.setFromLoci(target);
  254. plugin.managers.camera.focusLoci(target);
  255. }
  256. if (p.kind === 'density' && structure) {
  257. await initVolumeStreaming(plugin, structure);
  258. await PluginCommands.Toast.Show(plugin, {
  259. title: 'Electron Density',
  260. message: 'Click on a residue to display electron density, click background to reset.',
  261. key: 'toast-density',
  262. timeoutMs: 60000
  263. });
  264. plugin.behaviors.interaction.click.subscribe(async (e: InteractivityManager.ClickEvent) => {
  265. if (e.current && e.current.loci && e.current.loci.kind !== 'empty-loci') {
  266. await PluginCommands.Toast.Hide(plugin, { key: 'toast-density' });
  267. }
  268. });
  269. }
  270. return {
  271. model,
  272. modelProperties,
  273. unitcell,
  274. structure,
  275. structureProperties,
  276. representation
  277. };
  278. }
  279. });
  280. function determineAssemblyId(traj: any, p: MotifProps) {
  281. // nothing to do if assembly is known
  282. if (p.assemblyId && p.assemblyId !== '' && p.assemblyId !== '0') return;
  283. function equals(expr: string, val: string): boolean {
  284. const list = parseOperatorList(expr);
  285. const split = val.split('x');
  286. let matches = 0;
  287. for (let i = 0, il = Math.min(list.length, split.length); i < il; i++) {
  288. if (list[i].indexOf(split[i]) !== -1) matches++;
  289. }
  290. return matches === split.length;
  291. }
  292. function parseOperatorList(value: string): string[][] {
  293. // '(X0)(1-5)' becomes [['X0'], ['1', '2', '3', '4', '5']]
  294. // kudos to Glen van Ginkel.
  295. const oeRegex = /\(?([^()]+)\)?]*/g, groups: string[] = [], ret: string[][] = [];
  296. let g: any;
  297. while (g = oeRegex.exec(value)) groups[groups.length] = g[1];
  298. groups.forEach(g => {
  299. const group: string[] = [];
  300. g.split(',').forEach(e => {
  301. const dashIndex = e.indexOf('-');
  302. if (dashIndex > 0) {
  303. const from = parseInt(e.substring(0, dashIndex)), to = parseInt(e.substr(dashIndex + 1));
  304. for (let i = from; i <= to; i++) group[group.length] = i.toString();
  305. } else {
  306. group[group.length] = e.trim();
  307. }
  308. });
  309. ret[ret.length] = group;
  310. });
  311. return ret;
  312. }
  313. // set of provided [structOperId, labelAsymId] combinations
  314. const ids = p.targets.map(t => [t.structOperId || '1', t.labelAsymId!]).filter((x, i, a) => a.indexOf(x) === i);
  315. try {
  316. // find first assembly that contains all requested structOperIds - if multiple, the first will be returned
  317. const pdbx_struct_assembly_gen = traj.obj.data.representative.sourceData.data.frame.categories.pdbx_struct_assembly_gen;
  318. if (pdbx_struct_assembly_gen) {
  319. const assembly_id = pdbx_struct_assembly_gen.getField('assembly_id');
  320. const oper_expression = pdbx_struct_assembly_gen.getField('oper_expression');
  321. const asym_id_list = pdbx_struct_assembly_gen.getField('asym_id_list');
  322. for (let i = 0, il = pdbx_struct_assembly_gen.rowCount; i < il; i++) {
  323. if (ids.some(val => !equals(oper_expression.str(i), val[0]) || asym_id_list.str(i).indexOf(val[1]) === -1)) continue;
  324. Object.assign(p, { assemblyId: assembly_id.str(i) });
  325. return;
  326. }
  327. } else {
  328. // this happens e.g. for AlphaFold structures
  329. console.warn(`Source file is missing 'pdbx_struct_assembly_gen' category`);
  330. }
  331. } catch (error) {
  332. console.warn(error);
  333. }
  334. // default to '1' if error or legitimately not found
  335. console.warn(`Could not auto-detect assembly-of-interest. Falling back to '1'`);
  336. Object.assign(p, { assemblyId: '1' });
  337. }
  338. async function initVolumeStreaming(plugin: PluginContext, structure: StructureObject, props?: { overrideRadius?: number, hiddenChannels: string[] }) {
  339. if (!structure?.cell?.parent) return;
  340. const volumeRoot = StateSelection.findTagInSubtree(structure.cell.parent.tree, structure.cell.transform.ref, VolumeStreaming.RootTag);
  341. if (!volumeRoot) {
  342. const state = plugin.state.data;
  343. const params = PD.getDefaultValues(InitVolumeStreaming.definition.params!(structure.obj!, plugin));
  344. await plugin.runTask(state.applyAction(InitVolumeStreaming, params, structure.ref));
  345. // RO-2751: allow to specify radius of shown density
  346. if (props?.overrideRadius !== void 0) {
  347. const { params, transform } = state.select(StateSelection.Generators.ofType(VolumeStreaming))[0];
  348. const p = params?.values;
  349. (p.entry.params.view.params as any).radius = props.overrideRadius;
  350. await state.build().to(transform.ref).update(p).commit();
  351. }
  352. // RO-2751: hide all but 2Fo-Fc map
  353. if (props?.hiddenChannels?.length) {
  354. const cells = state.select(StateSelection.Generators.ofTransformer(VolumeStreamingVisual));
  355. for (const cell of cells) {
  356. if (props.hiddenChannels.indexOf(cell.obj!.tags![0]) !== -1) {
  357. setSubtreeVisibility(state, cell.transform.ref, true);
  358. }
  359. }
  360. }
  361. }
  362. ViewerState(plugin).collapsed.next({
  363. ...ViewerState(plugin).collapsed.value,
  364. volume: false
  365. });
  366. }