representation-preset.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /**
  2. * Copyright (c) 2019-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { PresetProvider } from '../preset-provider';
  8. import { PluginStateObject } from '../../objects';
  9. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  10. import { VisualQuality, VisualQualityOptions } from '../../../mol-geo/geometry/base';
  11. import { ColorTheme } from '../../../mol-theme/color';
  12. import { Structure } from '../../../mol-model/structure';
  13. import { PluginContext } from '../../../mol-plugin/context';
  14. import { StateObjectRef, StateObjectSelector } from '../../../mol-state';
  15. import { StaticStructureComponentType } from '../../helpers/structure-component';
  16. import { StructureSelectionQueries as Q } from '../../helpers/structure-selection-query';
  17. import { PluginConfig } from '../../../mol-plugin/config';
  18. import { StructureFocusRepresentation } from '../../../mol-plugin/behavior/dynamic/selection/structure-focus-representation';
  19. import { createStructureColorThemeParams } from '../../helpers/structure-representation-params';
  20. import { ChainIdColorThemeProvider } from '../../../mol-theme/color/chain-id';
  21. import { OperatorNameColorThemeProvider } from '../../../mol-theme/color/operator-name';
  22. import { IndexPairBonds } from '../../../mol-model-formats/structure/property/bonds/index-pair';
  23. import { StructConn } from '../../../mol-model-formats/structure/property/bonds/struct_conn';
  24. import { StructureRepresentationRegistry } from '../../../mol-repr/structure/registry';
  25. import { assertUnreachable } from '../../../mol-util/type-helpers';
  26. export interface StructureRepresentationPresetProvider<P = any, S extends _Result = _Result> extends PresetProvider<PluginStateObject.Molecule.Structure, P, S> { }
  27. export function StructureRepresentationPresetProvider<P, S extends _Result>(repr: StructureRepresentationPresetProvider<P, S>) { return repr; }
  28. export namespace StructureRepresentationPresetProvider {
  29. export type Params<P extends StructureRepresentationPresetProvider> = P extends StructureRepresentationPresetProvider<infer T> ? T : never;
  30. export type State<P extends StructureRepresentationPresetProvider> = P extends StructureRepresentationPresetProvider<infer _, infer S> ? S : never;
  31. export type Result = {
  32. components?: { [name: string]: StateObjectSelector | undefined },
  33. representations?: { [name: string]: StateObjectSelector | undefined }
  34. }
  35. export const CommonParams = {
  36. ignoreHydrogens: PD.Optional(PD.Boolean(false)),
  37. quality: PD.Optional(PD.Select<VisualQuality>('auto', VisualQualityOptions)),
  38. theme: PD.Optional(PD.Group({
  39. globalName: PD.Optional(PD.Text<ColorTheme.BuiltIn>('')),
  40. carbonColor: PD.Optional(PD.Select('chain-id', PD.arrayToOptions(['chain-id', 'operator-name', 'element-symbol'] as const))),
  41. symmetryColor: PD.Optional(PD.Text<ColorTheme.BuiltIn>('')),
  42. focus: PD.Optional(PD.Group({
  43. name: PD.Optional(PD.Text<ColorTheme.BuiltIn>('')),
  44. params: PD.Optional(PD.Value<ColorTheme.BuiltInParams<ColorTheme.BuiltIn>>({} as any))
  45. }))
  46. }))
  47. };
  48. export type CommonParams = PD.ValuesFor<typeof CommonParams>
  49. function getCarbonColorParams(name: 'chain-id' | 'operator-name' | 'element-symbol') {
  50. return name === 'chain-id'
  51. ? { name, params: ChainIdColorThemeProvider.defaultValues }
  52. : name === 'operator-name'
  53. ? { name, params: OperatorNameColorThemeProvider.defaultValues }
  54. : { name, params: {} };
  55. }
  56. function isSymmetry(structure: Structure) {
  57. return structure.units.some(u => !u.conformation.operator.assembly && u.conformation.operator.spgrOp >= 0);
  58. }
  59. export function reprBuilder(plugin: PluginContext, params: CommonParams, structure?: Structure) {
  60. const update = plugin.state.data.build();
  61. const builder = plugin.builders.structure.representation;
  62. const typeParams = {
  63. quality: plugin.managers.structure.component.state.options.visualQuality,
  64. ignoreHydrogens: !plugin.managers.structure.component.state.options.showHydrogens,
  65. };
  66. if (params.quality && params.quality !== 'auto') typeParams.quality = params.quality;
  67. if (params.ignoreHydrogens !== void 0) typeParams.ignoreHydrogens = !!params.ignoreHydrogens;
  68. const color: ColorTheme.BuiltIn | undefined = params.theme?.globalName ? params.theme?.globalName : void 0;
  69. const ballAndStickColor: ColorTheme.BuiltInParams<'element-symbol'> = params.theme?.carbonColor !== undefined
  70. ? { carbonColor: getCarbonColorParams(params.theme?.carbonColor) }
  71. : { };
  72. const symmetryColor: ColorTheme.BuiltIn | undefined = structure && params.theme?.symmetryColor
  73. ? isSymmetry(structure) ? params.theme?.symmetryColor : color
  74. : color;
  75. return { update, builder, color, symmetryColor, typeParams, ballAndStickColor };
  76. }
  77. export function updateFocusRepr<T extends ColorTheme.BuiltIn>(plugin: PluginContext, structure: Structure, themeName: T | undefined, themeParams: ColorTheme.BuiltInParams<T> | undefined) {
  78. return plugin.state.updateBehavior(StructureFocusRepresentation, p => {
  79. const c = createStructureColorThemeParams(plugin, structure, 'ball-and-stick', themeName || 'element-symbol', themeParams);
  80. p.surroundingsParams.colorTheme = c;
  81. p.targetParams.colorTheme = c;
  82. });
  83. }
  84. }
  85. type _Result = StructureRepresentationPresetProvider.Result
  86. const CommonParams = StructureRepresentationPresetProvider.CommonParams;
  87. type CommonParams = StructureRepresentationPresetProvider.CommonParams
  88. const reprBuilder = StructureRepresentationPresetProvider.reprBuilder;
  89. const updateFocusRepr = StructureRepresentationPresetProvider.updateFocusRepr;
  90. const auto = StructureRepresentationPresetProvider({
  91. id: 'preset-structure-representation-auto',
  92. display: {
  93. name: 'Automatic',
  94. description: 'Show representations based on the size of the structure. Smaller structures are shown with more detail than larger ones, ranging from atomistic display to coarse surfaces.'
  95. },
  96. params: () => CommonParams,
  97. apply(ref, params, plugin) {
  98. const structure = StateObjectRef.resolveAndCheck(plugin.state.data, ref)?.obj?.data;
  99. if (!structure) return { };
  100. const thresholds = plugin.config.get(PluginConfig.Structure.SizeThresholds) || Structure.DefaultSizeThresholds;
  101. const size = Structure.getSize(structure, thresholds);
  102. const gapFraction = structure.polymerResidueCount / structure.polymerGapCount;
  103. switch (size) {
  104. case Structure.Size.Gigantic:
  105. case Structure.Size.Huge:
  106. return coarseSurface.apply(ref, params, plugin);
  107. case Structure.Size.Large:
  108. return polymerCartoon.apply(ref, params, plugin);
  109. case Structure.Size.Medium:
  110. if (gapFraction > 3) {
  111. return polymerAndLigand.apply(ref, params, plugin);
  112. } // else fall through
  113. case Structure.Size.Small:
  114. // `showCarbohydrateSymbol: true` is nice, e.g., for PDB 1aga
  115. return atomicDetail.apply(ref, { ...params, showCarbohydrateSymbol: true }, plugin);
  116. default:
  117. assertUnreachable(size);
  118. }
  119. }
  120. });
  121. const empty = StructureRepresentationPresetProvider({
  122. id: 'preset-structure-representation-empty',
  123. display: { name: 'Empty', description: 'Removes all existing representations.' },
  124. async apply(ref, params, plugin) {
  125. return { };
  126. }
  127. });
  128. const BuiltInPresetGroupName = 'Basic';
  129. const polymerAndLigand = StructureRepresentationPresetProvider({
  130. id: 'preset-structure-representation-polymer-and-ligand',
  131. display: {
  132. name: 'Polymer & Ligand', group: BuiltInPresetGroupName,
  133. description: 'Shows polymers as Cartoon, ligands as Ball & Stick, carbohydrates as 3D-SNFG and water molecules semi-transparent.'
  134. },
  135. params: () => CommonParams,
  136. async apply(ref, params, plugin) {
  137. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  138. if (!structureCell) return {};
  139. const components = {
  140. polymer: await presetStaticComponent(plugin, structureCell, 'polymer'),
  141. ligand: await presetStaticComponent(plugin, structureCell, 'ligand'),
  142. nonStandard: await presetStaticComponent(plugin, structureCell, 'non-standard'),
  143. branched: await presetStaticComponent(plugin, structureCell, 'branched', { label: 'Carbohydrate' }),
  144. water: await presetStaticComponent(plugin, structureCell, 'water'),
  145. ion: await presetStaticComponent(plugin, structureCell, 'ion'),
  146. lipid: await presetStaticComponent(plugin, structureCell, 'lipid'),
  147. coarse: await presetStaticComponent(plugin, structureCell, 'coarse')
  148. };
  149. const structure = structureCell.obj!.data;
  150. const cartoonProps = {
  151. sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2,
  152. };
  153. // TODO make configurable
  154. const waterType = (components.water?.obj?.data?.elementCount || 0) > 50_000 ? 'line' : 'ball-and-stick';
  155. const lipidType = (components.lipid?.obj?.data?.elementCount || 0) > 20_000 ? 'line' : 'ball-and-stick';
  156. const { update, builder, typeParams, color, symmetryColor, ballAndStickColor } = reprBuilder(plugin, params, structure);
  157. const representations = {
  158. polymer: builder.buildRepresentation(update, components.polymer, { type: 'cartoon', typeParams: { ...typeParams, ...cartoonProps }, color: symmetryColor }, { tag: 'polymer' }),
  159. ligand: builder.buildRepresentation(update, components.ligand, { type: 'ball-and-stick', typeParams, color, colorParams: ballAndStickColor }, { tag: 'ligand' }),
  160. nonStandard: builder.buildRepresentation(update, components.nonStandard, { type: 'ball-and-stick', typeParams, color, colorParams: ballAndStickColor }, { tag: 'non-standard' }),
  161. branchedBallAndStick: builder.buildRepresentation(update, components.branched, { type: 'ball-and-stick', typeParams: { ...typeParams, alpha: 0.3 }, color, colorParams: ballAndStickColor }, { tag: 'branched-ball-and-stick' }),
  162. branchedSnfg3d: builder.buildRepresentation(update, components.branched, { type: 'carbohydrate', typeParams, color }, { tag: 'branched-snfg-3d' }),
  163. water: builder.buildRepresentation(update, components.water, { type: waterType, typeParams: { ...typeParams, alpha: 0.6 }, color, colorParams: { carbonColor: { name: 'element-symbol', params: {} } } }, { tag: 'water' }),
  164. ion: builder.buildRepresentation(update, components.ion, { type: 'ball-and-stick', typeParams, color, colorParams: { carbonColor: { name: 'element-symbol', params: {} } } }, { tag: 'ion' }),
  165. lipid: builder.buildRepresentation(update, components.lipid, { type: lipidType, typeParams: { ...typeParams, alpha: 0.6 }, color, colorParams: { carbonColor: { name: 'element-symbol', params: {} } } }, { tag: 'lipid' }),
  166. coarse: builder.buildRepresentation(update, components.coarse, { type: 'spacefill', typeParams, color: color || 'chain-id' }, { tag: 'coarse' })
  167. };
  168. await update.commit({ revertOnError: false });
  169. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  170. return { components, representations };
  171. }
  172. });
  173. const proteinAndNucleic = StructureRepresentationPresetProvider({
  174. id: 'preset-structure-representation-protein-and-nucleic',
  175. display: {
  176. name: 'Protein & Nucleic', group: BuiltInPresetGroupName,
  177. description: 'Shows proteins as Cartoon and RNA/DNA as Gaussian Surface.'
  178. },
  179. params: () => CommonParams,
  180. async apply(ref, params, plugin) {
  181. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  182. if (!structureCell) return {};
  183. const components = {
  184. protein: await presetSelectionComponent(plugin, structureCell, 'protein'),
  185. nucleic: await presetSelectionComponent(plugin, structureCell, 'nucleic'),
  186. };
  187. const structure = structureCell.obj!.data;
  188. const cartoonProps = {
  189. sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2,
  190. };
  191. const gaussianProps = {
  192. radiusOffset: structure.isCoarseGrained ? 2 : 0,
  193. smoothness: structure.isCoarseGrained ? 1.0 : 1.5,
  194. };
  195. const { update, builder, typeParams, symmetryColor } = reprBuilder(plugin, params, structure);
  196. const representations = {
  197. protein: builder.buildRepresentation(update, components.protein, { type: 'cartoon', typeParams: { ...typeParams, ...cartoonProps }, color: symmetryColor }, { tag: 'protein' }),
  198. nucleic: builder.buildRepresentation(update, components.nucleic, { type: 'gaussian-surface', typeParams: { ...typeParams, ...gaussianProps }, color: symmetryColor }, { tag: 'nucleic' })
  199. };
  200. await update.commit({ revertOnError: true });
  201. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  202. return { components, representations };
  203. }
  204. });
  205. const coarseSurface = StructureRepresentationPresetProvider({
  206. id: 'preset-structure-representation-coarse-surface',
  207. display: {
  208. name: 'Coarse Surface', group: BuiltInPresetGroupName,
  209. description: 'Shows polymers and lipids as coarse Gaussian Surface.'
  210. },
  211. params: () => CommonParams,
  212. async apply(ref, params, plugin) {
  213. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  214. if (!structureCell) return {};
  215. const components = {
  216. polymer: await presetStaticComponent(plugin, structureCell, 'polymer'),
  217. lipid: await presetStaticComponent(plugin, structureCell, 'lipid'),
  218. };
  219. const structure = structureCell.obj!.data;
  220. const size = Structure.getSize(structure);
  221. const gaussianProps = Object.create(null);
  222. if (size === Structure.Size.Gigantic) {
  223. Object.assign(gaussianProps, {
  224. traceOnly: !structure.isCoarseGrained,
  225. radiusOffset: 2,
  226. smoothness: 1,
  227. visuals: ['structure-gaussian-surface-mesh']
  228. });
  229. } else if(size === Structure.Size.Huge) {
  230. Object.assign(gaussianProps, {
  231. radiusOffset: structure.isCoarseGrained ? 2 : 0,
  232. smoothness: 1,
  233. });
  234. } else if(structure.isCoarseGrained) {
  235. Object.assign(gaussianProps, {
  236. radiusOffset: 2,
  237. smoothness: 1,
  238. });
  239. }
  240. const { update, builder, typeParams, symmetryColor } = reprBuilder(plugin, params, structure);
  241. const representations = {
  242. polymer: builder.buildRepresentation(update, components.polymer, { type: 'gaussian-surface', typeParams: { ...typeParams, ...gaussianProps }, color: symmetryColor }, { tag: 'polymer' }),
  243. lipid: builder.buildRepresentation(update, components.lipid, { type: 'gaussian-surface', typeParams: { ...typeParams, ...gaussianProps }, color: symmetryColor }, { tag: 'lipid' })
  244. };
  245. await update.commit({ revertOnError: true });
  246. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  247. return { components, representations };
  248. }
  249. });
  250. const polymerCartoon = StructureRepresentationPresetProvider({
  251. id: 'preset-structure-representation-polymer-cartoon',
  252. display: {
  253. name: 'Polymer Cartoon', group: BuiltInPresetGroupName,
  254. description: 'Shows polymers as Cartoon.'
  255. },
  256. params: () => CommonParams,
  257. async apply(ref, params, plugin) {
  258. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  259. if (!structureCell) return {};
  260. const components = {
  261. polymer: await presetStaticComponent(plugin, structureCell, 'polymer'),
  262. };
  263. const structure = structureCell.obj!.data;
  264. const cartoonProps = {
  265. sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2
  266. };
  267. const { update, builder, typeParams, symmetryColor } = reprBuilder(plugin, params, structure);
  268. const representations = {
  269. polymer: builder.buildRepresentation(update, components.polymer, { type: 'cartoon', typeParams: { ...typeParams, ...cartoonProps }, color: symmetryColor }, { tag: 'polymer' })
  270. };
  271. await update.commit({ revertOnError: true });
  272. await updateFocusRepr(plugin, structure, params.theme?.focus?.name, params.theme?.focus?.params);
  273. return { components, representations };
  274. }
  275. });
  276. const atomicDetail = StructureRepresentationPresetProvider({
  277. id: 'preset-structure-representation-atomic-detail',
  278. display: {
  279. name: 'Atomic Detail', group: BuiltInPresetGroupName,
  280. description: 'Shows everything in atomic detail with Ball & Stick.'
  281. },
  282. params: () => ({
  283. ...CommonParams,
  284. showCarbohydrateSymbol: PD.Boolean(false)
  285. }),
  286. async apply(ref, params, plugin) {
  287. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  288. if (!structureCell) return {};
  289. const components = {
  290. all: await presetStaticComponent(plugin, structureCell, 'all'),
  291. branched: undefined
  292. };
  293. const structure = structureCell.obj!.data;
  294. const highElementCount = structure.elementCount > 100_000; // TODO make configurable
  295. const lowResidueElementRatio = structure.atomicResidueCount &&
  296. structure.elementCount > 1000 &&
  297. structure.atomicResidueCount / structure.elementCount < 3;
  298. const m = structure.models[0];
  299. const bondsGiven = !!IndexPairBonds.Provider.get(m) || StructConn.isExhaustive(m);
  300. let atomicType: StructureRepresentationRegistry.BuiltIn = 'ball-and-stick';
  301. if (structure.isCoarseGrained) {
  302. // TODO make configurable?
  303. atomicType = structure.elementCount > 1_000_000 ? 'point' : 'spacefill';
  304. } else if (lowResidueElementRatio && !bondsGiven) {
  305. atomicType = 'spacefill';
  306. } else if (highElementCount) {
  307. atomicType = 'line';
  308. }
  309. const showCarbohydrateSymbol = params.showCarbohydrateSymbol && !highElementCount && !lowResidueElementRatio;
  310. if (showCarbohydrateSymbol) {
  311. Object.assign(components, {
  312. branched: await presetStaticComponent(plugin, structureCell, 'branched', { label: 'Carbohydrate' }),
  313. });
  314. }
  315. const { update, builder, typeParams, color, ballAndStickColor } = reprBuilder(plugin, params, structure);
  316. const colorParams = lowResidueElementRatio && !bondsGiven
  317. ? { carbonColor: { name: 'element-symbol', params: {} } }
  318. : ballAndStickColor;
  319. const representations = {
  320. all: builder.buildRepresentation(update, components.all, { type: atomicType, typeParams, color, colorParams }, { tag: 'all' }),
  321. };
  322. if (showCarbohydrateSymbol) {
  323. Object.assign(representations, {
  324. snfg3d: builder.buildRepresentation(update, components.branched, { type: 'carbohydrate', typeParams: { ...typeParams, alpha: 0.4, visuals: ['carbohydrate-symbol'] }, color }, { tag: 'snfg-3d' }),
  325. });
  326. }
  327. await update.commit({ revertOnError: true });
  328. return { components, representations };
  329. }
  330. });
  331. export function presetStaticComponent(plugin: PluginContext, structure: StateObjectRef<PluginStateObject.Molecule.Structure>, type: StaticStructureComponentType, params?: { label?: string, tags?: string[] }) {
  332. return plugin.builders.structure.tryCreateComponentStatic(structure, type, params);
  333. }
  334. export function presetSelectionComponent(plugin: PluginContext, structure: StateObjectRef<PluginStateObject.Molecule.Structure>, query: keyof typeof Q, params?: { label?: string, tags?: string[] }) {
  335. return plugin.builders.structure.tryCreateComponentFromSelection(structure, Q[query], `selection-${query}`, params);
  336. }
  337. export const PresetStructureRepresentations = {
  338. empty,
  339. auto,
  340. 'atomic-detail': atomicDetail,
  341. 'polymer-cartoon': polymerCartoon,
  342. 'polymer-and-ligand': polymerAndLigand,
  343. 'protein-and-nucleic': proteinAndNucleic,
  344. 'coarse-surface': coarseSurface
  345. };
  346. export type PresetStructureRepresentations = typeof PresetStructureRepresentations;