index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 { createPlugin, DefaultPluginSpec } from 'mol-plugin';
  7. import './index.html'
  8. import { PluginContext } from 'mol-plugin/context';
  9. import { PluginCommands } from 'mol-plugin/command';
  10. import { StateTransforms } from 'mol-plugin/state/transforms';
  11. import { StructureRepresentation3DHelpers } from 'mol-plugin/state/transforms/representation';
  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} from 'mol-state';
  16. import { EvolutionaryConservation } from './annotation';
  17. import { LoadParams, SupportedFormats, RepresentationStyle, ModelInfo } from './helpers';
  18. import { RxEventHelper } from 'mol-util/rx-event-helper';
  19. import { ControlsWrapper } from './ui/controls';
  20. import { PluginState } from 'mol-plugin/state';
  21. import { Canvas3D } from 'mol-canvas3d/canvas3d';
  22. require('mol-plugin/skin/light.scss')
  23. class MolStarPLYWrapper {
  24. static VERSION_MAJOR = 2;
  25. static VERSION_MINOR = 0;
  26. private _ev = RxEventHelper.create();
  27. readonly events = {
  28. modelInfo: this._ev<ModelInfo>()
  29. };
  30. plugin: PluginContext;
  31. init(target: string | HTMLElement) {
  32. this.plugin = createPlugin(typeof target === 'string' ? document.getElementById(target)! : target, {
  33. ...DefaultPluginSpec,
  34. layout: {
  35. initial: {
  36. isExpanded: false,
  37. showControls: false
  38. },
  39. controls: {
  40. right: ControlsWrapper
  41. }
  42. }
  43. });
  44. this.plugin.structureRepresentation.themeCtx.colorThemeRegistry.add(EvolutionaryConservation.Descriptor.name, EvolutionaryConservation.colorTheme!);
  45. this.plugin.lociLabels.addProvider(EvolutionaryConservation.labelProvider);
  46. this.plugin.customModelProperties.register(EvolutionaryConservation.propertyProvider);
  47. }
  48. get state() {
  49. return this.plugin.state.dataState;
  50. }
  51. get klick(){
  52. this.plugin.canvas3d.interaction.click.subscribe(e =>{
  53. console.log('atomID', e)
  54. aminoAcid = 169;
  55. })
  56. return 0
  57. }
  58. private download(b: StateBuilder.To<PSO.Root>, url: string) {
  59. return b.apply(StateTransforms.Data.Download, { url, isBinary: false })
  60. }
  61. private model(b: StateBuilder.To<PSO.Data.Binary | PSO.Data.String>, format: SupportedFormats, assemblyId: string) {
  62. const parsed = format === 'cif'
  63. ? b.apply(StateTransforms.Data.ParseCif).apply(StateTransforms.Model.TrajectoryFromMmCif)
  64. : b.apply(StateTransforms.Model.TrajectoryFromPDB);
  65. return parsed
  66. .apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 }, { ref: 'model' });
  67. }
  68. private plyData(b: StateBuilder.To<PSO.Data.String>) {
  69. return b.apply(StateTransforms.Data.ParsePly)
  70. .apply(StateTransforms.Model.ShapeFromPly)
  71. .apply(StateTransforms.Representation.ShapeRepresentation3D);
  72. }
  73. private structure(assemblyId: string) {
  74. const model = this.state.build().to('model');
  75. return model
  76. .apply(StateTransforms.Model.CustomModelProperties, { properties: [EvolutionaryConservation.Descriptor.name] }, { ref: 'props', props: { isGhost: false } })
  77. .apply(StateTransforms.Model.StructureAssemblyFromModel, { id: assemblyId || 'deposited' }, { ref: 'asm' });
  78. }
  79. private visual(ref: string, style?: RepresentationStyle) {
  80. const structure = this.getObj<PluginStateObject.Molecule.Structure>(ref);
  81. if (!structure) return;
  82. const root = this.state.build().to(ref);
  83. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-sequence' }, { ref: 'sequence' })
  84. .apply(StateTransforms.Representation.StructureRepresentation3D,
  85. StructureRepresentation3DHelpers.getDefaultParamsWithTheme(this.plugin,
  86. (style && style.sequence && style.sequence.kind) || 'cartoon',
  87. (style && style.sequence && style.sequence.coloring) || 'unit-index', structure),
  88. { ref: 'sequence-visual' });
  89. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-het' }, { ref: 'het' })
  90. .apply(StateTransforms.Representation.StructureRepresentation3D,
  91. StructureRepresentation3DHelpers.getDefaultParamsWithTheme(this.plugin,
  92. (style && style.hetGroups && style.hetGroups.kind) || 'ball-and-stick',
  93. (style && style.hetGroups && style.hetGroups.coloring), structure),
  94. { ref: 'het-visual' });
  95. root.apply(StateTransforms.Model.StructureComplexElement, { type: 'water' }, { ref: 'water' })
  96. .apply(StateTransforms.Representation.StructureRepresentation3D,
  97. StructureRepresentation3DHelpers.getDefaultParamsWithTheme(this.plugin,
  98. (style && style.water && style.water.kind) || 'ball-and-stick',
  99. (style && style.water && style.water.coloring), structure, { alpha: 0.51 }),
  100. { ref: 'water-visual' });
  101. return root;
  102. }
  103. private getObj<T extends StateObject>(ref: string): T['data'] {
  104. const state = this.state;
  105. const cell = state.select(ref)[0];
  106. if (!cell || !cell.obj) return void 0;
  107. return (cell.obj as T).data;
  108. }
  109. private async doInfo(checkPreferredAssembly: boolean) {
  110. const model = this.getObj<PluginStateObject.Molecule.Model>('model');
  111. if (!model) return;
  112. const info = await ModelInfo.get(this.plugin, model, checkPreferredAssembly)
  113. this.events.modelInfo.next(info);
  114. return info;
  115. }
  116. private applyState(tree: StateBuilder) {
  117. return PluginCommands.State.Update.dispatch(this.plugin, { state: this.plugin.state.dataState, tree });
  118. }
  119. private loadedParams: LoadParams = { plyurl: '', url: '', format: 'cif', assemblyId: '' };
  120. async load({ plyurl, url, format = 'cif', assemblyId = '', representationStyle }: LoadParams) {
  121. let loadType: 'full' | 'update' = 'full';
  122. const state = this.plugin.state.dataState;
  123. if (this.loadedParams.plyurl !== plyurl || this.loadedParams.url !== url || this.loadedParams.format !== format) {
  124. loadType = 'full';
  125. } else if (this.loadedParams.url === url) {
  126. if (state.select('asm').length > 0) loadType = 'update';
  127. }
  128. if (loadType === 'full') {
  129. await PluginCommands.State.RemoveObject.dispatch(this.plugin, { state, ref: state.tree.root.ref });
  130. // pdb/cif loading
  131. const modelTree = this.model(this.download(state.build().toRoot(), url), format, assemblyId);
  132. await this.applyState(modelTree);
  133. const info = await this.doInfo(true);
  134. const structureTree = this.structure((assemblyId === 'preferred' && info && info.preferredAssemblyId) || assemblyId);
  135. await this.applyState(structureTree);
  136. // ply loading
  137. const modelTreePly = this.plyData(this.download(state.build().toRoot(), plyurl));
  138. await this.applyState(modelTreePly);
  139. } else {
  140. const tree = state.build();
  141. tree.to('asm').update(StateTransforms.Model.StructureAssemblyFromModel, p => ({ ...p, id: assemblyId || 'deposited' }));
  142. await this.applyState(tree);
  143. }
  144. await this.updateStyle(representationStyle);
  145. this.loadedParams = { plyurl, url, format, assemblyId };
  146. PluginCommands.Camera.Reset.dispatch(this.plugin, { });
  147. }
  148. async updateStyle(style?: RepresentationStyle) {
  149. const tree = this.visual('asm', style);
  150. if (!tree) return;
  151. await PluginCommands.State.Update.dispatch(this.plugin, { state: this.plugin.state.dataState, tree });
  152. }
  153. setBackground(color: number) {
  154. PluginCommands.Canvas3D.SetSettings.dispatch(this.plugin, { settings: { backgroundColor: Color(color) } });
  155. }
  156. toggleSpin() {
  157. const trackball = this.plugin.canvas3d.props.trackball;
  158. const spinning = trackball.spin;
  159. PluginCommands.Canvas3D.SetSettings.dispatch(this.plugin, { settings: { trackball: { ...trackball, spin: !trackball.spin } } });
  160. if (!spinning) PluginCommands.Camera.Reset.dispatch(this.plugin, { });
  161. }
  162. animate = {
  163. modelIndex: {
  164. maxFPS: 8,
  165. onceForward: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'forward' } } }) },
  166. onceBackward: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'backward' } } }) },
  167. palindrome: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'palindrome', params: {} } }) },
  168. loop: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'loop', params: {} } }) },
  169. stop: () => this.plugin.state.animation.stop()
  170. }
  171. }
  172. coloring = {
  173. evolutionaryConservation: async () => {
  174. await this.updateStyle({ sequence: { kind: 'spacefill' } });
  175. const state = this.state;
  176. // const visuals = state.selectQ(q => q.ofType(PluginStateObject.Molecule.Structure.Representation3D).filter(c => c.transform.transformer === StateTransforms.Representation.StructureRepresentation3D));
  177. const tree = state.build();
  178. const colorTheme = { name: EvolutionaryConservation.Descriptor.name, params: this.plugin.structureRepresentation.themeCtx.colorThemeRegistry.get(EvolutionaryConservation.Descriptor.name).defaultValues };
  179. tree.to('sequence-visual').update(StateTransforms.Representation.StructureRepresentation3D, old => ({ ...old, colorTheme }));
  180. // for (const v of visuals) {
  181. // }
  182. await PluginCommands.State.Update.dispatch(this.plugin, { state, tree });
  183. }
  184. }
  185. snapshot = {
  186. get: () => {
  187. return this.plugin.state.getSnapshot();
  188. },
  189. set: (snapshot: PluginState.Snapshot) => {
  190. return this.plugin.state.setSnapshot(snapshot);
  191. },
  192. download: async (url: string) => {
  193. try {
  194. const data = await this.plugin.runTask(this.plugin.fetch({ url }));
  195. const snapshot = JSON.parse(data);
  196. await this.plugin.state.setSnapshot(snapshot);
  197. } catch (e) {
  198. console.log(e);
  199. }
  200. }
  201. }
  202. }
  203. (window as any).MolStarPLYWrapper = MolStarPLYWrapper;