preset.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, MembraneOrientationPreset);
  209. } else {
  210. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, 'auto');
  211. }
  212. if ((p.kind === 'feature' || p.kind === 'feature-density') && structure?.obj) {
  213. let loci = targetToLoci(p.target, structure!.obj.data);
  214. // if target is only defined by chain: then don't force first residue
  215. const chainMode = p.target.labelAsymId && !p.target.authSeqId && !p.target.labelSeqId && !p.target.labelCompId;
  216. // HELP-16678: check for rare case where ligand is not present in requested assembly
  217. if (loci.elements.length === 0 && !!p.assemblyId) {
  218. // switch to Model (a.k.a. show coordinates independent of assembly)
  219. const { selection } = plugin.managers.structure.hierarchy;
  220. const s = selection.structures[0];
  221. await plugin.managers.structure.hierarchy.updateStructure(s, { ...params, preset: { ...params.preset, assemblyId: void 0 } });
  222. // update loci
  223. loci = targetToLoci(p.target, structure!.obj.data);
  224. }
  225. const target = chainMode ? loci : StructureElement.Loci.firstResidue(loci);
  226. if (p.kind === 'feature-density') {
  227. await initVolumeStreaming(plugin, structure, { overrideRadius: p.radius || 0, hiddenChannels: p.hiddenChannels || ['fo-fc(+ve)', 'fo-fc(-ve)'] });
  228. }
  229. plugin.managers.structure.focus.setFromLoci(target);
  230. plugin.managers.camera.focusLoci(target);
  231. }
  232. if (p.kind === 'density' && structure) {
  233. await initVolumeStreaming(plugin, structure);
  234. await PluginCommands.Toast.Show(plugin, {
  235. title: 'Electron Density',
  236. message: 'Click on a residue to display electron density, click background to reset.',
  237. key: 'toast-density',
  238. timeoutMs: 60000
  239. });
  240. plugin.behaviors.interaction.click.subscribe(async (e: InteractivityManager.ClickEvent) => {
  241. if (e.current && e.current.loci && e.current.loci.kind !== 'empty-loci') {
  242. await PluginCommands.Toast.Hide(plugin, { key: 'toast-density' });
  243. }
  244. });
  245. }
  246. return {
  247. model,
  248. modelProperties,
  249. unitcell,
  250. structure,
  251. structureProperties,
  252. representation
  253. };
  254. }
  255. });
  256. function determineAssemblyId(traj: any, p: MotifProps) {
  257. // nothing to do if assembly is known
  258. if (p.assemblyId && p.assemblyId !== '' && p.assemblyId !== '0') return;
  259. function equals(expr: string, val: string): boolean {
  260. const list = parseOperatorList(expr);
  261. const split = val.split('x');
  262. let matches = 0;
  263. for (let i = 0, il = Math.min(list.length, split.length); i < il; i++) {
  264. if (list[i].indexOf(split[i]) !== -1) matches++;
  265. }
  266. return matches === split.length;
  267. }
  268. function parseOperatorList(value: string): string[][] {
  269. // '(X0)(1-5)' becomes [['X0'], ['1', '2', '3', '4', '5']]
  270. // kudos to Glen van Ginkel.
  271. const oeRegex = /\(?([^()]+)\)?]*/g, groups: string[] = [], ret: string[][] = [];
  272. let g: any;
  273. while (g = oeRegex.exec(value)) groups[groups.length] = g[1];
  274. groups.forEach(g => {
  275. const group: string[] = [];
  276. g.split(',').forEach(e => {
  277. const dashIndex = e.indexOf('-');
  278. if (dashIndex > 0) {
  279. const from = parseInt(e.substring(0, dashIndex)), to = parseInt(e.substr(dashIndex + 1));
  280. for (let i = from; i <= to; i++) group[group.length] = i.toString();
  281. } else {
  282. group[group.length] = e.trim();
  283. }
  284. });
  285. ret[ret.length] = group;
  286. });
  287. return ret;
  288. }
  289. // set of provided [struct_oper_id, label_asym_id] combinations
  290. const ids = p.targets.map(t => [t.structOperId || '1', t.labelAsymId!]).filter((x, i, a) => a.indexOf(x) === i);
  291. try {
  292. // find first assembly that contains all requested struct_oper_ids - if multiple, the first will be returned
  293. const pdbx_struct_assembly_gen = traj.obj.data.representative.sourceData.data.frame.categories.pdbx_struct_assembly_gen;
  294. const assembly_id = pdbx_struct_assembly_gen.getField('assembly_id');
  295. const oper_expression = pdbx_struct_assembly_gen.getField('oper_expression');
  296. const asym_id_list = pdbx_struct_assembly_gen.getField('asym_id_list');
  297. for (let i = 0, il = pdbx_struct_assembly_gen.rowCount; i < il; i++) {
  298. if (ids.some(val => !equals(oper_expression.str(i), val[0]) || asym_id_list.str(i).indexOf(val[1]) === -1)) continue;
  299. Object.assign(p, { assemblyId: assembly_id.str(i) });
  300. return;
  301. }
  302. } catch (error) {
  303. console.warn(error);
  304. }
  305. // default to '1' if error or legitimately not found
  306. Object.assign(p, { assemblyId: '1' });
  307. }
  308. async function initVolumeStreaming(plugin: PluginContext, structure: StructureObject, props?: { overrideRadius?: number, hiddenChannels: string[] }) {
  309. if (!structure?.cell?.parent) return;
  310. const volumeRoot = StateSelection.findTagInSubtree(structure.cell.parent.tree, structure.cell.transform.ref, VolumeStreaming.RootTag);
  311. if (!volumeRoot) {
  312. const state = plugin.state.data;
  313. const params = PD.getDefaultValues(InitVolumeStreaming.definition.params!(structure.obj!, plugin));
  314. await plugin.runTask(state.applyAction(InitVolumeStreaming, params, structure.ref));
  315. // RO-2751: allow to specify radius of shown density
  316. if (props?.overrideRadius !== void 0) {
  317. const { params, transform } = state.select(StateSelection.Generators.ofType(VolumeStreaming))[0];
  318. const p = params?.values;
  319. (p.entry.params.view.params as any).radius = props.overrideRadius;
  320. await state.build().to(transform.ref).update(p).commit();
  321. }
  322. // RO-2751: hide all but 2Fo-Fc map
  323. if (props?.hiddenChannels?.length) {
  324. const cells = state.select(StateSelection.Generators.ofTransformer(VolumeStreamingVisual));
  325. for (const cell of cells) {
  326. if (props.hiddenChannels.indexOf(cell.obj!.tags![0]) !== -1) {
  327. setSubtreeVisibility(state, cell.transform.ref, true);
  328. }
  329. }
  330. }
  331. }
  332. ViewerState(plugin).collapsed.next({
  333. ...ViewerState(plugin).collapsed.value,
  334. volume: false
  335. });
  336. }