index.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /**
  2. * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import * as ReactDOM from 'react-dom';
  7. import { createPlugin, DefaultPluginSpec } from '../../mol-plugin';
  8. import './index.html';
  9. import { PluginContext } from '../../mol-plugin/context';
  10. import { PluginCommands } from '../../mol-plugin/commands';
  11. import { StateTransforms } from '../../mol-plugin-state/transforms';
  12. import { Color } from '../../mol-util/color';
  13. import { PluginStateObject as PSO, PluginStateObject } from '../../mol-plugin-state/objects';
  14. import { AnimateModelIndex } from '../../mol-plugin-state/animation/built-in';
  15. import { StateBuilder, StateObject, StateSelection } from '../../mol-state';
  16. import { EvolutionaryConservation } from './annotation';
  17. import { LoadParams, SupportedFormats, RepresentationStyle, ModelInfo, StateElements } from './helpers';
  18. import { RxEventHelper } from '../../mol-util/rx-event-helper';
  19. import { volumeStreamingControls } from './ui/controls';
  20. import { PluginState } from '../../mol-plugin/state';
  21. import { Scheduler } from '../../mol-task';
  22. import { createProteopediaCustomTheme } from './coloring';
  23. import { MolScriptBuilder as MS } from '../../mol-script/language/builder';
  24. import { ColorNames } from '../../mol-util/color/names';
  25. import { InitVolumeStreaming, CreateVolumeStreamingInfo } from '../../mol-plugin/behavior/dynamic/volume-streaming/transformers';
  26. import { DefaultCanvas3DParams, Canvas3DProps } from '../../mol-canvas3d/canvas3d';
  27. import { createStructureRepresentationParams } from '../../mol-plugin-state/helpers/structure-representation-params';
  28. import { download } from '../../mol-util/download';
  29. import { getFormattedTime } from '../../mol-util/date';
  30. import { Asset } from '../../mol-util/assets';
  31. require('../../mol-plugin-ui/skin/light.scss');
  32. class MolStarProteopediaWrapper {
  33. static VERSION_MAJOR = 5;
  34. static VERSION_MINOR = 4;
  35. private _ev = RxEventHelper.create();
  36. readonly events = {
  37. modelInfo: this._ev<ModelInfo>()
  38. };
  39. plugin: PluginContext;
  40. init(target: string | HTMLElement, options?: {
  41. customColorList?: number[]
  42. }) {
  43. this.plugin = createPlugin(typeof target === 'string' ? document.getElementById(target)! : target, {
  44. ...DefaultPluginSpec,
  45. animations: [
  46. AnimateModelIndex
  47. ],
  48. layout: {
  49. initial: {
  50. isExpanded: false,
  51. showControls: false
  52. }
  53. },
  54. components: {
  55. remoteState: 'none'
  56. }
  57. });
  58. const customColoring = createProteopediaCustomTheme((options && options.customColorList) || []);
  59. this.plugin.representation.structure.themes.colorThemeRegistry.add(customColoring);
  60. this.plugin.representation.structure.themes.colorThemeRegistry.add(EvolutionaryConservation.colorThemeProvider!);
  61. this.plugin.managers.lociLabels.addProvider(EvolutionaryConservation.labelProvider!);
  62. this.plugin.customModelProperties.register(EvolutionaryConservation.propertyProvider, true);
  63. }
  64. get state() {
  65. return this.plugin.state.data;
  66. }
  67. private download(b: StateBuilder.To<PSO.Root>, url: string, isBinary: boolean) {
  68. return b.apply(StateTransforms.Data.Download, { url: Asset.Url(url), isBinary });
  69. }
  70. private model(b: StateBuilder.To<PSO.Data.Binary | PSO.Data.String>, format: SupportedFormats) {
  71. const parsed = format === 'cif'
  72. ? b.apply(StateTransforms.Data.ParseCif).apply(StateTransforms.Model.TrajectoryFromMmCif)
  73. : b.apply(StateTransforms.Model.TrajectoryFromPDB);
  74. return parsed
  75. .apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 }, { ref: StateElements.Model });
  76. }
  77. private structure(assemblyId: string) {
  78. const model = this.state.build().to(StateElements.Model);
  79. const props = {
  80. type: {
  81. name: 'assembly' as const,
  82. params: { id: assemblyId || 'deposited' }
  83. }
  84. };
  85. const s = model
  86. .apply(StateTransforms.Model.StructureFromModel, props, { ref: StateElements.Assembly });
  87. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-sequence' }, { ref: StateElements.Sequence });
  88. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-het' }, { ref: StateElements.Het });
  89. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'water' }, { ref: StateElements.Water });
  90. return s;
  91. }
  92. private visual(_style?: RepresentationStyle, partial?: boolean) {
  93. const structure = this.getObj<PluginStateObject.Molecule.Structure>(StateElements.Assembly);
  94. if (!structure) return;
  95. const style = _style || { };
  96. const update = this.state.build();
  97. if (!partial || (partial && style.sequence)) {
  98. const root = update.to(StateElements.Sequence);
  99. if (style.sequence && style.sequence.hide) {
  100. root.delete(StateElements.SequenceVisual);
  101. } else {
  102. root.applyOrUpdate(StateElements.SequenceVisual, StateTransforms.Representation.StructureRepresentation3D,
  103. createStructureRepresentationParams(this.plugin, structure, {
  104. type: (style.sequence && style.sequence.kind) || 'cartoon',
  105. color: (style.sequence && style.sequence.coloring) || 'unit-index'
  106. }));
  107. }
  108. }
  109. if (!partial || (partial && style.hetGroups)) {
  110. const root = update.to(StateElements.Het);
  111. if (style.hetGroups && style.hetGroups.hide) {
  112. root.delete(StateElements.HetVisual);
  113. } else {
  114. if (style.hetGroups && style.hetGroups.hide) {
  115. root.delete(StateElements.HetVisual);
  116. } else {
  117. root.applyOrUpdate(StateElements.HetVisual, StateTransforms.Representation.StructureRepresentation3D,
  118. createStructureRepresentationParams(this.plugin, structure, {
  119. type: (style.hetGroups && style.hetGroups.kind) || 'ball-and-stick',
  120. color: style.hetGroups && style.hetGroups.coloring
  121. }));
  122. }
  123. }
  124. }
  125. if (!partial || (partial && style.snfg3d)) {
  126. const root = update.to(StateElements.Het);
  127. if (style.hetGroups && style.hetGroups.hide) {
  128. root.delete(StateElements.HetVisual);
  129. } else {
  130. if (style.snfg3d && style.snfg3d.hide) {
  131. root.delete(StateElements.Het3DSNFG);
  132. } else {
  133. root.applyOrUpdate(StateElements.Het3DSNFG, StateTransforms.Representation.StructureRepresentation3D,
  134. createStructureRepresentationParams(this.plugin, structure, { type: 'carbohydrate' }));
  135. }
  136. }
  137. }
  138. if (!partial || (partial && style.water)) {
  139. const root = update.to(StateElements.Water);
  140. if (style.water && style.water.hide) {
  141. root.delete(StateElements.WaterVisual);
  142. } else {
  143. root.applyOrUpdate(StateElements.WaterVisual, StateTransforms.Representation.StructureRepresentation3D,
  144. createStructureRepresentationParams(this.plugin, structure, {
  145. type: (style.water && style.water.kind) || 'ball-and-stick',
  146. typeParams: { alpha: 0.51 },
  147. color: style.water && style.water.coloring
  148. }));
  149. }
  150. }
  151. return update;
  152. }
  153. private getObj<T extends StateObject>(ref: string): T['data'] {
  154. const state = this.state;
  155. const cell = state.select(ref)[0];
  156. if (!cell || !cell.obj) return void 0;
  157. return (cell.obj as T).data;
  158. }
  159. private async doInfo(checkPreferredAssembly: boolean) {
  160. const model = this.getObj<PluginStateObject.Molecule.Model>('model');
  161. if (!model) return;
  162. const info = await ModelInfo.get(this.plugin, model, checkPreferredAssembly);
  163. this.events.modelInfo.next(info);
  164. return info;
  165. }
  166. private applyState(tree: StateBuilder) {
  167. return PluginCommands.State.Update(this.plugin, { state: this.plugin.state.data, tree });
  168. }
  169. private emptyLoadedParams: LoadParams = { url: '', format: 'cif', isBinary: false, assemblyId: '' };
  170. private loadedParams: LoadParams = { url: '', format: 'cif', isBinary: false, assemblyId: '' };
  171. async load({ url, format = 'cif', assemblyId = 'deposited', isBinary = false, representationStyle }: LoadParams) {
  172. let loadType: 'full' | 'update' = 'full';
  173. const state = this.plugin.state.data;
  174. if (this.loadedParams.url !== url || this.loadedParams.format !== format) {
  175. loadType = 'full';
  176. } else if (this.loadedParams.url === url) {
  177. if (state.select(StateElements.Assembly).length > 0) loadType = 'update';
  178. }
  179. if (loadType === 'full') {
  180. await PluginCommands.State.RemoveObject(this.plugin, { state, ref: state.tree.root.ref });
  181. const modelTree = this.model(this.download(state.build().toRoot(), url, isBinary), format);
  182. await this.applyState(modelTree);
  183. const info = await this.doInfo(true);
  184. const asmId = (assemblyId === 'preferred' && info && info.preferredAssemblyId) || assemblyId;
  185. const structureTree = this.structure(asmId);
  186. await this.applyState(structureTree);
  187. } else {
  188. const tree = state.build();
  189. const info = await this.doInfo(true);
  190. const asmId = (assemblyId === 'preferred' && info && info.preferredAssemblyId) || assemblyId;
  191. const props = {
  192. type: {
  193. name: 'assembly' as const,
  194. params: { id: asmId || 'deposited' }
  195. }
  196. };
  197. tree.to(StateElements.Assembly).update(StateTransforms.Model.StructureFromModel, p => ({ ...p, ...props }));
  198. await this.applyState(tree);
  199. }
  200. await this.updateStyle(representationStyle);
  201. this.loadedParams = { url, format, assemblyId };
  202. Scheduler.setImmediate(() => PluginCommands.Camera.Reset(this.plugin, { }));
  203. }
  204. async updateStyle(style?: RepresentationStyle, partial?: boolean) {
  205. const tree = this.visual(style, partial);
  206. if (!tree) return;
  207. await PluginCommands.State.Update(this.plugin, { state: this.plugin.state.data, tree });
  208. }
  209. setBackground(color: number) {
  210. if (!this.plugin.canvas3d) return;
  211. const renderer = this.plugin.canvas3d.props.renderer;
  212. PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: { renderer: { ...renderer, backgroundColor: Color(color) } } });
  213. }
  214. toggleSpin() {
  215. if (!this.plugin.canvas3d) return;
  216. const trackball = this.plugin.canvas3d.props.trackball;
  217. const spinning = trackball.spin;
  218. PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: { trackball: { ...trackball, spin: !trackball.spin } } });
  219. if (!spinning) PluginCommands.Camera.Reset(this.plugin, { });
  220. }
  221. viewport = {
  222. setSettings: (settings?: Canvas3DProps) => {
  223. PluginCommands.Canvas3D.SetSettings(this.plugin, {
  224. settings: settings || DefaultCanvas3DParams
  225. });
  226. }
  227. };
  228. camera = {
  229. toggleSpin: () => this.toggleSpin(),
  230. resetPosition: () => PluginCommands.Camera.Reset(this.plugin, { })
  231. }
  232. animate = {
  233. modelIndex: {
  234. maxFPS: 8,
  235. onceForward: () => { this.plugin.managers.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'forward' } } }); },
  236. onceBackward: () => { this.plugin.managers.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'backward' } } }); },
  237. palindrome: () => { this.plugin.managers.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'palindrome', params: {} } }); },
  238. loop: () => { this.plugin.managers.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'loop', params: {} } }); },
  239. stop: () => this.plugin.managers.animation.stop()
  240. }
  241. }
  242. coloring = {
  243. evolutionaryConservation: async (params?: { sequence?: boolean, het?: boolean, keepStyle?: boolean }) => {
  244. if (!params || !params.keepStyle) {
  245. await this.updateStyle({ sequence: { kind: 'spacefill' } }, true);
  246. }
  247. const state = this.state;
  248. const tree = state.build();
  249. const colorTheme = { name: EvolutionaryConservation.propertyProvider.descriptor.name, params: this.plugin.representation.structure.themes.colorThemeRegistry.get(EvolutionaryConservation.propertyProvider.descriptor.name).defaultValues };
  250. if (!params || !!params.sequence) {
  251. tree.to(StateElements.SequenceVisual).update(StateTransforms.Representation.StructureRepresentation3D, old => ({ ...old, colorTheme }));
  252. }
  253. if (params && !!params.het) {
  254. tree.to(StateElements.HetVisual).update(StateTransforms.Representation.StructureRepresentation3D, old => ({ ...old, colorTheme }));
  255. }
  256. await PluginCommands.State.Update(this.plugin, { state, tree });
  257. }
  258. }
  259. private experimentalDataElement?: Element = void 0;
  260. experimentalData = {
  261. init: async (parent: Element) => {
  262. const asm = this.state.select(StateElements.Assembly)[0].obj!;
  263. const params = InitVolumeStreaming.createDefaultParams(asm, this.plugin);
  264. params.options.behaviorRef = StateElements.VolumeStreaming;
  265. params.defaultView = 'box';
  266. params.options.channelParams['fo-fc(+ve)'] = { wireframe: true };
  267. params.options.channelParams['fo-fc(-ve)'] = { wireframe: true };
  268. await this.plugin.runTask(this.state.applyAction(InitVolumeStreaming, params, StateElements.Assembly));
  269. this.experimentalDataElement = parent;
  270. volumeStreamingControls(this.plugin, parent);
  271. },
  272. remove: () => {
  273. const r = this.state.select(StateSelection.Generators.ofTransformer(CreateVolumeStreamingInfo))[0];
  274. if (!r) return;
  275. PluginCommands.State.RemoveObject(this.plugin, { state: this.state, ref: r.transform.ref });
  276. if (this.experimentalDataElement) {
  277. ReactDOM.unmountComponentAtNode(this.experimentalDataElement);
  278. this.experimentalDataElement = void 0;
  279. }
  280. }
  281. }
  282. hetGroups = {
  283. reset: () => {
  284. const update = this.state.build().delete(StateElements.HetGroupFocusGroup);
  285. PluginCommands.State.Update(this.plugin, { state: this.state, tree: update });
  286. PluginCommands.Camera.Reset(this.plugin, { });
  287. },
  288. focusFirst: async (compId: string, options?: { hideLabels: boolean, doNotLabelWaters: boolean }) => {
  289. if (!this.state.transforms.has(StateElements.Assembly)) return;
  290. await PluginCommands.Camera.Reset(this.plugin, { });
  291. const update = this.state.build();
  292. update.delete(StateElements.HetGroupFocusGroup);
  293. const core = MS.struct.filter.first([
  294. MS.struct.generator.atomGroups({
  295. 'residue-test': MS.core.rel.eq([MS.struct.atomProperty.macromolecular.label_comp_id(), compId]),
  296. 'group-by': MS.core.str.concat([MS.struct.atomProperty.core.operatorName(), MS.struct.atomProperty.macromolecular.residueKey()])
  297. })
  298. ]);
  299. const surroundings = MS.struct.modifier.includeSurroundings({ 0: core, radius: 5, 'as-whole-residues': true });
  300. const group = update.to(StateElements.Assembly).group(StateTransforms.Misc.CreateGroup, { label: compId }, { ref: StateElements.HetGroupFocusGroup });
  301. const asm = this.state.select(StateElements.Assembly)[0].obj as PluginStateObject.Molecule.Structure;
  302. const coreSel = group.apply(StateTransforms.Model.StructureSelectionFromExpression, { label: 'Core', expression: core }, { ref: StateElements.HetGroupFocus });
  303. coreSel.apply(StateTransforms.Representation.StructureRepresentation3D, createStructureRepresentationParams(this.plugin, asm.data, {
  304. type: 'ball-and-stick'
  305. }));
  306. coreSel.apply(StateTransforms.Representation.StructureRepresentation3D, createStructureRepresentationParams(this.plugin, asm.data, {
  307. type: 'label',
  308. typeParams: { level: 'element' }
  309. }), { tags: ['proteopedia-labels'] });
  310. group.apply(StateTransforms.Model.StructureSelectionFromExpression, { label: 'Surroundings', expression: surroundings })
  311. .apply(StateTransforms.Representation.StructureRepresentation3D, createStructureRepresentationParams(this.plugin, asm.data, {
  312. type: 'ball-and-stick',
  313. color: 'uniform', colorParams: { value: ColorNames.gray },
  314. size: 'uniform', sizeParams: { value: 0.33 }
  315. }));
  316. if (!options?.hideLabels) {
  317. // Labels
  318. const waters = MS.struct.generator.atomGroups({
  319. 'entity-test': MS.core.rel.eq([MS.struct.atomProperty.macromolecular.entityType(), 'water']),
  320. });
  321. const exclude = options?.doNotLabelWaters ? MS.struct.combinator.merge([core, waters]) : core;
  322. const onlySurroundings = MS.struct.modifier.exceptBy({ 0: surroundings, by: exclude });
  323. group.apply(StateTransforms.Model.StructureSelectionFromExpression, { label: 'Surroundings (only)', expression: onlySurroundings })
  324. .apply(StateTransforms.Representation.StructureRepresentation3D, createStructureRepresentationParams(this.plugin, asm.data, {
  325. type: 'label',
  326. typeParams: { level: 'residue' }
  327. }), { tags: ['proteopedia-labels'] }); // the tag can later be used to toggle the labels
  328. }
  329. await PluginCommands.State.Update(this.plugin, { state: this.state, tree: update });
  330. const focus = (this.state.select(StateElements.HetGroupFocus)[0].obj as PluginStateObject.Molecule.Structure).data;
  331. const sphere = focus.boundary.sphere;
  332. const radius = Math.max(sphere.radius, 5);
  333. const snapshot = this.plugin.canvas3d!.camera.getFocus(sphere.center, radius);
  334. PluginCommands.Camera.SetSnapshot(this.plugin, { snapshot, durationMs: 250 });
  335. }
  336. }
  337. snapshot = {
  338. get: (params?: PluginState.SnapshotParams) => {
  339. return this.plugin.state.getSnapshot(params);
  340. },
  341. set: (snapshot: PluginState.Snapshot) => {
  342. return this.plugin.state.setSnapshot(snapshot);
  343. },
  344. download: async (type: 'molj' | 'molx' = 'molj', params?: PluginState.SnapshotParams) => {
  345. const data = await this.plugin.managers.snapshot.serialize({ type, params });
  346. download(data, `mol-star_state_${(name || getFormattedTime())}.${type}`);
  347. },
  348. fetch: async (url: string, type: 'molj' | 'molx' = 'molj') => {
  349. try {
  350. const data = await this.plugin.runTask(this.plugin.fetch({ url, type: 'binary' }));
  351. this.loadedParams = { ...this.emptyLoadedParams };
  352. await this.plugin.managers.snapshot.open(new File([data], `state.${type}`));
  353. } catch (e) {
  354. console.log(e);
  355. }
  356. }
  357. }
  358. }
  359. (window as any).MolStarProteopediaWrapper = MolStarProteopediaWrapper;