app.ts 22 KB

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