preset.ts 18 KB

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