index.ts 15 KB

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