index.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 { GeometryExport } from '../../extensions/geo-export';
  12. import { MAQualityAssessment } from '../../extensions/model-archive/quality-assessment/behavior';
  13. import { QualityAssessmentPLDDTPreset, QualityAssessmentQmeanPreset } from '../../extensions/model-archive/quality-assessment/behavior';
  14. import { QualityAssessment } from '../../extensions/model-archive/quality-assessment/prop';
  15. import { Mp4Export } from '../../extensions/mp4-export';
  16. import { PDBeStructureQualityReport } from '../../extensions/pdbe';
  17. import { RCSBAssemblySymmetry, RCSBValidationReport } from '../../extensions/rcsb';
  18. import { DownloadStructure, PdbDownloadProvider } from '../../mol-plugin-state/actions/structure';
  19. import { DownloadDensity } from '../../mol-plugin-state/actions/volume';
  20. import { PresetTrajectoryHierarchy } from '../../mol-plugin-state/builder/structure/hierarchy-preset';
  21. import { PresetStructureRepresentations, StructureRepresentationPresetProvider } from '../../mol-plugin-state/builder/structure/representation-preset';
  22. import { DataFormatProvider } from '../../mol-plugin-state/formats/provider';
  23. import { BuildInStructureFormat } from '../../mol-plugin-state/formats/structure';
  24. import { BuiltInTrajectoryFormat } from '../../mol-plugin-state/formats/trajectory';
  25. import { BuildInVolumeFormat } from '../../mol-plugin-state/formats/volume';
  26. import { createVolumeRepresentationParams } from '../../mol-plugin-state/helpers/volume-representation-params';
  27. import { PluginStateObject } from '../../mol-plugin-state/objects';
  28. import { StateTransforms } from '../../mol-plugin-state/transforms';
  29. import { TrajectoryFromModelAndCoordinates } from '../../mol-plugin-state/transforms/model';
  30. import { createPluginUI } from '../../mol-plugin-ui';
  31. import { PluginUIContext } from '../../mol-plugin-ui/context';
  32. import { DefaultPluginUISpec, PluginUISpec } from '../../mol-plugin-ui/spec';
  33. import { PluginCommands } from '../../mol-plugin/commands';
  34. import { PluginConfig } from '../../mol-plugin/config';
  35. import { PluginLayoutControlsDisplay } from '../../mol-plugin/layout';
  36. import { PluginSpec } from '../../mol-plugin/spec';
  37. import { PluginState } from '../../mol-plugin/state';
  38. import { StateObjectRef, StateObjectSelector } from '../../mol-state';
  39. import { Asset } from '../../mol-util/assets';
  40. import { Color } from '../../mol-util/color';
  41. import '../../mol-util/polyfill';
  42. import { ObjectKeys } from '../../mol-util/type-helpers';
  43. import './embedded.html';
  44. import './favicon.ico';
  45. import './index.html';
  46. require('mol-plugin-ui/skin/light.scss');
  47. export { PLUGIN_VERSION as version } from '../../mol-plugin/version';
  48. export { setDebugMode, setProductionMode } from '../../mol-util/debug';
  49. const CustomFormats = [
  50. ['g3d', G3dProvider] as const
  51. ];
  52. const Extensions = {
  53. 'cellpack': PluginSpec.Behavior(CellPack),
  54. 'dnatco-confal-pyramids': PluginSpec.Behavior(DnatcoConfalPyramids),
  55. 'pdbe-structure-quality-report': PluginSpec.Behavior(PDBeStructureQualityReport),
  56. 'rcsb-assembly-symmetry': PluginSpec.Behavior(RCSBAssemblySymmetry),
  57. 'rcsb-validation-report': PluginSpec.Behavior(RCSBValidationReport),
  58. 'anvil-membrane-orientation': PluginSpec.Behavior(ANVILMembraneOrientation),
  59. 'g3d': PluginSpec.Behavior(G3DFormat),
  60. 'mp4-export': PluginSpec.Behavior(Mp4Export),
  61. 'geo-export': PluginSpec.Behavior(GeometryExport),
  62. 'ma-quality-assessment': PluginSpec.Behavior(MAQualityAssessment),
  63. };
  64. const DefaultViewerOptions = {
  65. customFormats: CustomFormats as [string, DataFormatProvider][],
  66. extensions: ObjectKeys(Extensions),
  67. layoutIsExpanded: true,
  68. layoutShowControls: true,
  69. layoutShowRemoteState: true,
  70. layoutControlsDisplay: 'reactive' as PluginLayoutControlsDisplay,
  71. layoutShowSequence: true,
  72. layoutShowLog: true,
  73. layoutShowLeftPanel: true,
  74. collapseLeftPanel: false,
  75. collapseRightPanel: false,
  76. disableAntialiasing: PluginConfig.General.DisableAntialiasing.defaultValue,
  77. pixelScale: PluginConfig.General.PixelScale.defaultValue,
  78. pickScale: PluginConfig.General.PickScale.defaultValue,
  79. pickPadding: PluginConfig.General.PickPadding.defaultValue,
  80. enableWboit: PluginConfig.General.EnableWboit.defaultValue,
  81. viewportShowExpand: PluginConfig.Viewport.ShowExpand.defaultValue,
  82. viewportShowControls: PluginConfig.Viewport.ShowControls.defaultValue,
  83. viewportShowSettings: PluginConfig.Viewport.ShowSettings.defaultValue,
  84. viewportShowSelectionMode: PluginConfig.Viewport.ShowSelectionMode.defaultValue,
  85. viewportShowAnimation: PluginConfig.Viewport.ShowAnimation.defaultValue,
  86. pluginStateServer: PluginConfig.State.DefaultServer.defaultValue,
  87. volumeStreamingServer: PluginConfig.VolumeStreaming.DefaultServer.defaultValue,
  88. volumeStreamingDisabled: !PluginConfig.VolumeStreaming.Enabled.defaultValue,
  89. pdbProvider: PluginConfig.Download.DefaultPdbProvider.defaultValue,
  90. emdbProvider: PluginConfig.Download.DefaultEmdbProvider.defaultValue,
  91. };
  92. type ViewerOptions = typeof DefaultViewerOptions;
  93. export class Viewer {
  94. constructor(public plugin: PluginUIContext) {
  95. }
  96. static async create(elementOrId: string | HTMLElement, options: Partial<ViewerOptions> = {}) {
  97. const o = { ...DefaultViewerOptions, ...options };
  98. const defaultSpec = DefaultPluginUISpec();
  99. const spec: PluginUISpec = {
  100. actions: defaultSpec.actions,
  101. behaviors: [
  102. ...defaultSpec.behaviors,
  103. ...o.extensions.map(e => Extensions[e]),
  104. ],
  105. animations: [...defaultSpec.animations || []],
  106. customParamEditors: defaultSpec.customParamEditors,
  107. customFormats: o?.customFormats,
  108. layout: {
  109. initial: {
  110. isExpanded: o.layoutIsExpanded,
  111. showControls: o.layoutShowControls,
  112. controlsDisplay: o.layoutControlsDisplay,
  113. regionState: {
  114. bottom: 'full',
  115. left: o.collapseLeftPanel ? 'collapsed' : 'full',
  116. right: o.collapseRightPanel ? 'hidden' : 'full',
  117. top: 'full',
  118. }
  119. },
  120. },
  121. components: {
  122. ...defaultSpec.components,
  123. controls: {
  124. ...defaultSpec.components?.controls,
  125. top: o.layoutShowSequence ? undefined : 'none',
  126. bottom: o.layoutShowLog ? undefined : 'none',
  127. left: o.layoutShowLeftPanel ? undefined : 'none',
  128. },
  129. remoteState: o.layoutShowRemoteState ? 'default' : 'none',
  130. },
  131. config: [
  132. [PluginConfig.General.DisableAntialiasing, o.disableAntialiasing],
  133. [PluginConfig.General.PixelScale, o.pixelScale],
  134. [PluginConfig.General.PickScale, o.pickScale],
  135. [PluginConfig.General.PickPadding, o.pickPadding],
  136. [PluginConfig.General.EnableWboit, o.enableWboit],
  137. [PluginConfig.Viewport.ShowExpand, o.viewportShowExpand],
  138. [PluginConfig.Viewport.ShowControls, o.viewportShowControls],
  139. [PluginConfig.Viewport.ShowSettings, o.viewportShowSettings],
  140. [PluginConfig.Viewport.ShowSelectionMode, o.viewportShowSelectionMode],
  141. [PluginConfig.Viewport.ShowAnimation, o.viewportShowAnimation],
  142. [PluginConfig.State.DefaultServer, o.pluginStateServer],
  143. [PluginConfig.State.CurrentServer, o.pluginStateServer],
  144. [PluginConfig.VolumeStreaming.DefaultServer, o.volumeStreamingServer],
  145. [PluginConfig.VolumeStreaming.Enabled, !o.volumeStreamingDisabled],
  146. [PluginConfig.Download.DefaultPdbProvider, o.pdbProvider],
  147. [PluginConfig.Download.DefaultEmdbProvider, o.emdbProvider],
  148. [PluginConfig.Structure.DefaultRepresentationPreset, ViewerAutoPreset.id],
  149. ]
  150. };
  151. const element = typeof elementOrId === 'string'
  152. ? document.getElementById(elementOrId)
  153. : elementOrId;
  154. if (!element) throw new Error(`Could not get element with id '${elementOrId}'`);
  155. const plugin = await createPluginUI(element, spec, {
  156. onBeforeUIRender: plugin => {
  157. // the preset needs to be added before the UI renders otherwise
  158. // "Download Structure" wont be able to pick it up
  159. plugin.builders.structure.representation.registerPreset(ViewerAutoPreset);
  160. }
  161. });
  162. return new Viewer(plugin);
  163. }
  164. setRemoteSnapshot(id: string) {
  165. const url = `${this.plugin.config.get(PluginConfig.State.CurrentServer)}/get/${id}`;
  166. return PluginCommands.State.Snapshots.Fetch(this.plugin, { url });
  167. }
  168. loadSnapshotFromUrl(url: string, type: PluginState.SnapshotType) {
  169. return PluginCommands.State.Snapshots.OpenUrl(this.plugin, { url, type });
  170. }
  171. loadStructureFromUrl(url: string, format: BuiltInTrajectoryFormat = 'mmcif', isBinary = false, options?: LoadStructureOptions) {
  172. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  173. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  174. source: {
  175. name: 'url',
  176. params: {
  177. url: Asset.Url(url),
  178. format: format as any,
  179. isBinary,
  180. options: { ...params.source.params.options, representationParams: options?.representationParams as any },
  181. }
  182. }
  183. }));
  184. }
  185. async loadAllModelsOrAssemblyFromUrl(url: string, format: BuiltInTrajectoryFormat = 'mmcif', isBinary = false, options?: LoadStructureOptions) {
  186. const plugin = this.plugin;
  187. const data = await plugin.builders.data.download({ url, isBinary }, { state: { isGhost: true } });
  188. const trajectory = await plugin.builders.structure.parseTrajectory(data, format);
  189. await this.plugin.builders.structure.hierarchy.applyPreset(trajectory, 'all-models', { useDefaultIfSingleModel: true, representationPresetParams: options?.representationParams });
  190. }
  191. async loadStructureFromData(data: string | number[], format: BuiltInTrajectoryFormat, options?: { dataLabel?: string }) {
  192. const _data = await this.plugin.builders.data.rawData({ data, label: options?.dataLabel });
  193. const trajectory = await this.plugin.builders.structure.parseTrajectory(_data, format);
  194. await this.plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default');
  195. }
  196. loadPdb(pdb: string, options?: LoadStructureOptions) {
  197. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  198. const provider = this.plugin.config.get(PluginConfig.Download.DefaultPdbProvider)!;
  199. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  200. source: {
  201. name: 'pdb' as const,
  202. params: {
  203. provider: {
  204. id: pdb,
  205. server: {
  206. name: provider,
  207. params: PdbDownloadProvider[provider].defaultValue as any
  208. }
  209. },
  210. options: { ...params.source.params.options, representationParams: options?.representationParams as any },
  211. }
  212. }
  213. }));
  214. }
  215. loadPdbDev(pdbDev: string) {
  216. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  217. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  218. source: {
  219. name: 'pdb-dev' as const,
  220. params: {
  221. provider: {
  222. id: pdbDev,
  223. encoding: 'bcif',
  224. },
  225. options: params.source.params.options,
  226. }
  227. }
  228. }));
  229. }
  230. loadEmdb(emdb: string, options?: { detail?: number }) {
  231. const provider = this.plugin.config.get(PluginConfig.Download.DefaultEmdbProvider)!;
  232. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadDensity, {
  233. source: {
  234. name: 'pdb-emd-ds' as const,
  235. params: {
  236. provider: {
  237. id: emdb,
  238. server: provider,
  239. },
  240. detail: options?.detail ?? 3,
  241. }
  242. }
  243. }));
  244. }
  245. loadAlphaFoldDb(afdb: string) {
  246. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  247. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  248. source: {
  249. name: 'alphafolddb' as const,
  250. params: {
  251. id: afdb,
  252. options: {
  253. ...params.source.params.options,
  254. representation: 'preset-structure-representation-ma-quality-assessment-plddt'
  255. },
  256. }
  257. }
  258. }));
  259. }
  260. loadModelArchive(id: string) {
  261. const params = DownloadStructure.createDefaultParams(this.plugin.state.data.root.obj!, this.plugin);
  262. return this.plugin.runTask(this.plugin.state.data.applyAction(DownloadStructure, {
  263. source: {
  264. name: 'modelarchive' as const,
  265. params: {
  266. id,
  267. options: params.source.params.options,
  268. }
  269. }
  270. }));
  271. }
  272. /**
  273. * @example Load X-ray density from volume server
  274. viewer.loadVolumeFromUrl({
  275. url: 'https://www.ebi.ac.uk/pdbe/densities/x-ray/1tqn/cell?detail=3',
  276. format: 'dscif',
  277. isBinary: true
  278. }, [{
  279. type: 'relative',
  280. value: 1.5,
  281. color: 0x3362B2
  282. }, {
  283. type: 'relative',
  284. value: 3,
  285. color: 0x33BB33,
  286. volumeIndex: 1
  287. }, {
  288. type: 'relative',
  289. value: -3,
  290. color: 0xBB3333,
  291. volumeIndex: 1
  292. }], {
  293. entryId: ['2FO-FC', 'FO-FC'],
  294. isLazy: true
  295. });
  296. * *********************
  297. * @example Load EM density from volume server
  298. viewer.loadVolumeFromUrl({
  299. url: 'https://maps.rcsb.org/em/emd-30210/cell?detail=6',
  300. format: 'dscif',
  301. isBinary: true
  302. }, [{
  303. type: 'relative',
  304. value: 1,
  305. color: 0x3377aa
  306. }], {
  307. entryId: 'EMD-30210',
  308. isLazy: true
  309. });
  310. */
  311. async loadVolumeFromUrl({ url, format, isBinary }: { url: string, format: BuildInVolumeFormat, isBinary: boolean }, isovalues: VolumeIsovalueInfo[], options?: { entryId?: string | string[], isLazy?: boolean }) {
  312. const plugin = this.plugin;
  313. if (!plugin.dataFormats.get(format)) {
  314. throw new Error(`Unknown density format: ${format}`);
  315. }
  316. if (options?.isLazy) {
  317. const update = this.plugin.build();
  318. update.toRoot().apply(StateTransforms.Data.LazyVolume, {
  319. url,
  320. format,
  321. entryId: options?.entryId,
  322. isBinary,
  323. isovalues: isovalues.map(v => ({ alpha: 1, volumeIndex: 0, ...v }))
  324. });
  325. return update.commit();
  326. }
  327. return plugin.dataTransaction(async () => {
  328. const data = await plugin.builders.data.download({ url, isBinary }, { state: { isGhost: true } });
  329. const parsed = await plugin.dataFormats.get(format)!.parse(plugin, data, { entryId: options?.entryId });
  330. const firstVolume = (parsed.volume || parsed.volumes[0]) as StateObjectSelector<PluginStateObject.Volume.Data>;
  331. if (!firstVolume?.isOk) throw new Error('Failed to parse any volume.');
  332. const repr = plugin.build();
  333. for (const iso of isovalues) {
  334. repr
  335. .to(parsed.volumes?.[iso.volumeIndex ?? 0] ?? parsed.volume)
  336. .apply(StateTransforms.Representation.VolumeRepresentation3D, createVolumeRepresentationParams(this.plugin, firstVolume.data!, {
  337. type: 'isosurface',
  338. typeParams: { alpha: iso.alpha ?? 1, isoValue: iso.type === 'absolute' ? { kind: 'absolute', absoluteValue: iso.value } : { kind: 'relative', relativeValue: iso.value } },
  339. color: 'uniform',
  340. colorParams: { value: iso.color }
  341. }));
  342. }
  343. await repr.commit();
  344. });
  345. }
  346. /**
  347. * @example
  348. * viewer.loadTrajectory({
  349. * model: { kind: 'model-url', url: 'villin.gro', format: 'gro' },
  350. * coordinates: { kind: 'coordinates-url', url: 'villin.xtc', format: 'xtc', isBinary: true },
  351. * preset: 'all-models' // or 'default'
  352. * });
  353. */
  354. async loadTrajectory(params: LoadTrajectoryParams) {
  355. const plugin = this.plugin;
  356. let model: StateObjectSelector, coords: StateObjectSelector;
  357. if (params.model.kind === 'model-data' || params.model.kind === 'model-url') {
  358. const data = params.model.kind === 'model-data'
  359. ? await plugin.builders.data.rawData({ data: params.model.data, label: params.modelLabel })
  360. : await plugin.builders.data.download({ url: params.model.url, isBinary: params.model.isBinary, label: params.modelLabel });
  361. const trajectory = await plugin.builders.structure.parseTrajectory(data, params.model.format ?? 'mmcif');
  362. model = await plugin.builders.structure.createModel(trajectory);
  363. } else {
  364. const data = params.model.kind === 'topology-data'
  365. ? await plugin.builders.data.rawData({ data: params.model.data, label: params.modelLabel })
  366. : await plugin.builders.data.download({ url: params.model.url, isBinary: params.model.isBinary, label: params.modelLabel });
  367. const provider = plugin.dataFormats.get(params.model.format);
  368. model = await provider!.parse(plugin, data);
  369. }
  370. {
  371. const data = params.coordinates.kind === 'coordinates-data'
  372. ? await plugin.builders.data.rawData({ data: params.coordinates.data, label: params.coordinatesLabel })
  373. : await plugin.builders.data.download({ url: params.coordinates.url, isBinary: params.coordinates.isBinary, label: params.coordinatesLabel });
  374. const provider = plugin.dataFormats.get(params.coordinates.format);
  375. coords = await provider!.parse(plugin, data);
  376. }
  377. const trajectory = await plugin.build().toRoot()
  378. .apply(TrajectoryFromModelAndCoordinates, {
  379. modelRef: model.ref,
  380. coordinatesRef: coords.ref
  381. }, { dependsOn: [model.ref, coords.ref] })
  382. .commit();
  383. const preset = await plugin.builders.structure.hierarchy.applyPreset(trajectory, params.preset ?? 'default');
  384. return { model, coords, preset };
  385. }
  386. handleResize() {
  387. this.plugin.layout.events.updated.next(void 0);
  388. }
  389. }
  390. export interface LoadStructureOptions {
  391. representationParams?: StructureRepresentationPresetProvider.CommonParams
  392. }
  393. export interface VolumeIsovalueInfo {
  394. type: 'absolute' | 'relative',
  395. value: number,
  396. color: Color,
  397. alpha?: number,
  398. volumeIndex?: number
  399. }
  400. export interface LoadTrajectoryParams {
  401. model: { kind: 'model-url', url: string, format?: BuiltInTrajectoryFormat /* mmcif */, isBinary?: boolean }
  402. | { kind: 'model-data', data: string | number[] | ArrayBuffer | Uint8Array, format?: BuiltInTrajectoryFormat /* mmcif */ }
  403. | { kind: 'topology-url', url: string, format: BuildInStructureFormat, isBinary?: boolean }
  404. | { kind: 'topology-data', data: string | number[] | ArrayBuffer | Uint8Array, format: BuildInStructureFormat },
  405. modelLabel?: string,
  406. coordinates: { kind: 'coordinates-url', url: string, format: BuildInStructureFormat, isBinary?: boolean }
  407. | { kind: 'coordinates-data', data: string | number[] | ArrayBuffer | Uint8Array, format: BuildInStructureFormat },
  408. coordinatesLabel?: string,
  409. preset?: keyof PresetTrajectoryHierarchy
  410. }
  411. export const ViewerAutoPreset = StructureRepresentationPresetProvider({
  412. id: 'preset-structure-representation-viewer-auto',
  413. display: {
  414. name: 'Automatic (w/ Annotation)', group: 'Annotation',
  415. description: 'Show standard automatic representation but colored by quality assessment (if available in the model).'
  416. },
  417. isApplicable(a) {
  418. return (
  419. !!a.data.models.some(m => QualityAssessment.isApplicable(m, 'pLDDT')) ||
  420. !!a.data.models.some(m => QualityAssessment.isApplicable(m, 'qmean'))
  421. );
  422. },
  423. params: () => StructureRepresentationPresetProvider.CommonParams,
  424. async apply(ref, params, plugin) {
  425. const structureCell = StateObjectRef.resolveAndCheck(plugin.state.data, ref);
  426. const structure = structureCell?.obj?.data;
  427. if (!structureCell || !structure) return {};
  428. if (!!structure.models.some(m => QualityAssessment.isApplicable(m, 'pLDDT'))) {
  429. return await QualityAssessmentPLDDTPreset.apply(ref, params, plugin);
  430. } else if (!!structure.models.some(m => QualityAssessment.isApplicable(m, 'qmean'))) {
  431. return await QualityAssessmentQmeanPreset.apply(ref, params, plugin);
  432. } else {
  433. return await PresetStructureRepresentations.auto.apply(ref, params, plugin);
  434. }
  435. }
  436. });