preset.ts 19 KB

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