preset.ts 17 KB

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