preset.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. type Target = {
  28. readonly auth_seq_id?: number
  29. readonly label_seq_id?: number
  30. readonly label_comp_id?: string
  31. readonly label_asym_id?: string
  32. }
  33. function targetToExpression(target: Target): Expression {
  34. const residueTests: Expression[] = []
  35. const tests = Object.create(null)
  36. if (target.auth_seq_id) {
  37. residueTests.push(MS.core.rel.eq([target.auth_seq_id, MS.ammp('auth_seq_id')]))
  38. } else if (target.label_seq_id) {
  39. residueTests.push(MS.core.rel.eq([target.label_seq_id, MS.ammp('label_seq_id')]))
  40. }
  41. if (target.label_comp_id) {
  42. residueTests.push(MS.core.rel.eq([target.label_comp_id, MS.ammp('label_comp_id')]))
  43. }
  44. if (residueTests.length === 1) {
  45. tests['residue-test'] = residueTests[0]
  46. } else if (residueTests.length > 1) {
  47. tests['residue-test'] = MS.core.logic.and(residueTests)
  48. }
  49. if (target.label_asym_id) {
  50. tests['chain-test'] = MS.core.rel.eq([target.label_asym_id, MS.ammp('label_asym_id')])
  51. }
  52. if (Object.keys(tests).length > 0) {
  53. return MS.struct.modifier.union([
  54. MS.struct.generator.atomGroups(tests)
  55. ])
  56. } else {
  57. return MS.struct.generator.empty
  58. }
  59. }
  60. function targetToLoci(target: Target, structure: Structure): StructureElement.Loci {
  61. const expression = targetToExpression(target)
  62. const query = compile<StructureSelection>(expression)
  63. const selection = query(new QueryContext(structure));
  64. return StructureSelection.toLociWithSourceUnits(selection)
  65. }
  66. type Range = { asymId: string, beg?: number, end?: number }
  67. type BaseProps = {
  68. assemblyId?: string
  69. modelIndex?: number
  70. }
  71. type ColorProp = {
  72. name: 'color',
  73. value: number
  74. };
  75. type PropSet = {
  76. args: ColorProp,
  77. positions: number[]
  78. };
  79. export type PropsetProps = {
  80. kind: 'prop-set',
  81. selection?: (Range & {
  82. matrix?: Mat4
  83. })[],
  84. representation: {
  85. asymId: string,
  86. propset: PropSet[]
  87. }[]
  88. } & BaseProps
  89. type ValidationProps = {
  90. kind: 'validation'
  91. colorTheme?: string
  92. showClashes?: boolean
  93. } & BaseProps
  94. type StandardProps = {
  95. kind: 'standard'
  96. } & BaseProps
  97. type SymmetryProps = {
  98. kind: 'symmetry'
  99. symmetryIndex?: number
  100. } & BaseProps
  101. type FeatureProps = {
  102. kind: 'feature'
  103. target: Target
  104. } & BaseProps
  105. type DensityProps = {
  106. kind: 'density'
  107. } & BaseProps
  108. export type PresetProps = ValidationProps | StandardProps | SymmetryProps | FeatureProps | DensityProps | PropsetProps
  109. const RcsbParams = (a: PluginStateObject.Molecule.Trajectory | undefined, plugin: PluginContext) => ({
  110. preset: PD.Value<PresetProps>({ kind: 'standard', assemblyId: '' }, { isHidden: true })
  111. });
  112. type StructureObject = StateObjectSelector<PluginStateObject.Molecule.Structure, StateTransformer<StateObject<any, StateObject.Type<any>>, StateObject<any, StateObject.Type<any>>, any>>
  113. const CommonParams = StructureRepresentationPresetProvider.CommonParams;
  114. const reprBuilder = StructureRepresentationPresetProvider.reprBuilder;
  115. const updateFocusRepr = StructureRepresentationPresetProvider.updateFocusRepr;
  116. type SelectionExpression = {
  117. tag: string
  118. type: StructureRepresentationRegistry.BuiltIn
  119. label: string
  120. expression: Expression
  121. };
  122. export const RcsbSuperpositionRepresentationPreset = StructureRepresentationPresetProvider({
  123. id: 'preset-superposition-representation-rcsb',
  124. display: {
  125. group: 'Superposition',
  126. name: 'Alignment',
  127. description: 'Show representations based on the structural alignment data.'
  128. },
  129. params: () => ({
  130. ...CommonParams,
  131. selectionExpressions: PD.Value<SelectionExpression[]>([])
  132. }),
  133. async apply(ref, params, plugin) {
  134. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  135. if (!structureCell) return {};
  136. const structure = structureCell.obj!.data;
  137. const cartoonProps = {sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2};
  138. let components = {};
  139. let representations = {};
  140. for (const expr of params.selectionExpressions) {
  141. const comp = await plugin.builders.structure.tryCreateComponentFromExpression(structureCell, expr.expression, expr.label, { label: expr.label });
  142. Object.assign(components, {[expr.label]: comp});
  143. const { update, builder, typeParams, color } = reprBuilder(plugin, params);
  144. let typeProps = {};
  145. if (expr.type === 'cartoon') {
  146. typeProps = {...typeParams, ...cartoonProps}
  147. } else {
  148. typeProps = {...typeParams}
  149. }
  150. Object.assign(representations, {
  151. [expr.label]: builder.buildRepresentation(update, comp, {type: expr.type,
  152. typeParams: typeProps, color: color as any}, { tag: expr.tag }),
  153. });
  154. await update.commit({ revertOnError: false });
  155. }
  156. // needed to apply same coloring scheme to focus representation
  157. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  158. return representations;
  159. }
  160. })
  161. export const RcsbPreset = TrajectoryHierarchyPresetProvider({
  162. id: 'preset-trajectory-rcsb',
  163. display: { name: 'RCSB' },
  164. isApplicable: o => {
  165. return true
  166. },
  167. params: RcsbParams,
  168. async apply(trajectory, params, plugin) {
  169. const builder = plugin.builders.structure;
  170. const p = params.preset
  171. const modelParams = { modelIndex: p.modelIndex || 0 }
  172. const structureParams: RootStructureDefinition.Params = { name: 'model', params: {} }
  173. if (p.assemblyId && p.assemblyId !== '' && p.assemblyId !== '0') {
  174. Object.assign(structureParams, {
  175. name: 'assembly',
  176. params: { id: p.assemblyId }
  177. } as RootStructureDefinition.Params)
  178. }
  179. const model = await builder.createModel(trajectory, modelParams);
  180. const modelProperties = await builder.insertModelProperties(model);
  181. let structure: StructureObject | undefined = undefined;
  182. let structureProperties: StructureObject | undefined = undefined;
  183. // If flexible transformation is allowed, we may need to create a single structure component
  184. // from transformed substructures
  185. const allowsFlexTransform = p.kind === 'prop-set';
  186. if (!allowsFlexTransform) {
  187. structure = await builder.createStructure(modelProperties || model, structureParams);
  188. structureProperties = await builder.insertStructureProperties(structure);
  189. }
  190. const unitcell = await builder.tryCreateUnitcell(modelProperties, undefined, { isHidden: true });
  191. let representation: StructureRepresentationPresetProvider.Result | undefined = undefined;
  192. if (p.kind === 'prop-set') {
  193. // This creates a single structure from selections/transformations as specified
  194. const _structure = plugin.state.data.build().to(modelProperties)
  195. .apply(FlexibleStructureFromModel, { selection: p.selection });
  196. structure = await _structure.commit();
  197. const _structureProperties = plugin.state.data.build().to(structure)
  198. .apply(CustomStructureProperties);
  199. structureProperties = await _structureProperties.commit();
  200. // adding coloring lookup scheme
  201. structure.data!.inheritedPropertyData.colors = {};
  202. for (const reprProp of p.representation) {
  203. const colorLookup = structure.data!.inheritedPropertyData.colors[reprProp.asymId] || new Map();
  204. reprProp.propset.forEach(prop => {
  205. if (prop.args.name === 'color') {
  206. for (let i = 0; i < prop.positions.length; i++) {
  207. colorLookup.set(prop.positions[i], prop.args.value);
  208. }
  209. }
  210. });
  211. structure.data!.inheritedPropertyData.colors[reprProp.asymId] = colorLookup;
  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. ViewerState(plugin).collapsed.next({
  257. ...ViewerState(plugin).collapsed.value,
  258. volume: false
  259. })
  260. }
  261. return {
  262. model,
  263. modelProperties,
  264. unitcell,
  265. structure,
  266. structureProperties,
  267. representation
  268. };
  269. }
  270. });
  271. export function createSelectionExpression(entryId: string, range?: Range): SelectionExpression[] {
  272. if (range) {
  273. const residues: number[] = (range.beg && range.end) ? toRange(range.beg, range.end) : [];
  274. const test = selectionTest(range.asymId, residues);
  275. const label = labelFromProps(entryId, range);
  276. return [{
  277. expression: MS.struct.generator.atomGroups(test),
  278. label: `${label}`,
  279. type: 'cartoon',
  280. tag: 'polymer'
  281. }]
  282. } else {
  283. return [
  284. {
  285. expression: Q.polymer.expression,
  286. label: `${entryId} - Polymers`,
  287. type: 'cartoon',
  288. tag: 'polymer'
  289. },
  290. {
  291. expression: Q.ligand.expression,
  292. label: `${entryId} - Ligands`,
  293. type: 'ball-and-stick',
  294. tag: 'ligand'
  295. },
  296. {
  297. expression: Q.ion.expression,
  298. label: `${entryId} - Ions`,
  299. type: 'ball-and-stick',
  300. tag: 'ion'
  301. },
  302. {
  303. expression: Q.branched.expression,
  304. label: `${entryId} - Carbohydrates`,
  305. type: 'carbohydrate',
  306. tag: 'branched-snfg-3d'
  307. },
  308. {
  309. expression: Q.lipid.expression,
  310. label: `${entryId} - Lipids`,
  311. type: 'ball-and-stick',
  312. tag: 'lipid'
  313. },
  314. {
  315. expression: Q.water.expression,
  316. label: `${entryId} - Waters`,
  317. type: 'ball-and-stick',
  318. tag: 'water'
  319. }
  320. ]
  321. }
  322. }
  323. export const selectionTest = (asymId: string, residues: number[]) => {
  324. if (residues.length > 0) {
  325. return {
  326. 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), asymId]),
  327. 'residue-test': MS.core.set.has([MS.set(...residues), MS.ammp('label_seq_id')])
  328. };
  329. } else {
  330. return { 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), asymId]) };
  331. }
  332. }
  333. export const toRange = (start: number, end: number) => [...Array(end - start + 1)].map((_, i) => start + i);
  334. const labelFromProps = (entryId: string, range: Range) => {
  335. return entryId +(range.asymId ? `.${range.asymId}` : '') +
  336. (range.beg && range.end ? `:${range.beg.toString()}-${range.end.toString()}` : '');
  337. }