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