index.ts 22 KB

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