preset.ts 17 KB

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