index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /**
  2. * Copyright (c) 2018-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 { ANVILMembraneOrientation } from '../../extensions/anvil/behavior';
  8. import { CellPack } from '../../extensions/cellpack';
  9. import { DnatcoConfalPyramids } from '../../extensions/dnatco';
  10. import { G3DFormat, G3dProvider } from '../../extensions/g3d/format';
  11. import { Mp4Export } from '../../extensions/mp4-export';
  12. import { GeometryExport } from '../../extensions/geo-export';
  13. import { PDBeStructureQualityReport } from '../../extensions/pdbe';
  14. import { RCSBAssemblySymmetry, RCSBValidationReport } from '../../extensions/rcsb';
  15. import { DownloadStructure, PdbDownloadProvider } from '../../mol-plugin-state/actions/structure';
  16. import { DownloadDensity } from '../../mol-plugin-state/actions/volume';
  17. import { StructureRepresentationPresetProvider } from '../../mol-plugin-state/builder/structure/representation-preset';
  18. import { DataFormatProvider } from '../../mol-plugin-state/formats/provider';
  19. import { BuiltInTrajectoryFormat } from '../../mol-plugin-state/formats/trajectory';
  20. import { BuildInVolumeFormat } from '../../mol-plugin-state/formats/volume';
  21. import { createVolumeRepresentationParams } from '../../mol-plugin-state/helpers/volume-representation-params';
  22. import { PluginStateObject } from '../../mol-plugin-state/objects';
  23. import { StateTransforms } from '../../mol-plugin-state/transforms';
  24. import { createPlugin } from '../../mol-plugin-ui';
  25. import { PluginUIContext } from '../../mol-plugin-ui/context';
  26. import { PluginLayoutControlsDisplay } from '../../mol-plugin/layout';
  27. import { DefaultPluginUISpec, PluginUISpec } from '../../mol-plugin-ui/spec';
  28. import { PluginCommands } from '../../mol-plugin/commands';
  29. import { PluginConfig } from '../../mol-plugin/config';
  30. import { PluginSpec } from '../../mol-plugin/spec';
  31. import { PluginState } from '../../mol-plugin/state';
  32. import { StateObjectSelector } from '../../mol-state';
  33. import { Asset } from '../../mol-util/assets';
  34. import { Color } from '../../mol-util/color';
  35. import '../../mol-util/polyfill';
  36. import { ObjectKeys } from '../../mol-util/type-helpers';
  37. import './embedded.html';
  38. import './favicon.ico';
  39. import './index.html';
  40. require('mol-plugin-ui/skin/light.scss');
  41. export { PLUGIN_VERSION as version } from '../../mol-plugin/version';
  42. export { setDebugMode, setProductionMode } from '../../mol-util/debug';
  43. const CustomFormats = [
  44. ['g3d', G3dProvider] as const
  45. ];
  46. const Extensions = {
  47. 'cellpack': PluginSpec.Behavior(CellPack),
  48. 'dnatco-confal-pyramids': PluginSpec.Behavior(DnatcoConfalPyramids),
  49. 'pdbe-structure-quality-report': PluginSpec.Behavior(PDBeStructureQualityReport),
  50. 'rcsb-assembly-symmetry': PluginSpec.Behavior(RCSBAssemblySymmetry),
  51. 'rcsb-validation-report': PluginSpec.Behavior(RCSBValidationReport),
  52. 'anvil-membrane-orientation': PluginSpec.Behavior(ANVILMembraneOrientation),
  53. 'g3d': PluginSpec.Behavior(G3DFormat),
  54. 'mp4-export': PluginSpec.Behavior(Mp4Export),
  55. 'geo-export': PluginSpec.Behavior(GeometryExport)
  56. };
  57. const DefaultViewerOptions = {
  58. customFormats: CustomFormats as [string, DataFormatProvider][],
  59. extensions: ObjectKeys(Extensions),
  60. layoutIsExpanded: true,
  61. layoutShowControls: true,
  62. layoutShowRemoteState: true,
  63. layoutControlsDisplay: 'reactive' as PluginLayoutControlsDisplay,
  64. layoutShowSequence: true,
  65. layoutShowLog: true,
  66. layoutShowLeftPanel: true,
  67. collapseLeftPanel: false,
  68. disableAntialiasing: PluginConfig.General.DisableAntialiasing.defaultValue,
  69. pixelScale: PluginConfig.General.PixelScale.defaultValue,
  70. pickScale: PluginConfig.General.PickScale.defaultValue,
  71. enableWboit: PluginConfig.General.EnableWboit.defaultValue,
  72. viewportShowExpand: PluginConfig.Viewport.ShowExpand.defaultValue,
  73. viewportShowControls: PluginConfig.Viewport.ShowControls.defaultValue,
  74. viewportShowSettings: PluginConfig.Viewport.ShowSettings.defaultValue,
  75. viewportShowSelectionMode: PluginConfig.Viewport.ShowSelectionMode.defaultValue,
  76. viewportShowAnimation: PluginConfig.Viewport.ShowAnimation.defaultValue,
  77. pluginStateServer: PluginConfig.State.DefaultServer.defaultValue,
  78. volumeStreamingServer: PluginConfig.VolumeStreaming.DefaultServer.defaultValue,
  79. volumeStreamingDisabled: !PluginConfig.VolumeStreaming.Enabled.defaultValue,
  80. pdbProvider: PluginConfig.Download.DefaultPdbProvider.defaultValue,
  81. emdbProvider: PluginConfig.Download.DefaultEmdbProvider.defaultValue,
  82. };
  83. type ViewerOptions = typeof DefaultViewerOptions;
  84. export class Viewer {
  85. plugin: PluginUIContext
  86. constructor(elementOrId: string | HTMLElement, options: Partial<ViewerOptions> = {}) {
  87. const o = { ...DefaultViewerOptions, ...options };
  88. const defaultSpec = DefaultPluginUISpec();
  89. const spec: PluginUISpec = {
  90. actions: defaultSpec.actions,
  91. behaviors: [
  92. ...defaultSpec.behaviors,
  93. ...o.extensions.map(e => Extensions[e]),
  94. ],
  95. animations: [...defaultSpec.animations || []],
  96. customParamEditors: defaultSpec.customParamEditors,
  97. customFormats: o?.customFormats,
  98. layout: {
  99. initial: {
  100. isExpanded: o.layoutIsExpanded,
  101. showControls: o.layoutShowControls,
  102. controlsDisplay: o.layoutControlsDisplay,
  103. regionState: {
  104. bottom: 'full',
  105. left: o.collapseLeftPanel ? 'collapsed' : 'full',
  106. right: 'full',
  107. top: 'full',
  108. }
  109. },
  110. },
  111. components: {
  112. ...defaultSpec.components,
  113. controls: {
  114. ...defaultSpec.components?.controls,
  115. top: o.layoutShowSequence ? undefined : 'none',
  116. bottom: o.layoutShowLog ? undefined : 'none',
  117. left: o.layoutShowLeftPanel ? undefined : 'none',
  118. },
  119. remoteState: o.layoutShowRemoteState ? 'default' : 'none',
  120. },
  121. config: [
  122. [PluginConfig.General.DisableAntialiasing, o.disableAntialiasing],
  123. [PluginConfig.General.PixelScale, o.pixelScale],
  124. [PluginConfig.General.PickScale, o.pickScale],
  125. [PluginConfig.General.EnableWboit, o.enableWboit],
  126. [PluginConfig.Viewport.ShowExpand, o.viewportShowExpand],
  127. [PluginConfig.Viewport.ShowControls, o.viewportShowControls],
  128. [PluginConfig.Viewport.ShowSettings, o.viewportShowSettings],
  129. [PluginConfig.Viewport.ShowSelectionMode, o.viewportShowSelectionMode],
  130. [PluginConfig.Viewport.ShowAnimation, o.viewportShowAnimation],
  131. [PluginConfig.State.DefaultServer, o.pluginStateServer],
  132. [PluginConfig.State.CurrentServer, o.pluginStateServer],
  133. [PluginConfig.VolumeStreaming.DefaultServer, o.volumeStreamingServer],
  134. [PluginConfig.VolumeStreaming.Enabled, !o.volumeStreamingDisabled],
  135. [PluginConfig.Download.DefaultPdbProvider, o.pdbProvider],
  136. [PluginConfig.Download.DefaultEmdbProvider, o.emdbProvider]
  137. ]
  138. };
  139. const element = typeof elementOrId === 'string'
  140. ? document.getElementById(elementOrId)
  141. : elementOrId;
  142. if (!element) throw new Error(`Could not get element with id '${elementOrId}'`);
  143. this.plugin = createPlugin(element, spec);
  144. }
  145. setRemoteSnapshot(id: string) {
  146. const url = `${this.plugin.config.get(PluginConfig.State.CurrentServer)}/get/${id}`;
  147. return PluginCommands.State.Snapshots.Fetch(this.plugin, { url });
  148. }
  149. loadSnapshotFromUrl(url: string, type: PluginState.SnapshotType) {
  150. return PluginCommands.State.Snapshots.OpenUrl(this.plugin, { url, type });
  151. }
  152. loadStructureFromUrl(url: string, format: BuiltInTrajectoryFormat = 'mmcif', isBinary = false, options?: LoadStructureOptions) {
  153. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  154. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  155. source: {
  156. name: 'url',
  157. params: {
  158. url: Asset.Url(url),
  159. format: format as any,
  160. isBinary,
  161. options: { ...params.source.params.options, representationParams: options?.representationParams as any },
  162. }
  163. }
  164. }));
  165. }
  166. async loadAllModelsOrAssemblyFromUrl(url: string, format: BuiltInTrajectoryFormat = 'mmcif', isBinary = false, options?: LoadStructureOptions) {
  167. const plugin = this.plugin;
  168. const data = await plugin.builders.data.download({ url, isBinary }, { state: { isGhost: true } });
  169. const trajectory = await plugin.builders.structure.parseTrajectory(data, format);
  170. await this.plugin.builders.structure.hierarchy.applyPreset(trajectory, 'all-models', { useDefaultIfSingleModel: true, representationPresetParams: options?.representationParams });
  171. }
  172. async loadStructureFromData(data: string | number[], format: BuiltInTrajectoryFormat, options?: { dataLabel?: string }) {
  173. const _data = await this.plugin.builders.data.rawData({ data, label: options?.dataLabel });
  174. const trajectory = await this.plugin.builders.structure.parseTrajectory(_data, format);
  175. await this.plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default');
  176. }
  177. loadPdb(pdb: string, options?: LoadStructureOptions) {
  178. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  179. const provider = this.plugin.config.get(PluginConfig.Download.DefaultPdbProvider)!;
  180. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  181. source: {
  182. name: 'pdb' as const,
  183. params: {
  184. provider: {
  185. id: pdb,
  186. server: {
  187. name: provider,
  188. params: PdbDownloadProvider[provider].defaultValue as any
  189. }
  190. },
  191. options: { ...params.source.params.options, representationParams: options?.representationParams as any },
  192. }
  193. }
  194. }));
  195. }
  196. loadPdbDev(pdbDev: string) {
  197. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  198. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  199. source: {
  200. name: 'pdb-dev' as const,
  201. params: {
  202. provider: {
  203. id: pdbDev,
  204. encoding: 'bcif',
  205. },
  206. options: params.source.params.options,
  207. }
  208. }
  209. }));
  210. }
  211. loadEmdb(emdb: string, options?: { detail?: number }) {
  212. const provider = this.plugin.config.get(PluginConfig.Download.DefaultEmdbProvider)!;
  213. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadDensity, {
  214. source: {
  215. name: 'pdb-emd-ds' as const,
  216. params: {
  217. provider: {
  218. id: emdb,
  219. server: provider,
  220. },
  221. detail: options?.detail ?? 3,
  222. }
  223. }
  224. }));
  225. }
  226. /**
  227. * @example Load X-ray density from volume server
  228. viewer.loadVolumeFromUrl({
  229. url: 'https://www.ebi.ac.uk/pdbe/densities/x-ray/1tqn/cell?detail=3',
  230. format: 'dscif',
  231. isBinary: true
  232. }, [{
  233. type: 'relative',
  234. value: 1.5,
  235. color: 0x3362B2
  236. }, {
  237. type: 'relative',
  238. value: 3,
  239. color: 0x33BB33,
  240. volumeIndex: 1
  241. }, {
  242. type: 'relative',
  243. value: -3,
  244. color: 0xBB3333,
  245. volumeIndex: 1
  246. }], {
  247. entryId: ['2FO-FC', 'FO-FC'],
  248. isLazy: true
  249. });
  250. * *********************
  251. * @example Load EM density from volume server
  252. viewer.loadVolumeFromUrl({
  253. url: 'https://maps.rcsb.org/em/emd-30210/cell?detail=6',
  254. format: 'dscif',
  255. isBinary: true
  256. }, [{
  257. type: 'relative',
  258. value: 1,
  259. color: 0x3377aa
  260. }], {
  261. entryId: 'EMD-30210',
  262. isLazy: true
  263. });
  264. */
  265. async loadVolumeFromUrl({ url, format, isBinary }: { url: string, format: BuildInVolumeFormat, isBinary: boolean }, isovalues: VolumeIsovalueInfo[], options?: { entryId?: string | string[], isLazy?: boolean }) {
  266. const plugin = this.plugin;
  267. if (!plugin.dataFormats.get(format)) {
  268. throw new Error(`Unknown density format: ${format}`);
  269. }
  270. if (options?.isLazy) {
  271. const update = this.plugin.build();
  272. update.toRoot().apply(StateTransforms.Data.LazyVolume, {
  273. url,
  274. format,
  275. entryId: options?.entryId,
  276. isBinary,
  277. isovalues: isovalues.map(v => ({ alpha: 1, volumeIndex: 0, ...v }))
  278. });
  279. return update.commit();
  280. }
  281. return plugin.dataTransaction(async () => {
  282. const data = await plugin.builders.data.download({ url, isBinary }, { state: { isGhost: true } });
  283. const parsed = await plugin.dataFormats.get(format)!.parse(plugin, data, { entryId: options?.entryId });
  284. const firstVolume = (parsed.volume || parsed.volumes[0]) as StateObjectSelector<PluginStateObject.Volume.Data>;
  285. if (!firstVolume?.isOk) throw new Error('Failed to parse any volume.');
  286. const repr = plugin.build();
  287. for (const iso of isovalues) {
  288. repr
  289. .to(parsed.volumes?.[iso.volumeIndex ?? 0] ?? parsed.volume)
  290. .apply(StateTransforms.Representation.VolumeRepresentation3D, createVolumeRepresentationParams(this.plugin, firstVolume.data!, {
  291. type: 'isosurface',
  292. typeParams: { alpha: iso.alpha ?? 1, isoValue: iso.type === 'absolute' ? { kind: 'absolute', absoluteValue: iso.value } : { kind: 'relative', relativeValue: iso.value } },
  293. color: 'uniform',
  294. colorParams: { value: iso.color }
  295. }));
  296. }
  297. await repr.commit();
  298. });
  299. }
  300. handleResize() {
  301. this.plugin.layout.events.updated.next(void 0);
  302. }
  303. }
  304. export interface LoadStructureOptions {
  305. representationParams?: StructureRepresentationPresetProvider.CommonParams
  306. }
  307. export interface VolumeIsovalueInfo {
  308. type: 'absolute' | 'relative',
  309. value: number,
  310. color: Color,
  311. alpha?: number,
  312. volumeIndex?: number
  313. }