strucmotif.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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,
  15. TuneSvg
  16. } from 'molstar/lib/mol-plugin-ui/controls/icons';
  17. import {ActionMenu} from 'molstar/lib/mol-plugin-ui/controls/action-menu';
  18. import {StructureSelectionHistoryEntry} from 'molstar/lib/mol-plugin-state/manager/structure/selection';
  19. import {StructureElement, StructureProperties} from 'molstar/lib/mol-model/structure/structure';
  20. import {ToggleSelectionModeButton} from 'molstar/lib/mol-plugin-ui/structure/selection';
  21. import {OrderedSet} from 'molstar/lib/mol-data/int';
  22. import {ExchangesControl} from './exchanges';
  23. const ADVANCED_SEARCH_URL = 'https://rcsb.org/search?query=';
  24. const RETURN_TYPE = '&return_type=assembly';
  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 = number;
  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. // invalidate potentially expanded exchange panel
  68. this.setState({ action: void 0 });
  69. this.forceUpdate();
  70. });
  71. this.subscribe(this.plugin.behaviors.state.isBusy, v => {
  72. this.setState({ isBusy: v });
  73. });
  74. }
  75. get selection() {
  76. return this.plugin.managers.structure.selection;
  77. }
  78. submitSearch = () => {
  79. const pdbId: Set<string> = new Set();
  80. const residueIds: ResidueSelection[] = [];
  81. const exchanges: Exchange[] = [];
  82. const loci = this.plugin.managers.structure.selection.additionsHistory;
  83. let structure;
  84. for (let i = 0; i < Math.min(MAX_MOTIF_SIZE, loci.length); i++) {
  85. const l = loci[i];
  86. structure = l.loci.structure;
  87. pdbId.add(structure.model.entry);
  88. // only first element and only first index will be considered (ignoring multiple residues)
  89. const e = l.loci.elements[0];
  90. StructureElement.Location.set(location, structure, e.unit, e.unit.elements[OrderedSet.getAt(e.indices, 0)]);
  91. // handle pure residue-info
  92. const struct_oper_list_ids = StructureProperties.unit.pdbx_struct_oper_list_ids(location);
  93. const residueId = {
  94. label_asym_id: StructureProperties.chain.label_asym_id(location),
  95. // can be empty array if model is selected
  96. struct_oper_id: struct_oper_list_ids?.length ? struct_oper_list_ids.join('x') : '1',
  97. label_seq_id: StructureProperties.residue.label_seq_id(location)
  98. };
  99. residueIds.push(residueId);
  100. // handle potential exchanges - can be empty if deselected by users
  101. const residueMapEntry = this.state.residueMap.get(l)!;
  102. if (residueMapEntry.exchanges?.size > 0) {
  103. exchanges.push({ residue_id: residueId, allowed: Array.from(residueMapEntry.exchanges.values()) });
  104. }
  105. }
  106. if (pdbId.size > 1) {
  107. this.plugin.log.warn('Motifs can only be extracted from a single model!');
  108. return;
  109. }
  110. if (residueIds.length > MAX_MOTIF_SIZE) {
  111. this.plugin.log.warn(`Maximum motif size is ${MAX_MOTIF_SIZE} residues!`);
  112. return;
  113. }
  114. if (residueIds.filter(v => v.label_seq_id === 0).length > 0) {
  115. this.plugin.log.warn('Selections may only contain polymeric entities!');
  116. return;
  117. }
  118. const query = {
  119. type: 'terminal',
  120. service: 'strucmotif',
  121. parameters: {
  122. value: {
  123. data: pdbId.values().next().value as string,
  124. residue_ids: residueIds.sort((a, b) => this.sortResidueIds(a, b))
  125. },
  126. score_cutoff: 0,
  127. exchanges: exchanges
  128. }
  129. };
  130. // console.log(query);
  131. const url = ADVANCED_SEARCH_URL + encodeURIComponent(JSON.stringify(query)) + RETURN_TYPE;
  132. // console.log(url);
  133. window.open(url, '_blank');
  134. }
  135. sortResidueIds(a: ResidueSelection, b: ResidueSelection): number {
  136. if (a.label_asym_id !== b.label_asym_id) {
  137. return a.label_asym_id.localeCompare(b.label_asym_id);
  138. } else if (a.struct_oper_id !== b.struct_oper_id) {
  139. return a.struct_oper_id.localeCompare(b.struct_oper_id);
  140. } else {
  141. return a.label_seq_id < b.label_seq_id ? -1 : a.label_seq_id > b.label_seq_id ? 1 : 0;
  142. }
  143. }
  144. get actions(): ActionMenu.Items {
  145. const history = this.selection.additionsHistory;
  146. return [
  147. {
  148. kind: 'item',
  149. label: `Submit Search ${history.length < MIN_MOTIF_SIZE ? ' (' + MIN_MOTIF_SIZE + ' selections required)' : ''}`,
  150. value: this.submitSearch,
  151. disabled: history.length < MIN_MOTIF_SIZE
  152. },
  153. ];
  154. }
  155. selectAction: ActionMenu.OnSelect = item => {
  156. if (!item) return;
  157. (item?.value as any)();
  158. }
  159. toggleExchanges = (idx: number) => this.setState({ action: (this.state.action === idx ? void 0 : idx) as ExchangeState });
  160. highlight(loci: StructureElement.Loci) {
  161. this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci }, false);
  162. }
  163. moveHistory(e: Residue, direction: 'up' | 'down') {
  164. this.setState({ action: void 0 });
  165. this.plugin.managers.structure.selection.modifyHistory(e.entry, direction, MAX_MOTIF_SIZE);
  166. this.updateResidues();
  167. }
  168. modifyHistory(e: Residue, a: 'remove') {
  169. this.setState({ action: void 0 });
  170. this.plugin.managers.structure.selection.modifyHistory(e.entry, a);
  171. this.updateResidues();
  172. }
  173. updateResidues() {
  174. const newResidueMap = new Map<StructureSelectionHistoryEntry, Residue>();
  175. this.selection.additionsHistory.forEach(entry => {
  176. newResidueMap.set(entry, this.state.residueMap.get(entry)!);
  177. });
  178. this.setState({ residueMap: newResidueMap });
  179. }
  180. focusLoci(loci: StructureElement.Loci) {
  181. this.plugin.managers.camera.focusLoci(loci);
  182. }
  183. historyEntry(e: Residue, idx: number) {
  184. const history = this.plugin.managers.structure.selection.additionsHistory;
  185. return <div key={e.entry.id}>
  186. <div className='msp-flex-row'>
  187. <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}>
  188. {idx}. <span dangerouslySetInnerHTML={{ __html: e.entry.label }} />
  189. </Button>
  190. <ToggleButton icon={TuneSvg} className='msp-form-control' title='Define exchanges' toggle={() => this.toggleExchanges(idx)} isSelected={this.state.action === idx} disabled={this.state.isBusy} style={{ flex: '0 0 40px', padding: 0 }} />
  191. {history.length > 1 && <IconButton svg={ArrowUpwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'up')} flex='20px' title={'Move up'} />}
  192. {history.length > 1 && <IconButton svg={ArrowDownwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'down')} flex='20px' title={'Move down'} />}
  193. <IconButton svg={DeleteOutlinedSvg} small={true} className='msp-form-control' onClick={() => this.modifyHistory(e, 'remove')} flex title={'Remove'} />
  194. </div>
  195. { this.state.action === idx && <ExchangesControl handler={e} /> }
  196. </div>;
  197. }
  198. add() {
  199. const history = this.plugin.managers.structure.selection.additionsHistory;
  200. const entries: JSX.Element[] = [];
  201. for (let i = 0, _i = Math.min(history.length, 10); i < _i; i++) {
  202. let residue: Residue;
  203. if (this.state.residueMap.has(history[i])) {
  204. residue = this.state.residueMap.get(history[i])!;
  205. } else {
  206. residue = new Residue(history[i], this);
  207. this.state.residueMap.set(history[i], residue);
  208. }
  209. entries.push(this.historyEntry(residue, i + 1));
  210. }
  211. return <>
  212. <ActionMenu items={this.actions} onSelect={this.selectAction} />
  213. {entries.length > 0 && <div className='msp-control-offset'>
  214. {entries}
  215. </div>}
  216. {entries.length === 0 && <div className='msp-control-offset msp-help-text'>
  217. <div className='msp-help-description'><Icon svg={HelpOutlineSvg} inline />Add one or more selections (toggle <ToggleSelectionModeButton inline /> mode)</div>
  218. </div>}
  219. </>;
  220. }
  221. render() {
  222. return <>
  223. {this.add()}
  224. </>;
  225. }
  226. }
  227. export class Residue {
  228. readonly exchanges: Set<string>;
  229. constructor(readonly entry: StructureSelectionHistoryEntry, readonly parent: SubmitControls) {
  230. this.exchanges = new Set<string>();
  231. // by default: explicitly 'activate' original residue type
  232. const structure = entry.loci.structure;
  233. const e = entry.loci.elements[0];
  234. StructureElement.Location.set(location, structure, e.unit, e.unit.elements[OrderedSet.getAt(e.indices, 0)]);
  235. this.exchanges.add(StructureProperties.atom.label_comp_id(location));
  236. }
  237. toggleExchange(val: string): void {
  238. if (this.hasExchange(val)) {
  239. this.exchanges.delete(val);
  240. } else {
  241. this.exchanges.add(val);
  242. }
  243. // this will update state of parent component
  244. this.parent.forceUpdate();
  245. }
  246. hasExchange(val: string): boolean {
  247. return this.exchanges.has(val);
  248. }
  249. }