strucmotif.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. import Vec3 from 'molstar/lib/mol-math/linear-algebra/3d/vec3';
  24. import Structure from 'molstar/lib/mol-model/structure/structure/structure';
  25. import Unit from 'molstar/lib/mol-model/structure/structure/unit';
  26. import {UnitIndex} from 'molstar/lib/mol-model/structure/structure/element/element';
  27. const ADVANCED_SEARCH_URL = 'https://rcsb.org/search?query=';
  28. const RETURN_TYPE = '&return_type=assembly';
  29. const MIN_MOTIF_SIZE = 3;
  30. const MAX_MOTIF_SIZE = 10;
  31. export const MAX_EXCHANGES = 4;
  32. const MAX_MOTIF_EXTENT = 15;
  33. const MAX_MOTIF_EXTENT_SQUARED = MAX_MOTIF_EXTENT * MAX_MOTIF_EXTENT;
  34. /**
  35. * The top-level component that exposes the strucmotif search.
  36. */
  37. export class StrucmotifSubmitControls extends CollapsableControls {
  38. protected defaultState() {
  39. return {
  40. header: 'Structural Motif Search',
  41. isCollapsed: false,
  42. brand: { accent: 'gray' as const, svg: SearchIconSvg }
  43. };
  44. }
  45. renderControls() {
  46. return <>
  47. <SubmitControls />
  48. </>;
  49. }
  50. }
  51. const _SearchIcon = <svg width='24px' height='24px' viewBox='0 0 12 12'>
  52. <g strokeWidth='1.5' fill='none'>
  53. <path d='M11.29 11.71l-4-4' />
  54. <circle cx='5' cy='5' r='4' />
  55. </g>
  56. </svg>;
  57. export function SearchIconSvg() { return _SearchIcon; }
  58. const location = StructureElement.Location.create(void 0);
  59. type ExchangeState = number;
  60. type ResidueSelection = { label_asym_id: string, struct_oper_id: string, label_seq_id: number }
  61. type Exchange = { residue_id: ResidueSelection, allowed: string[] }
  62. /**
  63. * The inner component of strucmotif search that can be collapsed.
  64. */
  65. class SubmitControls extends PurePluginUIComponent<{}, { isBusy: boolean, residueMap: Map<StructureSelectionHistoryEntry, Residue>, action?: ExchangeState }> {
  66. state = {
  67. isBusy: false,
  68. // map between selection entries of Mol* and additional exchange state
  69. residueMap: new Map<StructureSelectionHistoryEntry, Residue>(),
  70. action: void 0 as ExchangeState | undefined
  71. };
  72. componentDidMount() {
  73. this.subscribe(this.selection.events.additionsHistoryUpdated, () => {
  74. // invalidate potentially expanded exchange panel
  75. this.setState({ action: void 0 });
  76. this.forceUpdate();
  77. });
  78. this.subscribe(this.plugin.behaviors.state.isBusy, v => {
  79. this.setState({ isBusy: v });
  80. });
  81. }
  82. get selection() {
  83. return this.plugin.managers.structure.selection;
  84. }
  85. submitSearch = () => {
  86. const { label_atom_id, x, y, z } = StructureProperties.atom;
  87. const pdbId: Set<string> = new Set();
  88. const residueIds: ResidueSelection[] = [];
  89. const exchanges: Exchange[] = [];
  90. const coordinates: { coords: Vec3, residueId: ResidueSelection }[] = [];
  91. /**
  92. * This sets the 'location' to the backbone atom (CA or C4').
  93. * @param structure context
  94. * @param element wraps atom indices of this residue
  95. */
  96. const determineBackboneAtom = (structure: Structure, element: { unit: Unit; indices: OrderedSet<UnitIndex> }) => {
  97. const { indices } = element;
  98. for (let i = 0, il = OrderedSet.size(indices); i < il; i++) {
  99. StructureElement.Location.set(location, structure, element.unit, element.unit.elements[OrderedSet.getAt(indices, i)]);
  100. const atomLabelId = label_atom_id(location);
  101. if ('CA' === atomLabelId || `C4'` === atomLabelId) {
  102. return true;
  103. }
  104. }
  105. return false;
  106. };
  107. const loci = this.plugin.managers.structure.selection.additionsHistory;
  108. for (let i = 0; i < Math.min(MAX_MOTIF_SIZE, loci.length); i++) {
  109. const l = loci[i];
  110. const { structure, elements } = l.loci;
  111. pdbId.add(structure.model.entry);
  112. // only first element and only first index will be considered (ignoring multiple residues)
  113. if (!determineBackboneAtom(structure, elements[0])) {
  114. const struct_oper_list_ids = StructureProperties.unit.pdbx_struct_oper_list_ids(location);
  115. const struct_oper_id = struct_oper_list_ids?.length ? struct_oper_list_ids.join('x') : '1';
  116. alert(`No CA or C4' atom for ${StructureProperties.residue.label_seq_id(location)} | ${StructureProperties.chain.label_asym_id(location)} | ${struct_oper_id}`);
  117. return;
  118. }
  119. // handle pure residue-info
  120. const struct_oper_list_ids = StructureProperties.unit.pdbx_struct_oper_list_ids(location);
  121. // TODO honor NCS operators: StructureProperties.unit.struct_ncs_oper_id(location);
  122. const residueId = {
  123. label_asym_id: StructureProperties.chain.label_asym_id(location),
  124. // can be empty array if model is selected
  125. struct_oper_id: struct_oper_list_ids?.length ? struct_oper_list_ids.join('x') : '1',
  126. label_seq_id: StructureProperties.residue.label_seq_id(location)
  127. };
  128. residueIds.push(residueId);
  129. // retrieve CA/C4', used to compute residue distance
  130. const coords = [x(location), y(location), z(location)] as Vec3;
  131. coordinates.push({coords, residueId});
  132. // handle potential exchanges - can be empty if deselected by users
  133. const residueMapEntry = this.state.residueMap.get(l)!;
  134. if (residueMapEntry.exchanges?.size > 0) {
  135. if (residueMapEntry.exchanges.size > MAX_EXCHANGES) {
  136. alert(`Maximum number of exchanges per position is ${MAX_EXCHANGES} - Please remove some exchanges from residue ${residueId.label_seq_id} | ${residueId.label_asym_id} | ${residueId.struct_oper_id}.`);
  137. return;
  138. }
  139. exchanges.push({ residue_id: residueId, allowed: Array.from(residueMapEntry.exchanges.values()) });
  140. }
  141. }
  142. if (pdbId.size > 1) {
  143. alert('Motifs can only be extracted from a single model!');
  144. return;
  145. }
  146. if (residueIds.length > MAX_MOTIF_SIZE) {
  147. alert(`Maximum motif size is ${MAX_MOTIF_SIZE} residues!`);
  148. return;
  149. }
  150. if (residueIds.filter(v => v.label_seq_id === 0).length > 0) {
  151. alert('Selections may only contain polymeric entities!');
  152. return;
  153. }
  154. // warn if >15 A
  155. const a = Vec3();
  156. const b = Vec3();
  157. // this is not efficient but is good enough for up to 10 residues
  158. for (let i = 0, il = coordinates.length; i < il; i++) {
  159. Vec3.set(a, coordinates[i].coords[0], coordinates[i].coords[1], coordinates[i].coords[2]);
  160. let contact = false;
  161. for (let j = 0, jl = coordinates.length; j < jl; j++) {
  162. if (i === j) continue;
  163. Vec3.set(b, coordinates[j].coords[0], coordinates[j].coords[1], coordinates[j].coords[2]);
  164. const d = Vec3.squaredDistance(a, b);
  165. if (d < MAX_MOTIF_EXTENT_SQUARED) {
  166. contact = true;
  167. }
  168. }
  169. if (!contact) {
  170. const { residueId } = coordinates[i];
  171. alert(`Residue ${residueId.label_seq_id} | ${residueId.label_asym_id} | ${residueId.struct_oper_id} needs to be less than 15 \u212B from another residue - Consider adding more residues to connect far-apart residues.`);
  172. return;
  173. }
  174. }
  175. const query = {
  176. type: 'terminal',
  177. service: 'strucmotif',
  178. parameters: {
  179. value: {
  180. data: pdbId.values().next().value as string,
  181. residue_ids: residueIds.sort((a, b) => this.sortResidueIds(a, b))
  182. },
  183. score_cutoff: 0,
  184. exchanges: exchanges
  185. }
  186. };
  187. // console.log(query);
  188. const url = ADVANCED_SEARCH_URL + encodeURIComponent(JSON.stringify(query)) + RETURN_TYPE;
  189. // console.log(url);
  190. window.open(url, '_blank');
  191. }
  192. sortResidueIds(a: ResidueSelection, b: ResidueSelection): number {
  193. if (a.label_asym_id !== b.label_asym_id) {
  194. return a.label_asym_id.localeCompare(b.label_asym_id);
  195. } else if (a.struct_oper_id !== b.struct_oper_id) {
  196. return a.struct_oper_id.localeCompare(b.struct_oper_id);
  197. } else {
  198. return a.label_seq_id < b.label_seq_id ? -1 : a.label_seq_id > b.label_seq_id ? 1 : 0;
  199. }
  200. }
  201. get actions(): ActionMenu.Items {
  202. const history = this.selection.additionsHistory;
  203. return [
  204. {
  205. kind: 'item',
  206. label: `Submit Search ${history.length < MIN_MOTIF_SIZE ? ' (' + MIN_MOTIF_SIZE + ' selections required)' : ''}`,
  207. value: this.submitSearch,
  208. disabled: history.length < MIN_MOTIF_SIZE
  209. },
  210. ];
  211. }
  212. selectAction: ActionMenu.OnSelect = item => {
  213. if (!item) return;
  214. (item?.value as any)();
  215. }
  216. toggleExchanges = (idx: number) => this.setState({ action: (this.state.action === idx ? void 0 : idx) as ExchangeState });
  217. highlight(loci: StructureElement.Loci) {
  218. this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci }, false);
  219. }
  220. moveHistory(e: Residue, direction: 'up' | 'down') {
  221. this.setState({ action: void 0 });
  222. this.plugin.managers.structure.selection.modifyHistory(e.entry, direction, MAX_MOTIF_SIZE);
  223. this.updateResidues();
  224. }
  225. modifyHistory(e: Residue, a: 'remove') {
  226. this.setState({ action: void 0 });
  227. this.plugin.managers.structure.selection.modifyHistory(e.entry, a);
  228. this.updateResidues();
  229. }
  230. updateResidues() {
  231. const newResidueMap = new Map<StructureSelectionHistoryEntry, Residue>();
  232. this.selection.additionsHistory.forEach(entry => {
  233. newResidueMap.set(entry, this.state.residueMap.get(entry)!);
  234. });
  235. this.setState({ residueMap: newResidueMap });
  236. }
  237. focusLoci(loci: StructureElement.Loci) {
  238. this.plugin.managers.camera.focusLoci(loci);
  239. }
  240. historyEntry(e: Residue, idx: number) {
  241. const history = this.plugin.managers.structure.selection.additionsHistory;
  242. return <div key={e.entry.id}>
  243. <div className='msp-flex-row'>
  244. <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}>
  245. {idx}. <span dangerouslySetInnerHTML={{ __html: e.entry.label }} />
  246. </Button>
  247. <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 }} />
  248. {history.length > 1 && <IconButton svg={ArrowUpwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'up')} flex='20px' title={'Move up'} />}
  249. {history.length > 1 && <IconButton svg={ArrowDownwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'down')} flex='20px' title={'Move down'} />}
  250. <IconButton svg={DeleteOutlinedSvg} small={true} className='msp-form-control' onClick={() => this.modifyHistory(e, 'remove')} flex title={'Remove'} />
  251. </div>
  252. { this.state.action === idx && <ExchangesControl handler={e} /> }
  253. </div>;
  254. }
  255. add() {
  256. const history = this.plugin.managers.structure.selection.additionsHistory;
  257. const entries: JSX.Element[] = [];
  258. for (let i = 0, _i = Math.min(history.length, 10); i < _i; i++) {
  259. let residue: Residue;
  260. if (this.state.residueMap.has(history[i])) {
  261. residue = this.state.residueMap.get(history[i])!;
  262. } else {
  263. residue = new Residue(history[i], this);
  264. this.state.residueMap.set(history[i], residue);
  265. }
  266. entries.push(this.historyEntry(residue, i + 1));
  267. }
  268. return <>
  269. <ActionMenu items={this.actions} onSelect={this.selectAction} />
  270. {entries.length > 0 && <div className='msp-control-offset'>
  271. {entries}
  272. </div>}
  273. {entries.length === 0 && <div className='msp-control-offset msp-help-text'>
  274. <div className='msp-help-description'><Icon svg={HelpOutlineSvg} inline />Add one or more selections (toggle <ToggleSelectionModeButton inline /> mode)</div>
  275. </div>}
  276. </>;
  277. }
  278. render() {
  279. return <>
  280. {this.add()}
  281. </>;
  282. }
  283. }
  284. export class Residue {
  285. readonly exchanges: Set<string>;
  286. constructor(readonly entry: StructureSelectionHistoryEntry, readonly parent: SubmitControls) {
  287. this.exchanges = new Set<string>();
  288. // by default: explicitly 'activate' original residue type
  289. const structure = entry.loci.structure;
  290. const e = entry.loci.elements[0];
  291. StructureElement.Location.set(location, structure, e.unit, e.unit.elements[OrderedSet.getAt(e.indices, 0)]);
  292. this.exchanges.add(StructureProperties.atom.label_comp_id(location));
  293. }
  294. toggleExchange(val: string): void {
  295. if (this.hasExchange(val)) {
  296. this.exchanges.delete(val);
  297. } else {
  298. if (this.exchanges.size < MAX_EXCHANGES) {
  299. this.exchanges.add(val);
  300. } else {
  301. alert(`Maximum number of exchanges per position is ${MAX_EXCHANGES}`);
  302. }
  303. }
  304. // this will update state of parent component
  305. this.parent.forceUpdate();
  306. }
  307. hasExchange(val: string): boolean {
  308. return this.exchanges.has(val);
  309. }
  310. }