strucmotif.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
  5. */
  6. import * as React from 'react';
  7. import {CollapsableControls, PurePluginUIComponent} from 'molstar/lib/mol-plugin-ui/base';
  8. import {Button, IconButton, ToggleButton} from 'molstar/lib/mol-plugin-ui/controls/common';
  9. import {
  10. ArrowDownwardSvg,
  11. ArrowUpwardSvg,
  12. DeleteOutlinedSvg,
  13. HelpOutlineSvg,
  14. Icon, TuneSvg
  15. } from 'molstar/lib/mol-plugin-ui/controls/icons';
  16. import {ActionMenu} from 'molstar/lib/mol-plugin-ui/controls/action-menu';
  17. import {StructureSelectionHistoryEntry} from 'molstar/lib/mol-plugin-state/manager/structure/selection';
  18. import {StructureElement, StructureProperties} from 'molstar/lib/mol-model/structure/structure';
  19. import {ToggleSelectionModeButton} from 'molstar/lib/mol-plugin-ui/structure/selection';
  20. import {OrderedSet} from 'molstar/lib/mol-data/int';
  21. import {ExchangesControl} from './exchanges';
  22. // TODO use prod
  23. const ADVANCED_SEARCH_URL = 'https://strucmotif-dev.rcsb.org/search?request=';
  24. // TODO consider 2 as value
  25. const MIN_MOTIF_SIZE = 3;
  26. const MAX_MOTIF_SIZE = 10;
  27. /**
  28. * The top-level component that exposes the strucmotif search.
  29. */
  30. export class StrucmotifSubmitControls extends CollapsableControls {
  31. protected defaultState() {
  32. return {
  33. header: 'Structural Motif Search',
  34. isCollapsed: false,
  35. brand: { accent: 'gray' as const, svg: SearchIconSvg }
  36. };
  37. }
  38. renderControls() {
  39. return <>
  40. <SubmitControls />
  41. </>;
  42. }
  43. }
  44. const _SearchIcon = <svg width='24px' height='24px' viewBox='0 0 12 12'>
  45. <g strokeWidth='1.5' fill='none'>
  46. <path d='M11.29 11.71l-4-4' />
  47. <circle cx='5' cy='5' r='4' />
  48. </g>
  49. </svg>;
  50. export function SearchIconSvg() { return _SearchIcon; }
  51. const location = StructureElement.Location.create(void 0);
  52. type ExchangeState = 'exchanges-0' | 'exchanges-1' | 'exchanges-2' | 'exchanges-3' | 'exchanges-4' | 'exchanges-5' | 'exchanges-6' | 'exchanges-7' | 'exchanges-8' | 'exchanges-9';
  53. type ResidueSelection = { label_asym_id: string, struct_oper_id: string, label_seq_id: number }
  54. type Exchange = { residue_id: ResidueSelection, allowed: string[] }
  55. /**
  56. * The inner component of strucmotif search that can be collapsed.
  57. */
  58. class SubmitControls extends PurePluginUIComponent<{}, { isBusy: boolean, residueMap: Map<StructureSelectionHistoryEntry, Residue>, action?: ExchangeState }> {
  59. state = {
  60. isBusy: false,
  61. // map between selection entries of Mol* and additional exchange state
  62. residueMap: new Map<StructureSelectionHistoryEntry, Residue>(),
  63. action: void 0 as ExchangeState | undefined
  64. };
  65. componentDidMount() {
  66. this.subscribe(this.selection.events.additionsHistoryUpdated, () => {
  67. this.forceUpdate();
  68. });
  69. this.subscribe(this.plugin.behaviors.state.isBusy, v => {
  70. this.setState({ isBusy: v });
  71. });
  72. }
  73. get selection() {
  74. return this.plugin.managers.structure.selection;
  75. }
  76. submitSearch = () => {
  77. const pdbId: Set<string> = new Set();
  78. const residueIds: ResidueSelection[] = [];
  79. const exchanges: Exchange[] = [];
  80. const loci = this.plugin.managers.structure.selection.additionsHistory;
  81. let structure;
  82. for (let i = 0; i < Math.min(MAX_MOTIF_SIZE, loci.length); i++) {
  83. const l = loci[i];
  84. structure = l.loci.structure;
  85. pdbId.add(structure.model.entry);
  86. // only first element and only first index will be considered (ignoring multiple residues)
  87. const e = l.loci.elements[0];
  88. StructureElement.Location.set(location, structure, e.unit, e.unit.elements[OrderedSet.getAt(e.indices, 0)]);
  89. // handle pure residue-info
  90. const struct_oper_list_ids = StructureProperties.unit.pdbx_struct_oper_list_ids(location);
  91. const residueId = {
  92. label_asym_id: StructureProperties.chain.label_asym_id(location),
  93. // can be empty array if model is selected
  94. struct_oper_id: struct_oper_list_ids?.length ? struct_oper_list_ids.join('x') : '1',
  95. label_seq_id: StructureProperties.residue.label_seq_id(location)
  96. };
  97. residueIds.push(residueId);
  98. // handle potential exchanges
  99. const residueMapEntry = this.state.residueMap.get(l)!;
  100. if (residueMapEntry.exchanges?.size > 0) {
  101. exchanges.push({ residue_id: residueId, allowed: Array.from(residueMapEntry.exchanges.values()) });
  102. }
  103. }
  104. if (pdbId.size > 1) {
  105. this.plugin.log.warn('Motifs can only be extracted from a single model!');
  106. return;
  107. }
  108. if (residueIds.length > MAX_MOTIF_SIZE) {
  109. this.plugin.log.warn(`Maximum motif size is ${MAX_MOTIF_SIZE} residues!`);
  110. return;
  111. }
  112. if (residueIds.filter(v => v.label_seq_id === 0).length > 0) {
  113. this.plugin.log.warn('Selections may only contain polymeric entities!');
  114. return;
  115. }
  116. const query = {
  117. query: {
  118. type: 'group',
  119. logical_operator: 'and',
  120. nodes: [{
  121. type: 'terminal',
  122. service: 'strucmotif',
  123. parameters: {
  124. value: {
  125. data: pdbId.values().next().value as string,
  126. residue_ids: residueIds
  127. },
  128. score_cutoff: 5,
  129. exchanges: exchanges
  130. },
  131. label: 'strucmotif',
  132. node_id: 0
  133. }],
  134. label: 'query-builder'
  135. },
  136. return_type: 'assembly',
  137. request_options: {
  138. pager: {
  139. start: 0,
  140. rows: 100
  141. },
  142. scoring_strategy: 'combined',
  143. sort: [{
  144. sort_by: 'score',
  145. direction: 'desc'
  146. }]
  147. },
  148. 'request_info': {
  149. 'src': 'ui'
  150. }
  151. };
  152. console.log(query.query.nodes[0].parameters);
  153. window.open(ADVANCED_SEARCH_URL + encodeURIComponent(JSON.stringify(query)), '_blank');
  154. }
  155. get actions(): ActionMenu.Items {
  156. const history = this.selection.additionsHistory;
  157. return [
  158. {
  159. kind: 'item',
  160. label: `Submit Search ${history.length < MIN_MOTIF_SIZE ? ' (' + MIN_MOTIF_SIZE + ' selections required)' : ''}`,
  161. value: this.submitSearch,
  162. disabled: history.length < MIN_MOTIF_SIZE
  163. },
  164. ];
  165. }
  166. selectAction: ActionMenu.OnSelect = item => {
  167. if (!item) return;
  168. (item?.value as any)();
  169. }
  170. toggleExchanges = (idx: number) => this.setState({ action: this.state.action === `exchanges-${idx}` ? void 0 : `exchanges-${idx}` as ExchangeState });
  171. highlight(loci: StructureElement.Loci) {
  172. this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci }, false);
  173. }
  174. moveHistory(e: Residue, direction: 'up' | 'down') {
  175. this.setState({ action: void 0 });
  176. this.plugin.managers.structure.selection.modifyHistory(e.entry, direction, MAX_MOTIF_SIZE);
  177. this.updateResidues();
  178. }
  179. modifyHistory(e: Residue, a: 'remove') {
  180. this.setState({ action: void 0 });
  181. this.plugin.managers.structure.selection.modifyHistory(e.entry, a);
  182. this.updateResidues();
  183. }
  184. updateResidues() {
  185. const newResidueMap = new Map<StructureSelectionHistoryEntry, Residue>();
  186. this.selection.additionsHistory.forEach(entry => {
  187. newResidueMap.set(entry, this.state.residueMap.get(entry)!);
  188. });
  189. this.setState({ residueMap: newResidueMap });
  190. }
  191. focusLoci(loci: StructureElement.Loci) {
  192. this.plugin.managers.camera.focusLoci(loci);
  193. }
  194. historyEntry(e: Residue, idx: number) {
  195. const history = this.plugin.managers.structure.selection.additionsHistory;
  196. return <div key={e.entry.id}>
  197. <div className='msp-flex-row'>
  198. <Button noOverflow title='Click to focus. Hover to highlight.' onClick={() => this.focusLoci(e.entry.loci)} style={{ width: 'auto', textAlign: 'left' }} onMouseEnter={() => this.highlight(e.entry.loci)} onMouseLeave={this.plugin.managers.interactivity.lociHighlights.clearHighlights}>
  199. {idx}. <span dangerouslySetInnerHTML={{ __html: e.entry.label }} />
  200. </Button>
  201. <ToggleButton icon={TuneSvg} className='msp-form-control' title='Define exchanges' toggle={() => this.toggleExchanges(idx)} isSelected={this.state.action === `exchanges-${idx}`} disabled={this.state.isBusy} style={{ flex: '0 0 40px', padding: 0 }} />
  202. {history.length > 1 && <IconButton svg={ArrowUpwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'up')} flex='20px' title={'Move up'} />}
  203. {history.length > 1 && <IconButton svg={ArrowDownwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'down')} flex='20px' title={'Move down'} />}
  204. <IconButton svg={DeleteOutlinedSvg} small={true} className='msp-form-control' onClick={() => this.modifyHistory(e, 'remove')} flex title={'Remove'} />
  205. </div>
  206. { this.state.action === `exchanges-${idx}` && <ExchangesControl handler={e} /> }
  207. </div>;
  208. }
  209. add() {
  210. const history = this.plugin.managers.structure.selection.additionsHistory;
  211. const entries: JSX.Element[] = [];
  212. for (let i = 0, _i = Math.min(history.length, 10); i < _i; i++) {
  213. let residue: Residue;
  214. if (this.state.residueMap.has(history[i])) {
  215. residue = this.state.residueMap.get(history[i])!;
  216. } else {
  217. residue = new Residue(history[i], this.updateResidues.bind(this));
  218. this.state.residueMap.set(history[i], residue);
  219. }
  220. entries.push(this.historyEntry(residue, i + 1));
  221. }
  222. return <>
  223. <ActionMenu items={this.actions} onSelect={this.selectAction} />
  224. {entries.length > 0 && <div className='msp-control-offset'>
  225. {entries}
  226. </div>}
  227. {entries.length === 0 && <div className='msp-control-offset msp-help-text'>
  228. <div className='msp-help-description'><Icon svg={HelpOutlineSvg} inline />Add one or more selections (toggle <ToggleSelectionModeButton inline /> mode)</div>
  229. </div>}
  230. </>;
  231. }
  232. render() {
  233. return <>
  234. {this.add()}
  235. </>;
  236. }
  237. }
  238. export class Residue {
  239. readonly exchanges: Set<string>;
  240. constructor(readonly entry: StructureSelectionHistoryEntry, readonly callback: () => void) {
  241. this.exchanges = new Set<string>();
  242. }
  243. toggleExchange(val: string): void {
  244. if (this.hasExchange(val)) {
  245. this.exchanges.delete(val);
  246. } else {
  247. this.exchanges.add(val);
  248. }
  249. // this will update state of parent component
  250. this.callback();
  251. }
  252. hasExchange(val: string): boolean {
  253. return this.exchanges.has(val);
  254. }
  255. }