representation-preset.ts 19 KB

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