preset.ts 23 KB

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