preset.ts 17 KB

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