2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.analysis;
23 import jalview.api.AlignViewportI;
24 import jalview.api.FinderI;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SearchResultMatchI;
27 import jalview.datamodel.SearchResults;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceGroup;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.Comparison;
32 import jalview.util.MapList;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Iterator;
37 import java.util.List;
39 import com.stevesoft.pat.Regex;
42 * Implements the search algorithm for the Find dialog
44 public class Finder implements FinderI
47 * matched residue locations
49 private SearchResultsI searchResults;
52 * sequences matched by id or description
54 private List<SequenceI> idMatches;
57 * the viewport to search over
59 private AlignViewportI viewport;
62 * sequence index in alignment to search from
64 private int sequenceIndex;
67 * position offset in sequence to search from, base 0
68 * (position after start of last match for a 'find next')
70 private int residueIndex;
73 * the true sequence position of the start of the
74 * last sequence searched (when 'ignore hidden regions' does not apply)
76 private int searchedSequenceStartPosition;
79 * when 'ignore hidden regions' applies, this holds the mapping from
80 * the visible sequence positions (1, 2, ...) to true sequence positions
82 private MapList searchedSequenceMap;
84 private String seqToSearch;
87 * Constructor for searching a viewport
91 public Finder(AlignViewportI av)
94 this.sequenceIndex = 0;
95 this.residueIndex = -1;
99 public void findAll(String theSearchString, boolean matchCase,
100 boolean searchDescription, boolean ignoreHidden)
103 * search from the start
108 doFind(theSearchString, matchCase, searchDescription, true,
112 * reset to start for next search
119 public void findNext(String theSearchString, boolean matchCase,
120 boolean searchDescription, boolean ignoreHidden)
122 doFind(theSearchString, matchCase, searchDescription, false,
125 if (searchResults.isEmpty() && idMatches.isEmpty())
128 * search failed - reset to start for next search
136 * Performs a 'find next' or 'find all'
138 * @param theSearchString
140 * @param searchDescription
142 * @param ignoreHidden
144 protected void doFind(String theSearchString, boolean matchCase,
145 boolean searchDescription, boolean findAll, boolean ignoreHidden)
147 searchResults = new SearchResults();
148 idMatches = new ArrayList<>();
150 String searchString = matchCase ? theSearchString
151 : theSearchString.toUpperCase();
152 Regex searchPattern = new Regex(searchString);
153 searchPattern.setIgnoreCase(!matchCase);
155 SequenceGroup selection = viewport.getSelectionGroup();
156 if (selection != null && selection.getSize() < 1)
158 selection = null; // ? ignore column-only selection
161 AlignmentI alignment = viewport.getAlignment();
162 int end = alignment.getHeight();
164 getSequence(ignoreHidden);
166 boolean found = false;
167 while ((!found || findAll) && sequenceIndex < end)
169 found = findNextMatch(searchString, searchPattern, searchDescription,
175 * Calculates and saves the sequence string to search. The string is restricted
176 * to the current selection region if there is one, and is saved with all gaps
179 * If there are hidden columns, and option {@ignoreHidden} is selected, then
180 * only visible positions of the sequence are included, and a mapping is also
181 * constructed from the returned string positions to the true sequence
184 * Note we have to do this each time {@code findNext} or {@code findAll} is
185 * called, in case the alignment, selection group or hidden columns have
186 * changed. In particular, if the sequence at offset {@code sequenceIndex} in
187 * the alignment is (no longer) in the selection group, search is advanced to
188 * the next sequence that is.
190 * Sets sequence string to the empty string if there are no more sequences (in
191 * selection group if any) at or after {@code sequenceIndex}.
193 * Returns true if a sequence could be found, false if end of alignment was
196 * @param ignoreHidden
199 private boolean getSequence(boolean ignoreHidden)
201 AlignmentI alignment = viewport.getAlignment();
202 if (sequenceIndex >= alignment.getHeight())
207 SequenceI seq = alignment.getSequenceAt(sequenceIndex);
208 SequenceGroup selection = viewport.getSelectionGroup();
209 if (selection != null && !selection.contains(seq))
211 if (!nextSequence(ignoreHidden))
215 seq = alignment.getSequenceAt(sequenceIndex);
218 String seqString = null;
221 seqString = getVisibleSequence(seq);
222 this.searchedSequenceStartPosition = 1;
227 int endCol = seq.getLength() - 1;
228 this.searchedSequenceStartPosition = seq.getStart();
229 if (selection != null)
231 startCol = selection.getStartRes();
232 endCol = Math.min(endCol, selection.getEndRes());
233 this.searchedSequenceStartPosition = seq.findPosition(startCol);
235 seqString = seq.getSequenceAsString(startCol, endCol + 1);
239 * remove gaps; note that even if this leaves an empty string, we 'search'
240 * the sequence anyway (for possible match on name or description)
242 String ungapped = AlignSeq.extractGaps(Comparison.GapChars, seqString);
243 this.seqToSearch = ungapped;
249 * Returns a string consisting of only the visible residues of {@code seq} from
250 * alignment column {@ fromColumn}, restricted to the current selection region
253 * As a side-effect, also computes the mapping from the true sequence positions
254 * to the positions (1, 2, ...) of the returned sequence. This is to allow
255 * search matches in the visible sequence to be converted to sequence positions.
260 private String getVisibleSequence(SequenceI seq)
263 * get start / end columns of sequence and convert to base 0
264 * (so as to match the visible column ranges)
266 int seqStartCol = seq.findIndex(seq.getStart()) - 1;
267 int seqEndCol = seq.findIndex(seq.getStart() + seq.getLength() - 1) - 1;
268 Iterator<int[]> visibleColumns = viewport.getViewAsVisibleContigs(true);
269 StringBuilder visibleSeq = new StringBuilder(seqEndCol - seqStartCol);
270 List<int[]> fromRanges = new ArrayList<>();
272 while (visibleColumns.hasNext())
274 int[] range = visibleColumns.next();
275 if (range[0] > seqEndCol)
277 // beyond the end of the sequence
280 if (range[1] < seqStartCol)
282 // before the start of the sequence
285 String subseq = seq.getSequenceAsString(range[0], range[1] + 1);
286 String ungapped = AlignSeq.extractGaps(Comparison.GapChars, subseq);
287 visibleSeq.append(ungapped);
288 if (!ungapped.isEmpty())
291 * visible region includes at least one non-gap character,
292 * so add the range to the mapping being constructed
294 int seqResFrom = seq.findPosition(range[0]);
295 int seqResTo = seqResFrom + ungapped.length() - 1;
296 fromRanges.add(new int[] { seqResFrom, seqResTo });
301 * construct the mapping
302 * from: visible sequence positions 1..length
303 * to: true residue positions of the alignment sequence
305 List<int[]> toRange = Arrays
307 { 1, visibleSeq.length() });
308 searchedSequenceMap = new MapList(fromRanges, toRange, 1, 1);
310 return visibleSeq.toString();
314 * Advances the search to the next sequence in the alignment. Sequences not in
315 * the current selection group (if there is one) are skipped. The (sub-)sequence
316 * to be searched is extracted, gaps removed, and saved, or set to null if there
317 * are no more sequences to search.
319 * Returns true if a sequence could be found, false if end of alignment was
322 * @param ignoreHidden
324 private boolean nextSequence(boolean ignoreHidden)
329 return getSequence(ignoreHidden);
333 * Finds the next match in the given sequence, starting at offset
334 * {@code residueIndex}. Answers true if a match is found, else false.
336 * If a match is found, {@code residueIndex} is advanced to the position after
337 * the start of the matched region, ready for the next search.
339 * If no match is found, {@code sequenceIndex} is advanced ready to search the
343 * @param searchString
344 * @param searchPattern
345 * @param matchDescription
346 * @param ignoreHidden
349 protected boolean findNextMatch(String searchString,
350 Regex searchPattern, boolean matchDescription,
351 boolean ignoreHidden)
353 if (residueIndex < 0)
356 * at start of sequence; try find by residue number, in sequence id,
357 * or (optionally) in sequence description
359 if (doNonMotifSearches(searchString, searchPattern,
367 * search for next match in sequence string
369 int end = seqToSearch.length();
370 while (residueIndex < end)
372 boolean matched = searchPattern.searchFrom(seqToSearch, residueIndex);
375 if (recordMatch(searchPattern, ignoreHidden))
382 residueIndex = Integer.MAX_VALUE;
386 nextSequence(ignoreHidden);
391 * Adds the match held in the <code>searchPattern</code> Regex to the
392 * <code>searchResults</code>, unless it is a subregion of the last match
393 * recorded. <code>residueIndex</code> is advanced to the position after the
394 * start of the matched region, ready for the next search. Answers true if a
395 * match was added, else false.
397 * Matches that lie entirely within hidden regions of the alignment are not
400 * @param searchPattern
401 * @param ignoreHidden
404 protected boolean recordMatch(Regex searchPattern, boolean ignoreHidden)
406 SequenceI seq = viewport.getAlignment().getSequenceAt(sequenceIndex);
409 * convert start/end of the match to sequence coordinates
411 int offset = searchPattern.matchedFrom();
412 int matchStartPosition = this.searchedSequenceStartPosition + offset;
413 int matchEndPosition = matchStartPosition
414 + searchPattern.charsMatched() - 1;
417 * update residueIndex to next position after the start of the match
418 * (findIndex returns a value base 1, columnIndex is held base 0)
420 residueIndex = searchPattern.matchedFrom()+1;
423 * return false if the match is entirely in a hidden region
425 if (allHidden(seq, matchStartPosition, matchEndPosition))
431 * check that this match is not a subset of the previous one (JAL-2302)
433 List<SearchResultMatchI> matches = searchResults.getResults();
434 SearchResultMatchI lastMatch = matches.isEmpty() ? null
435 : matches.get(matches.size() - 1);
437 if (lastMatch == null || !lastMatch.contains(seq, matchStartPosition,
440 addMatch(seq, matchStartPosition, matchEndPosition, ignoreHidden);
448 * Adds one match to the stored list. If hidden residues are being skipped, then
449 * the match may need to be split into contiguous positions of the sequence (so
450 * it does not include skipped residues).
453 * @param matchStartPosition
454 * @param matchEndPosition
455 * @param ignoreHidden
457 private void addMatch(SequenceI seq, int matchStartPosition,
458 int matchEndPosition, boolean ignoreHidden)
465 searchResults.addResult(seq, matchStartPosition, matchEndPosition);
470 * get start-end contiguous ranges in underlying sequence
472 int[] truePositions = searchedSequenceMap
473 .locateInFrom(matchStartPosition, matchEndPosition);
474 searchResults.addResult(seq, truePositions);
478 * Returns true if all residues are hidden, else false
485 private boolean allHidden(SequenceI seq, int fromPos, int toPos)
487 if (!viewport.hasHiddenColumns())
491 for (int res = fromPos; res <= toPos; res++)
493 if (isVisible(seq, res))
502 * Does searches other than for residue patterns. Currently this includes
504 * <li>find residue by position (if search string is a number)</li>
505 * <li>match search string to sequence id</li>
506 * <li>match search string to sequence description (optional)</li>
508 * Answers true if a match is found, else false.
510 * @param searchString
511 * @param searchPattern
512 * @param includeDescription
515 protected boolean doNonMotifSearches(String searchString,
516 Regex searchPattern, boolean includeDescription)
518 SequenceI seq = viewport.getAlignment().getSequenceAt(sequenceIndex);
521 * position sequence search to start of sequence
526 int res = Integer.parseInt(searchString);
527 return searchForResidueNumber(seq, res);
528 } catch (NumberFormatException ex)
530 // search pattern is not a number
533 if (searchSequenceName(seq, searchPattern))
537 if (includeDescription && searchSequenceDescription(seq, searchPattern))
545 * Searches for a match with the sequence description, and if found, adds the
546 * sequence to the list of match ids (but not as a duplicate). Answers true if
547 * a match was added, else false.
550 * @param searchPattern
553 protected boolean searchSequenceDescription(SequenceI seq, Regex searchPattern)
555 String desc = seq.getDescription();
556 if (desc != null && searchPattern.search(desc) && !idMatches.contains(seq))
565 * Searches for a match with the sequence name, and if found, adds the
566 * sequence to the list of match ids (but not as a duplicate). Answers true if
567 * a match was added, else false.
570 * @param searchPattern
573 protected boolean searchSequenceName(SequenceI seq, Regex searchPattern)
575 if (searchPattern.search(seq.getName()) && !idMatches.contains(seq))
584 * If the residue position is valid for the sequence, and in a visible column,
585 * adds the position to the search results and returns true, else answers false.
591 protected boolean searchForResidueNumber(SequenceI seq, int resNo)
593 if (seq.getStart() <= resNo && seq.getEnd() >= resNo)
595 if (isVisible(seq, resNo))
597 searchResults.addResult(seq, resNo, resNo);
605 * Returns true if the residue is in a visible column, else false
611 private boolean isVisible(SequenceI seq, int res)
613 if (!viewport.hasHiddenColumns())
617 int col = seq.findIndex(res); // base 1
618 return viewport.getAlignment().getHiddenColumns().isVisible(col - 1); // base 0
622 public List<SequenceI> getIdMatches()
628 public SearchResultsI getSearchResults()
630 return searchResults;