preset.ts 20 KB

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