strucmotif.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. const residueId = {
  122. label_asym_id: StructureProperties.chain.label_asym_id(location),
  123. // can be empty array if model is selected
  124. struct_oper_id: struct_oper_list_ids?.length ? struct_oper_list_ids.join('x') : '1',
  125. label_seq_id: StructureProperties.residue.label_seq_id(location)
  126. };
  127. residueIds.push(residueId);
  128. // retrieve CA/C4', used to compute residue distance
  129. const coords = [x(location), y(location), z(location)] as Vec3;
  130. coordinates.push({coords, residueId});
  131. // handle potential exchanges - can be empty if deselected by users
  132. const residueMapEntry = this.state.residueMap.get(l)!;
  133. if (residueMapEntry.exchanges?.size > 0) {
  134. if (residueMapEntry.exchanges.size > MAX_EXCHANGES) {
  135. 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}.`);
  136. return;
  137. }
  138. exchanges.push({ residue_id: residueId, allowed: Array.from(residueMapEntry.exchanges.values()) });
  139. }
  140. }
  141. if (pdbId.size > 1) {
  142. alert('Motifs can only be extracted from a single model!');
  143. return;
  144. }
  145. if (residueIds.length > MAX_MOTIF_SIZE) {
  146. alert(`Maximum motif size is ${MAX_MOTIF_SIZE} residues!`);
  147. return;
  148. }
  149. if (residueIds.filter(v => v.label_seq_id === 0).length > 0) {
  150. alert('Selections may only contain polymeric entities!');
  151. return;
  152. }
  153. // warn if >15 A
  154. const a = Vec3();
  155. const b = Vec3();
  156. // this is not efficient but is good enough for up to 10 residues
  157. for (let i = 0, il = coordinates.length; i < il; i++) {
  158. Vec3.set(a, coordinates[i].coords[0], coordinates[i].coords[1], coordinates[i].coords[2]);
  159. let contact = false;
  160. for (let j = 0, jl = coordinates.length; j < jl; j++) {
  161. if (i === j) continue;
  162. Vec3.set(b, coordinates[j].coords[0], coordinates[j].coords[1], coordinates[j].coords[2]);
  163. const d = Vec3.squaredDistance(a, b);
  164. if (d < MAX_MOTIF_EXTENT_SQUARED) {
  165. contact = true;
  166. }
  167. }
  168. if (!contact) {
  169. const { residueId } = coordinates[i];
  170. 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.`);
  171. return;
  172. }
  173. }
  174. const query = {
  175. type: 'terminal',
  176. service: 'strucmotif',
  177. parameters: {
  178. value: {
  179. data: pdbId.values().next().value as string,
  180. residue_ids: residueIds.sort((a, b) => this.sortResidueIds(a, b))
  181. },
  182. score_cutoff: 0,
  183. exchanges: exchanges
  184. }
  185. };
  186. // console.log(query);
  187. const url = ADVANCED_SEARCH_URL + encodeURIComponent(JSON.stringify(query)) + RETURN_TYPE;
  188. // console.log(url);
  189. window.open(url, '_blank');
  190. }
  191. sortResidueIds(a: ResidueSelection, b: ResidueSelection): number {
  192. if (a.label_asym_id !== b.label_asym_id) {
  193. return a.label_asym_id.localeCompare(b.label_asym_id);
  194. } else if (a.struct_oper_id !== b.struct_oper_id) {
  195. return a.struct_oper_id.localeCompare(b.struct_oper_id);
  196. } else {
  197. return a.label_seq_id < b.label_seq_id ? -1 : a.label_seq_id > b.label_seq_id ? 1 : 0;
  198. }
  199. }
  200. get actions(): ActionMenu.Items {
  201. const history = this.selection.additionsHistory;
  202. return [
  203. {
  204. kind: 'item',
  205. label: `Submit Search ${history.length < MIN_MOTIF_SIZE ? ' (' + MIN_MOTIF_SIZE + ' selections required)' : ''}`,
  206. value: this.submitSearch,
  207. disabled: history.length < MIN_MOTIF_SIZE
  208. },
  209. ];
  210. }
  211. selectAction: ActionMenu.OnSelect = item => {
  212. if (!item) return;
  213. (item?.value as any)();
  214. }
  215. toggleExchanges = (idx: number) => this.setState({ action: (this.state.action === idx ? void 0 : idx) as ExchangeState });
  216. highlight(loci: StructureElement.Loci) {
  217. this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci }, false);
  218. }
  219. moveHistory(e: Residue, direction: 'up' | 'down') {
  220. this.setState({ action: void 0 });
  221. this.plugin.managers.structure.selection.modifyHistory(e.entry, direction, MAX_MOTIF_SIZE);
  222. this.updateResidues();
  223. }
  224. modifyHistory(e: Residue, a: 'remove') {
  225. this.setState({ action: void 0 });
  226. this.plugin.managers.structure.selection.modifyHistory(e.entry, a);
  227. this.updateResidues();
  228. }
  229. updateResidues() {
  230. const newResidueMap = new Map<StructureSelectionHistoryEntry, Residue>();
  231. this.selection.additionsHistory.forEach(entry => {
  232. newResidueMap.set(entry, this.state.residueMap.get(entry)!);
  233. });
  234. this.setState({ residueMap: newResidueMap });
  235. }
  236. focusLoci(loci: StructureElement.Loci) {
  237. this.plugin.managers.camera.focusLoci(loci);
  238. }
  239. historyEntry(e: Residue, idx: number) {
  240. const history = this.plugin.managers.structure.selection.additionsHistory;
  241. return <div key={e.entry.id}>
  242. <div className='msp-flex-row'>
  243. <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}>
  244. {idx}. <span dangerouslySetInnerHTML={{ __html: e.entry.label }} />
  245. </Button>
  246. <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 }} />
  247. {history.length > 1 && <IconButton svg={ArrowUpwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'up')} flex='20px' title={'Move up'} />}
  248. {history.length > 1 && <IconButton svg={ArrowDownwardSvg} small={true} className='msp-form-control' onClick={() => this.moveHistory(e, 'down')} flex='20px' title={'Move down'} />}
  249. <IconButton svg={DeleteOutlinedSvg} small={true} className='msp-form-control' onClick={() => this.modifyHistory(e, 'remove')} flex title={'Remove'} />
  250. </div>
  251. { this.state.action === idx && <ExchangesControl handler={e} /> }
  252. </div>;
  253. }
  254. add() {
  255. const history = this.plugin.managers.structure.selection.additionsHistory;
  256. const entries: JSX.Element[] = [];
  257. for (let i = 0, _i = Math.min(history.length, 10); i < _i; i++) {
  258. let residue: Residue;
  259. if (this.state.residueMap.has(history[i])) {
  260. residue = this.state.residueMap.get(history[i])!;
  261. } else {
  262. residue = new Residue(history[i], this);
  263. this.state.residueMap.set(history[i], residue);
  264. }
  265. entries.push(this.historyEntry(residue, i + 1));
  266. }
  267. return <>
  268. <ActionMenu items={this.actions} onSelect={this.selectAction} />
  269. {entries.length > 0 && <div className='msp-control-offset'>
  270. {entries}
  271. </div>}
  272. {entries.length === 0 && <div className='msp-control-offset msp-help-text'>
  273. <div className='msp-help-description'><Icon svg={HelpOutlineSvg} inline />Add one or more selections (toggle <ToggleSelectionModeButton inline /> mode)</div>
  274. </div>}
  275. </>;
  276. }
  277. render() {
  278. return <>
  279. {this.add()}
  280. </>;
  281. }
  282. }
  283. export class Residue {
  284. readonly exchanges: Set<string>;
  285. constructor(readonly entry: StructureSelectionHistoryEntry, readonly parent: SubmitControls) {
  286. this.exchanges = new Set<string>();
  287. // by default: explicitly 'activate' original residue type
  288. const structure = entry.loci.structure;
  289. const e = entry.loci.elements[0];
  290. StructureElement.Location.set(location, structure, e.unit, e.unit.elements[OrderedSet.getAt(e.indices, 0)]);
  291. this.exchanges.add(StructureProperties.atom.label_comp_id(location));
  292. }
  293. toggleExchange(val: string): void {
  294. if (this.hasExchange(val)) {
  295. this.exchanges.delete(val);
  296. } else {
  297. if (this.exchanges.size < MAX_EXCHANGES) {
  298. this.exchanges.add(val);
  299. } else {
  300. alert(`Maximum number of exchanges per position is ${MAX_EXCHANGES}`);
  301. }
  302. }
  303. // this will update state of parent component
  304. this.parent.forceUpdate();
  305. }
  306. hasExchange(val: string): boolean {
  307. return this.exchanges.has(val);
  308. }
  309. }