index.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 { ControlsWrapper, 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 { Vec3 } from 'mol-math/linear-algebra';
  29. // import { ParamDefinition } from 'mol-util/param-definition';
  30. // import { Text } from 'mol-geo/geometry/text/text';
  31. require('../../mol-plugin-ui/skin/light.scss')
  32. class MolStarProteopediaWrapper {
  33. static VERSION_MAJOR = 4;
  34. static VERSION_MINOR = 0;
  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. controls: {
  54. right: ControlsWrapper
  55. }
  56. },
  57. components: {
  58. remoteState: 'none'
  59. }
  60. });
  61. const customColoring = createProteopediaCustomTheme((options && options.customColorList) || []);
  62. this.plugin.structureRepresentation.themeCtx.colorThemeRegistry.add(customColoring);
  63. this.plugin.structureRepresentation.themeCtx.colorThemeRegistry.add(EvolutionaryConservation.colorThemeProvider!);
  64. this.plugin.managers.lociLabels.addProvider(EvolutionaryConservation.labelProvider!);
  65. this.plugin.customModelProperties.register(EvolutionaryConservation.propertyProvider, true);
  66. }
  67. get state() {
  68. return this.plugin.state.dataState;
  69. }
  70. private download(b: StateBuilder.To<PSO.Root>, url: string) {
  71. return b.apply(StateTransforms.Data.Download, { url, isBinary: false })
  72. }
  73. private model(b: StateBuilder.To<PSO.Data.Binary | PSO.Data.String>, format: SupportedFormats) {
  74. const parsed = format === 'cif'
  75. ? b.apply(StateTransforms.Data.ParseCif).apply(StateTransforms.Model.TrajectoryFromMmCif)
  76. : b.apply(StateTransforms.Model.TrajectoryFromPDB);
  77. return parsed
  78. .apply(StateTransforms.Model.ModelFromTrajectory, { modelIndex: 0 }, { ref: StateElements.Model });
  79. }
  80. private structure(assemblyId: string) {
  81. const model = this.state.build().to(StateElements.Model);
  82. const props = {
  83. type: {
  84. name: 'assembly' as const,
  85. params: { id: assemblyId || 'deposited' }
  86. }
  87. }
  88. const s = model
  89. .apply(StateTransforms.Model.CustomModelProperties, { autoAttach: [EvolutionaryConservation.propertyProvider.descriptor.name], properties: {} }, { ref: StateElements.ModelProps, state: { isGhost: false } })
  90. .apply(StateTransforms.Model.StructureFromModel, props, { ref: StateElements.Assembly });
  91. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-sequence' }, { ref: StateElements.Sequence });
  92. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'atomic-het' }, { ref: StateElements.Het });
  93. s.apply(StateTransforms.Model.StructureComplexElement, { type: 'water' }, { ref: StateElements.Water });
  94. return s;
  95. }
  96. private visual(_style?: RepresentationStyle, partial?: boolean) {
  97. const structure = this.getObj<PluginStateObject.Molecule.Structure>(StateElements.Assembly);
  98. if (!structure) return;
  99. const style = _style || { };
  100. const update = this.state.build();
  101. if (!partial || (partial && style.sequence)) {
  102. const root = update.to(StateElements.Sequence);
  103. if (style.sequence && style.sequence.hide) {
  104. root.delete(StateElements.SequenceVisual);
  105. } else {
  106. root.applyOrUpdate(StateElements.SequenceVisual, StateTransforms.Representation.StructureRepresentation3D,
  107. createStructureRepresentationParams(this.plugin, structure, {
  108. type: (style.sequence && style.sequence.kind) || 'cartoon',
  109. color: (style.sequence && style.sequence.coloring) || 'unit-index'
  110. }));
  111. }
  112. }
  113. if (!partial || (partial && style.hetGroups)) {
  114. const root = update.to(StateElements.Het);
  115. if (style.hetGroups && style.hetGroups.hide) {
  116. root.delete(StateElements.HetVisual);
  117. } else {
  118. if (style.hetGroups && style.hetGroups.hide) {
  119. root.delete(StateElements.HetVisual);
  120. } else {
  121. root.applyOrUpdate(StateElements.HetVisual, StateTransforms.Representation.StructureRepresentation3D,
  122. createStructureRepresentationParams(this.plugin, structure, {
  123. type: (style.hetGroups && style.hetGroups.kind) || 'ball-and-stick',
  124. color: style.hetGroups && style.hetGroups.coloring
  125. }));
  126. }
  127. }
  128. }
  129. if (!partial || (partial && style.snfg3d)) {
  130. const root = update.to(StateElements.Het);
  131. if (style.hetGroups && style.hetGroups.hide) {
  132. root.delete(StateElements.HetVisual);
  133. } else {
  134. if (style.snfg3d && style.snfg3d.hide) {
  135. root.delete(StateElements.Het3DSNFG);
  136. } else {
  137. root.applyOrUpdate(StateElements.Het3DSNFG, StateTransforms.Representation.StructureRepresentation3D,
  138. createStructureRepresentationParams(this.plugin, structure, { type: 'carbohydrate' }));
  139. }
  140. }
  141. }
  142. if (!partial || (partial && style.water)) {
  143. const root = update.to(StateElements.Water);
  144. if (style.water && style.water.hide) {
  145. root.delete(StateElements.WaterVisual);
  146. } else {
  147. root.applyOrUpdate(StateElements.WaterVisual, StateTransforms.Representation.StructureRepresentation3D,
  148. createStructureRepresentationParams(this.plugin, structure, {
  149. type: (style.water && style.water.kind) || 'ball-and-stick',
  150. typeParams: { alpha: 0.51 },
  151. color: style.water && style.water.coloring
  152. }));
  153. }
  154. }
  155. return update;
  156. }
  157. private getObj<T extends StateObject>(ref: string): T['data'] {
  158. const state = this.state;
  159. const cell = state.select(ref)[0];
  160. if (!cell || !cell.obj) return void 0;
  161. return (cell.obj as T).data;
  162. }
  163. private async doInfo(checkPreferredAssembly: boolean) {
  164. const model = this.getObj<PluginStateObject.Molecule.Model>('model');
  165. if (!model) return;
  166. const info = await ModelInfo.get(this.plugin, model, checkPreferredAssembly)
  167. this.events.modelInfo.next(info);
  168. return info;
  169. }
  170. private applyState(tree: StateBuilder) {
  171. return PluginCommands.State.Update(this.plugin, { state: this.plugin.state.dataState, tree });
  172. }
  173. private loadedParams: LoadParams = { url: '', format: 'cif', assemblyId: '' };
  174. async load({ url, format = 'cif', assemblyId = 'deposited', representationStyle }: LoadParams) {
  175. let loadType: 'full' | 'update' = 'full';
  176. const state = this.plugin.state.dataState;
  177. if (this.loadedParams.url !== url || this.loadedParams.format !== format) {
  178. loadType = 'full';
  179. } else if (this.loadedParams.url === url) {
  180. if (state.select(StateElements.Assembly).length > 0) loadType = 'update';
  181. }
  182. if (loadType === 'full') {
  183. await PluginCommands.State.RemoveObject(this.plugin, { state, ref: state.tree.root.ref });
  184. const modelTree = this.model(this.download(state.build().toRoot(), url), format);
  185. await this.applyState(modelTree);
  186. const info = await this.doInfo(true);
  187. const asmId = (assemblyId === 'preferred' && info && info.preferredAssemblyId) || assemblyId;
  188. const structureTree = this.structure(asmId);
  189. await this.applyState(structureTree);
  190. } else {
  191. const tree = state.build();
  192. const info = await this.doInfo(true);
  193. const asmId = (assemblyId === 'preferred' && info && info.preferredAssemblyId) || assemblyId;
  194. const props = {
  195. type: {
  196. name: 'assembly' as const,
  197. params: { id: asmId || 'deposited' }
  198. }
  199. }
  200. tree.to(StateElements.Assembly).update(StateTransforms.Model.StructureFromModel, p => ({ ...p, ...props }));
  201. await this.applyState(tree);
  202. }
  203. await this.updateStyle(representationStyle);
  204. this.loadedParams = { url, format, assemblyId };
  205. Scheduler.setImmediate(() => PluginCommands.Camera.Reset(this.plugin, { }));
  206. }
  207. async updateStyle(style?: RepresentationStyle, partial?: boolean) {
  208. const tree = this.visual(style, partial);
  209. if (!tree) return;
  210. await PluginCommands.State.Update(this.plugin, { state: this.plugin.state.dataState, tree });
  211. }
  212. setBackground(color: number) {
  213. if (!this.plugin.canvas3d) return;
  214. const renderer = this.plugin.canvas3d.props.renderer;
  215. PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: { renderer: { ...renderer, backgroundColor: Color(color) } } });
  216. }
  217. toggleSpin() {
  218. if (!this.plugin.canvas3d) return;
  219. const trackball = this.plugin.canvas3d.props.trackball;
  220. const spinning = trackball.spin;
  221. PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: { trackball: { ...trackball, spin: !trackball.spin } } });
  222. if (!spinning) PluginCommands.Camera.Reset(this.plugin, { });
  223. }
  224. viewport = {
  225. setSettings: (settings?: Canvas3DProps) => {
  226. PluginCommands.Canvas3D.SetSettings(this.plugin, {
  227. settings: settings || DefaultCanvas3DParams
  228. });
  229. }
  230. };
  231. camera = {
  232. toggleSpin: () => this.toggleSpin(),
  233. resetPosition: () => PluginCommands.Camera.Reset(this.plugin, { }),
  234. // setClip: (options?: { distance?: number, near?: number, far?: number }) => {
  235. // if (!options) {
  236. // PluginCommands.Canvas3D.SetSettings(this.plugin, {
  237. // settings: {
  238. // cameraClipDistance: DefaultCanvas3DParams.cameraClipDistance,
  239. // clip: DefaultCanvas3DParams.clip
  240. // }
  241. // });
  242. // return;
  243. // }
  244. // options = options || { };
  245. // const props = this.plugin.canvas3d.props;
  246. // const clipNear = typeof options.near === 'undefined' ? props.clip[0] : options.near;
  247. // const clipFar = typeof options.far === 'undefined' ? props.clip[1] : options.far;
  248. // PluginCommands.Canvas3D.SetSettings(this.plugin, {
  249. // settings: { cameraClipDistance: options.distance, clip: [clipNear, clipFar] }
  250. // });
  251. // }
  252. }
  253. animate = {
  254. modelIndex: {
  255. maxFPS: 8,
  256. onceForward: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'forward' } } }) },
  257. onceBackward: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'once', params: { direction: 'backward' } } }) },
  258. palindrome: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'palindrome', params: {} } }) },
  259. loop: () => { this.plugin.state.animation.play(AnimateModelIndex, { maxFPS: Math.max(0.5, this.animate.modelIndex.maxFPS | 0), mode: { name: 'loop', params: {} } }) },
  260. stop: () => this.plugin.state.animation.stop()
  261. }
  262. }
  263. coloring = {
  264. evolutionaryConservation: async (params?: { sequence?: boolean, het?: boolean, keepStyle?: boolean }) => {
  265. if (!params || !params.keepStyle) {
  266. await this.updateStyle({ sequence: { kind: 'spacefill' } }, true);
  267. }
  268. const state = this.state;
  269. // const visuals = state.selectQ(q => q.ofType(PluginStateObject.Molecule.Structure.Representation3D).filter(c => c.transform.transformer === StateTransforms.Representation.StructureRepresentation3D));
  270. // for (const v of visuals) {
  271. // }
  272. const tree = state.build();
  273. const colorTheme = { name: EvolutionaryConservation.propertyProvider.descriptor.name, params: this.plugin.structureRepresentation.themeCtx.colorThemeRegistry.get(EvolutionaryConservation.propertyProvider.descriptor.name).defaultValues };
  274. if (!params || !!params.sequence) {
  275. tree.to(StateElements.SequenceVisual).update(StateTransforms.Representation.StructureRepresentation3D, old => ({ ...old, colorTheme }));
  276. }
  277. if (params && !!params.het) {
  278. tree.to(StateElements.HetVisual).update(StateTransforms.Representation.StructureRepresentation3D, old => ({ ...old, colorTheme }));
  279. }
  280. await PluginCommands.State.Update(this.plugin, { state, tree });
  281. }
  282. }
  283. private experimentalDataElement?: Element = void 0;
  284. experimentalData = {
  285. init: async (parent: Element) => {
  286. const asm = this.state.select(StateElements.Assembly)[0].obj!;
  287. const params = InitVolumeStreaming.createDefaultParams(asm, this.plugin);
  288. params.options.behaviorRef = StateElements.VolumeStreaming;
  289. params.defaultView = 'box';
  290. params.options.channelParams['fo-fc(+ve)'] = { wireframe: true };
  291. params.options.channelParams['fo-fc(-ve)'] = { wireframe: true };
  292. await this.plugin.runTask(this.state.applyAction(InitVolumeStreaming, params, StateElements.Assembly));
  293. this.experimentalDataElement = parent;
  294. volumeStreamingControls(this.plugin, parent);
  295. },
  296. remove: () => {
  297. const r = this.state.select(StateSelection.Generators.ofTransformer(CreateVolumeStreamingInfo))[0];
  298. if (!r) return;
  299. PluginCommands.State.RemoveObject(this.plugin, { state: this.state, ref: r.transform.ref });
  300. if (this.experimentalDataElement) {
  301. ReactDOM.unmountComponentAtNode(this.experimentalDataElement);
  302. this.experimentalDataElement = void 0;
  303. }
  304. }
  305. }
  306. hetGroups = {
  307. reset: () => {
  308. const update = this.state.build().delete(StateElements.HetGroupFocusGroup);
  309. PluginCommands.State.Update(this.plugin, { state: this.state, tree: update });
  310. PluginCommands.Camera.Reset(this.plugin, { });
  311. },
  312. focusFirst: async (compId: string) => {
  313. if (!this.state.transforms.has(StateElements.Assembly)) return;
  314. await PluginCommands.Camera.Reset(this.plugin, { });
  315. // const asm = (this.state.select(StateElements.Assembly)[0].obj as PluginStateObject.Molecule.Structure).data;
  316. const update = this.state.build();
  317. update.delete(StateElements.HetGroupFocusGroup);
  318. const core = MS.struct.filter.first([
  319. MS.struct.generator.atomGroups({
  320. 'residue-test': MS.core.rel.eq([MS.struct.atomProperty.macromolecular.label_comp_id(), compId]),
  321. 'group-by': MS.core.str.concat([MS.struct.atomProperty.core.operatorName(), MS.struct.atomProperty.macromolecular.residueKey()])
  322. })
  323. ]);
  324. const surroundings = MS.struct.modifier.includeSurroundings({ 0: core, radius: 5, 'as-whole-residues': true });
  325. const group = update.to(StateElements.Assembly).group(StateTransforms.Misc.CreateGroup, { label: compId }, { ref: StateElements.HetGroupFocusGroup });
  326. group.apply(StateTransforms.Model.StructureSelectionFromExpression, { label: 'Core', expression: core }, { ref: StateElements.HetGroupFocus })
  327. .apply(StateTransforms.Representation.StructureRepresentation3D, this.createCoreVisualParams());
  328. group.apply(StateTransforms.Model.StructureSelectionFromExpression, { label: 'Surroundings', expression: surroundings })
  329. .apply(StateTransforms.Representation.StructureRepresentation3D, this.createSurVisualParams());
  330. // sel.apply(StateTransforms.Representation.StructureLabels3D, {
  331. // target: { name: 'residues', params: { } },
  332. // options: {
  333. // ...ParamDefinition.getDefaultValues(Text.Params),
  334. // background: true,
  335. // backgroundMargin: 0.2,
  336. // backgroundColor: ColorNames.snow,
  337. // backgroundOpacity: 0.9,
  338. // }
  339. // });
  340. await PluginCommands.State.Update(this.plugin, { state: this.state, tree: update });
  341. const focus = (this.state.select(StateElements.HetGroupFocus)[0].obj as PluginStateObject.Molecule.Structure).data;
  342. const sphere = focus.boundary.sphere;
  343. // const asmCenter = asm.boundary.sphere.center;
  344. // const position = Vec3.sub(Vec3.zero(), sphere.center, asmCenter);
  345. // Vec3.normalize(position, position);
  346. // Vec3.scaleAndAdd(position, sphere.center, position, sphere.radius);
  347. const radius = Math.max(sphere.radius, 5)
  348. const snapshot = this.plugin.canvas3d!.camera.getFocus(sphere.center, radius, radius);
  349. PluginCommands.Camera.SetSnapshot(this.plugin, { snapshot, durationMs: 250 });
  350. }
  351. }
  352. private createSurVisualParams() {
  353. const asm = this.state.select(StateElements.Assembly)[0].obj as PluginStateObject.Molecule.Structure;
  354. return createStructureRepresentationParams(this.plugin, asm.data, {
  355. type: 'ball-and-stick',
  356. color: 'uniform', colorParams: { value: ColorNames.gray },
  357. size: 'uniform', sizeParams: { value: 0.33 }
  358. });
  359. }
  360. private createCoreVisualParams() {
  361. const asm = this.state.select(StateElements.Assembly)[0].obj as PluginStateObject.Molecule.Structure;
  362. return createStructureRepresentationParams(this.plugin, asm.data, {
  363. type: 'ball-and-stick'
  364. });
  365. }
  366. snapshot = {
  367. get: () => {
  368. return this.plugin.state.getSnapshot();
  369. },
  370. set: (snapshot: PluginState.Snapshot) => {
  371. return this.plugin.state.setSnapshot(snapshot);
  372. },
  373. download: async (url: string) => {
  374. try {
  375. const snapshot = await this.plugin.runTask(this.plugin.fetch({ url, type: 'json' }));
  376. await this.plugin.state.setSnapshot(snapshot);
  377. } catch (e) {
  378. console.log(e);
  379. }
  380. }
  381. }
  382. }
  383. (window as any).MolStarProteopediaWrapper = MolStarProteopediaWrapper;