preset.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 { MolScriptBuilder as MS } from 'molstar/lib/mol-script/language/builder';
  8. import { Expression } from 'molstar/lib/mol-script/language/expression';
  9. import { ParamDefinition as PD } from 'molstar/lib/mol-util/param-definition';
  10. import { TrajectoryHierarchyPresetProvider } from 'molstar/lib/mol-plugin-state/builder/structure/hierarchy-preset';
  11. import { ValidationReportGeometryQualityPreset } from 'molstar/lib/extensions/rcsb/validation-report/behavior';
  12. import { AssemblySymmetryPreset } from 'molstar/lib/extensions/rcsb/assembly-symmetry/behavior';
  13. import { PluginStateObject } from 'molstar/lib/mol-plugin-state/objects';
  14. import { RootStructureDefinition } from 'molstar/lib/mol-plugin-state/helpers/root-structure';
  15. import { StructureRepresentationPresetProvider } from 'molstar/lib/mol-plugin-state/builder/structure/representation-preset';
  16. import {
  17. Structure,
  18. StructureSelection,
  19. QueryContext,
  20. StructureElement
  21. } from 'molstar/lib/mol-model/structure';
  22. import { compile } from 'molstar/lib/mol-script/runtime/query/compiler';
  23. import { InitVolumeStreaming } from 'molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/transformers';
  24. import { ViewerState } from '../types';
  25. import {
  26. StateSelection,
  27. StateObjectSelector,
  28. StateObject,
  29. StateTransformer,
  30. StateObjectRef
  31. } from 'molstar/lib/mol-state';
  32. import { VolumeStreaming } from 'molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/behavior';
  33. import { Mat4 } from 'molstar/lib/mol-math/linear-algebra';
  34. import { CustomStructureProperties } from 'molstar/lib/mol-plugin-state/transforms/model';
  35. import { FlexibleStructureFromModel as FlexibleStructureFromModel } from './superpose/flexible-structure';
  36. import { StructureRepresentationRegistry } from 'molstar/lib/mol-repr/structure/registry';
  37. import { StructureSelectionQueries as Q } from 'molstar/lib/mol-plugin-state/helpers/structure-selection-query';
  38. import { PluginCommands } from 'molstar/lib/mol-plugin/commands';
  39. import { InteractivityManager } from 'molstar/lib/mol-plugin-state/manager/interactivity';
  40. import { MembraneOrientationPreset } from 'molstar/lib/extensions/anvil/behavior';
  41. type Target = {
  42. readonly auth_seq_id?: number
  43. readonly label_seq_id?: number
  44. readonly label_comp_id?: string
  45. readonly label_asym_id?: string
  46. }
  47. function targetToExpression(target: Target): Expression {
  48. const residueTests: Expression[] = [];
  49. const tests = Object.create(null);
  50. if (target.auth_seq_id) {
  51. residueTests.push(MS.core.rel.eq([target.auth_seq_id, MS.ammp('auth_seq_id')]));
  52. } else if (target.label_seq_id) {
  53. residueTests.push(MS.core.rel.eq([target.label_seq_id, MS.ammp('label_seq_id')]));
  54. }
  55. if (target.label_comp_id) {
  56. residueTests.push(MS.core.rel.eq([target.label_comp_id, MS.ammp('label_comp_id')]));
  57. }
  58. if (residueTests.length === 1) {
  59. tests['residue-test'] = residueTests[0];
  60. } else if (residueTests.length > 1) {
  61. tests['residue-test'] = MS.core.logic.and(residueTests);
  62. }
  63. if (target.label_asym_id) {
  64. tests['chain-test'] = MS.core.rel.eq([target.label_asym_id, MS.ammp('label_asym_id')]);
  65. }
  66. if (Object.keys(tests).length > 0) {
  67. return MS.struct.modifier.union([
  68. MS.struct.generator.atomGroups(tests)
  69. ]);
  70. } else {
  71. return MS.struct.generator.empty;
  72. }
  73. }
  74. function targetToLoci(target: Target, structure: Structure): StructureElement.Loci {
  75. const expression = targetToExpression(target);
  76. const query = compile<StructureSelection>(expression);
  77. const selection = query(new QueryContext(structure));
  78. return StructureSelection.toLociWithSourceUnits(selection);
  79. }
  80. type Range = {
  81. label_asym_id: string
  82. label_seq_id?: { beg: number, end?: number }
  83. }
  84. type BaseProps = {
  85. assemblyId?: string
  86. modelIndex?: number
  87. }
  88. type ColorProp = {
  89. name: 'color',
  90. value: number,
  91. positions: Range[]
  92. };
  93. export type PropsetProps = {
  94. kind: 'prop-set',
  95. selection?: (Range & {
  96. matrix?: Mat4
  97. })[],
  98. representation: ColorProp[]
  99. } & BaseProps
  100. export type EmptyProps = {
  101. kind: 'empty'
  102. } & BaseProps
  103. type ValidationProps = {
  104. kind: 'validation'
  105. colorTheme?: string
  106. showClashes?: boolean
  107. } & BaseProps
  108. type StandardProps = {
  109. kind: 'standard'
  110. } & BaseProps
  111. type SymmetryProps = {
  112. kind: 'symmetry'
  113. symmetryIndex?: number
  114. } & BaseProps
  115. type FeatureProps = {
  116. kind: 'feature'
  117. target: Target
  118. } & BaseProps
  119. type DensityProps = {
  120. kind: 'density'
  121. } & BaseProps
  122. type MembraneProps = {
  123. kind: 'membrane',
  124. } & BaseProps
  125. type FeatureDensityProps = {
  126. kind: 'feature-density',
  127. target: Target
  128. } & BaseProps
  129. export type PresetProps = ValidationProps | StandardProps | SymmetryProps | FeatureProps | DensityProps | PropsetProps | MembraneProps | FeatureDensityProps | EmptyProps;
  130. const RcsbParams = (a: PluginStateObject.Molecule.Trajectory | undefined, plugin: PluginContext) => ({
  131. preset: PD.Value<PresetProps>({ kind: 'standard', assemblyId: '' }, { isHidden: true })
  132. });
  133. type StructureObject = StateObjectSelector<PluginStateObject.Molecule.Structure, StateTransformer<StateObject<any, StateObject.Type<any>>, StateObject<any, StateObject.Type<any>>, any>>
  134. const CommonParams = StructureRepresentationPresetProvider.CommonParams;
  135. const reprBuilder = StructureRepresentationPresetProvider.reprBuilder;
  136. const updateFocusRepr = StructureRepresentationPresetProvider.updateFocusRepr;
  137. type SelectionExpression = {
  138. tag: string
  139. type: StructureRepresentationRegistry.BuiltIn
  140. label: string
  141. expression: Expression
  142. };
  143. export const RcsbSuperpositionRepresentationPreset = StructureRepresentationPresetProvider({
  144. id: 'preset-superposition-representation-rcsb',
  145. display: {
  146. group: 'Superposition',
  147. name: 'Alignment',
  148. description: 'Show representations based on the structural alignment data.'
  149. },
  150. params: () => ({
  151. ...CommonParams,
  152. selectionExpressions: PD.Value<SelectionExpression[]>([])
  153. }),
  154. async apply(ref, params, plugin) {
  155. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  156. if (!structureCell) return Object.create(null);
  157. const structure = structureCell.obj!.data;
  158. const cartoonProps = {sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2};
  159. let components = Object.create(null);
  160. let representations = Object.create(null);
  161. for (const expr of params.selectionExpressions) {
  162. const comp = await plugin.builders.structure.tryCreateComponentFromExpression(structureCell, expr.expression, expr.label, { label: expr.label });
  163. Object.assign(components, {[expr.label]: comp});
  164. const { update, builder, typeParams, color } = reprBuilder(plugin, params);
  165. let typeProps = {...typeParams};
  166. if (expr.type === 'cartoon') {
  167. Object.assign(typeProps, {...cartoonProps});
  168. }
  169. Object.assign(representations, {
  170. [expr.label]: builder.buildRepresentation(update, comp, {type: expr.type,
  171. typeParams: typeProps, color: color as any}, { tag: expr.tag }),
  172. });
  173. await update.commit({ revertOnError: false });
  174. }
  175. // needed to apply same coloring scheme to focus representation
  176. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  177. return representations;
  178. }
  179. });
  180. export const RcsbPreset = TrajectoryHierarchyPresetProvider({
  181. id: 'preset-trajectory-rcsb',
  182. display: { name: 'RCSB' },
  183. isApplicable: o => {
  184. return true;
  185. },
  186. params: RcsbParams,
  187. async apply(trajectory, params, plugin) {
  188. const builder = plugin.builders.structure;
  189. const p = params.preset;
  190. const modelParams = { modelIndex: p.modelIndex || 0 };
  191. const structureParams: RootStructureDefinition.Params = { name: 'model', params: {} };
  192. if (p.assemblyId && p.assemblyId !== '' && p.assemblyId !== '0') {
  193. Object.assign(structureParams, {
  194. name: 'assembly',
  195. params: { id: p.assemblyId }
  196. } as RootStructureDefinition.Params);
  197. }
  198. const model = await builder.createModel(trajectory, modelParams);
  199. const modelProperties = await builder.insertModelProperties(model);
  200. let structure: StructureObject | undefined = undefined;
  201. let structureProperties: StructureObject | undefined = undefined;
  202. let unitcell: StateObjectSelector | undefined = undefined;
  203. // If flexible transformation is allowed, we may need to create a single structure component
  204. // from transformed substructures
  205. const allowsFlexTransform = p.kind === 'prop-set';
  206. if (!allowsFlexTransform) {
  207. structure = await builder.createStructure(modelProperties || model, structureParams);
  208. structureProperties = await builder.insertStructureProperties(structure);
  209. unitcell = await builder.tryCreateUnitcell(modelProperties, undefined, { isHidden: true });
  210. }
  211. let representation: StructureRepresentationPresetProvider.Result | undefined = undefined;
  212. if (p.kind === 'prop-set') {
  213. // This creates a single structure from selections/transformations as specified
  214. const _structure = plugin.state.data.build().to(modelProperties)
  215. .apply(FlexibleStructureFromModel, { selection: p.selection });
  216. structure = await _structure.commit();
  217. const _structureProperties = plugin.state.data.build().to(structure)
  218. .apply(CustomStructureProperties);
  219. structureProperties = await _structureProperties.commit();
  220. // adding coloring lookup scheme
  221. structure.data!.inheritedPropertyData.colors = Object.create(null);
  222. for (const repr of p.representation) {
  223. if (repr.name === 'color') {
  224. const colorValue = repr.value;
  225. const positions = repr.positions;
  226. for (const range of positions) {
  227. if (!structure.data!.inheritedPropertyData.colors[range.label_asym_id])
  228. structure.data!.inheritedPropertyData.colors[range.label_asym_id] = new Map();
  229. const residues: number[] = (range.label_seq_id) ? toRange(range.label_seq_id.beg, range.label_seq_id.end) : [];
  230. for (const num of residues) {
  231. structure.data!.inheritedPropertyData.colors[range.label_asym_id].set(num, colorValue);
  232. }
  233. }
  234. }
  235. }
  236. // At this we have a structure that contains only the transformed substructres,
  237. // creating structure selections to have multiple components per each flexible part
  238. const entryId = model.data!.entryId;
  239. let selectionExpressions: SelectionExpression[] = [];
  240. if (p.selection) {
  241. for (const range of p.selection) {
  242. selectionExpressions = selectionExpressions.concat(createSelectionExpression(entryId, range));
  243. }
  244. } else {
  245. selectionExpressions = selectionExpressions.concat(createSelectionExpression(entryId));
  246. }
  247. const params = {
  248. ignoreHydrogens: CommonParams.ignoreHydrogens.defaultValue,
  249. quality: CommonParams.quality.defaultValue,
  250. theme: { globalName: 'superpose' as any, focus: { name: 'superpose' } },
  251. selectionExpressions: selectionExpressions
  252. };
  253. representation = await RcsbSuperpositionRepresentationPreset.apply(structure, params, plugin);
  254. } else if (p.kind === 'validation') {
  255. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, ValidationReportGeometryQualityPreset);
  256. } else if (p.kind === 'symmetry') {
  257. representation = await plugin.builders.structure.representation.applyPreset<any>(structureProperties!, AssemblySymmetryPreset, { symmetryIndex: p.symmetryIndex });
  258. ViewerState(plugin).collapsed.next({
  259. ...ViewerState(plugin).collapsed.value,
  260. custom: false
  261. });
  262. } else if (p.kind === 'empty') {
  263. console.warn('Using empty representation');
  264. } else if (p.kind === 'membrane') {
  265. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, MembraneOrientationPreset);
  266. } else {
  267. representation = await plugin.builders.structure.representation.applyPreset(structureProperties!, 'auto');
  268. }
  269. if ((p.kind === 'feature' || p.kind === 'feature-density') && structure?.obj) {
  270. let loci = targetToLoci(p.target, structure.obj.data);
  271. // if target is only defined by chain: then don't force first residue
  272. const chainMode = p.target.label_asym_id && !p.target.auth_seq_id && !p.target.label_seq_id && !p.target.label_comp_id;
  273. // HELP-16678: check for rare case where ligand is not present in requested assembly
  274. if (loci.elements.length === 0 && !!p.assemblyId) {
  275. // switch to Model (a.k.a. show coordinate independent of assembly )
  276. const { selection } = plugin.managers.structure.hierarchy;
  277. const s = selection.structures[0];
  278. await plugin.managers.structure.hierarchy.updateStructure(s, { ...params, preset: { ...params.preset, assemblyId: void 0 } });
  279. // update loci
  280. loci = targetToLoci(p.target, structure.obj.data);
  281. }
  282. const target = chainMode ? loci : StructureElement.Loci.firstResidue(loci);
  283. if (p.kind === 'feature-density') {
  284. await initVolumeStreaming(plugin, structure, 0);
  285. }
  286. plugin.managers.structure.focus.setFromLoci(target);
  287. plugin.managers.camera.focusLoci(target);
  288. }
  289. if (p.kind === 'density' && structure) {
  290. await initVolumeStreaming(plugin, structure);
  291. await PluginCommands.Toast.Show(plugin, {
  292. title: 'Electron Density',
  293. message: 'Click on a residue to display electron density, click background to reset.',
  294. key: 'toast-density',
  295. timeoutMs: 60000
  296. });
  297. plugin.behaviors.interaction.click.subscribe(async (e: InteractivityManager.ClickEvent) => {
  298. if (e.current && e.current.loci && e.current.loci.kind !== 'empty-loci') {
  299. await PluginCommands.Toast.Hide(plugin, { key: 'toast-density' });
  300. }
  301. });
  302. }
  303. return {
  304. model,
  305. modelProperties,
  306. unitcell,
  307. structure,
  308. structureProperties,
  309. representation
  310. };
  311. }
  312. });
  313. async function initVolumeStreaming(plugin: PluginContext, structure: StructureObject, overrideRadius?: number) {
  314. if (!structure?.cell?.parent) return;
  315. const volumeRoot = StateSelection.findTagInSubtree(structure.cell.parent.tree, structure.cell.transform.ref, VolumeStreaming.RootTag);
  316. if (!volumeRoot) {
  317. const state = plugin.state.data;
  318. const params = PD.getDefaultValues(InitVolumeStreaming.definition.params!(structure.obj!, plugin));
  319. await plugin.runTask(state.applyAction(InitVolumeStreaming, params, structure.ref));
  320. // RO-2751: allow to specify radius of shown density
  321. if (overrideRadius !== void 0) {
  322. const { params, transform } = state.select(StateSelection.Generators.ofType(VolumeStreaming))[0];
  323. const p = params?.values;
  324. (p.entry.params.view.params as any).radius = overrideRadius;
  325. const tree = state.build().to(transform.ref).update(p);
  326. await PluginCommands.State.Update(plugin, { state, tree });
  327. }
  328. }
  329. ViewerState(plugin).collapsed.next({
  330. ...ViewerState(plugin).collapsed.value,
  331. volume: false
  332. });
  333. }
  334. export function createSelectionExpression(entryId: string, range?: Range): SelectionExpression[] {
  335. if (range) {
  336. const residues: number[] = (range.label_seq_id) ? toRange(range.label_seq_id.beg, range.label_seq_id.end) : [];
  337. const test = selectionTest(range.label_asym_id, residues);
  338. const label = labelFromProps(entryId, range);
  339. return [{
  340. expression: MS.struct.generator.atomGroups(test),
  341. label: `${label}`,
  342. type: 'cartoon',
  343. tag: 'polymer'
  344. }];
  345. } else {
  346. return [
  347. {
  348. expression: Q.polymer.expression,
  349. label: `${entryId} - Polymers`,
  350. type: 'cartoon',
  351. tag: 'polymer'
  352. },
  353. {
  354. expression: Q.ligand.expression,
  355. label: `${entryId} - Ligands`,
  356. type: 'ball-and-stick',
  357. tag: 'ligand'
  358. },
  359. {
  360. expression: Q.ion.expression,
  361. label: `${entryId} - Ions`,
  362. type: 'ball-and-stick',
  363. tag: 'ion'
  364. },
  365. {
  366. expression: Q.branched.expression,
  367. label: `${entryId} - Carbohydrates`,
  368. type: 'carbohydrate',
  369. tag: 'branched-snfg-3d'
  370. },
  371. {
  372. expression: Q.lipid.expression,
  373. label: `${entryId} - Lipids`,
  374. type: 'ball-and-stick',
  375. tag: 'lipid'
  376. },
  377. {
  378. expression: Q.water.expression,
  379. label: `${entryId} - Waters`,
  380. type: 'ball-and-stick',
  381. tag: 'water'
  382. }
  383. ];
  384. }
  385. }
  386. export const selectionTest = (asymId: string, residues: number[]) => {
  387. if (residues.length > 0) {
  388. return {
  389. 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), asymId]),
  390. 'residue-test': MS.core.set.has([MS.set(...residues), MS.ammp('label_seq_id')])
  391. };
  392. } else {
  393. return { 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), asymId]) };
  394. }
  395. };
  396. export const toRange = (start: number, end?: number) => {
  397. if (!end) return [start];
  398. const b = start < end ? start : end;
  399. const e = start < end ? end : start;
  400. return [...Array(e - b + 1)].map((_, i) => b + i);
  401. };
  402. const labelFromProps = (entryId: string, range: Range) => {
  403. const residues: number[] = (range.label_seq_id) ? toRange(range.label_seq_id.beg, range.label_seq_id.end) : [];
  404. const label = entryId + (range.label_asym_id ? `.${range.label_asym_id}` : '') +
  405. (residues && residues.length > 0 ? `:${residues[0]}` : '') +
  406. (residues && residues.length > 1 ? `-${residues[residues.length - 1]}` : '');
  407. return label;
  408. };