Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[jalview.git] / src / jalview / analysis / Finder.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.analysis;
22
23 import java.util.Locale;
24
25 import jalview.api.AlignViewportI;
26 import jalview.api.FinderI;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultMatchI;
29 import jalview.datamodel.SearchResults;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.util.Comparison;
34 import jalview.util.Platform;
35 import jalview.util.MapList;
36
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Iterator;
40 import java.util.List;
41
42 import com.stevesoft.pat.Regex;
43
44 /**
45  * Implements the search algorithm for the Find dialog
46  */
47 public class Finder implements FinderI
48 {
49   /*
50    * matched residue locations
51    */
52   private SearchResultsI searchResults;
53
54   /*
55    * sequences matched by id or description
56    */
57   private List<SequenceI> idMatches;
58
59   /*
60    * the viewport to search over
61    */
62   private AlignViewportI viewport;
63
64   /*
65    * sequence index in alignment to search from
66    */
67   private int sequenceIndex;
68
69   /*
70    * position offset in sequence to search from, base 0
71    * (position after start of last match for a 'find next')
72    */
73   private int residueIndex;
74
75   /*
76    * the true sequence position of the start of the 
77    * last sequence searched (when 'ignore hidden regions' does not apply)
78    */
79   private int searchedSequenceStartPosition;
80
81   /*
82    * when 'ignore hidden regions' applies, this holds the mapping from
83    * the visible sequence positions (1, 2, ...) to true sequence positions
84    */
85   private MapList searchedSequenceMap;
86
87   private String seqToSearch;
88
89   /**
90    * Constructor for searching a viewport
91    * 
92    * @param av
93    */
94   public Finder(AlignViewportI av)
95   {
96     this.viewport = av;
97     this.sequenceIndex = 0;
98     this.residueIndex = -1;
99   }
100
101   @Override
102   public void findAll(String theSearchString, boolean matchCase,
103           boolean searchDescription, boolean ignoreHidden)
104   {
105     /*
106      * search from the start
107      */
108     sequenceIndex = 0;
109     residueIndex = -1;
110
111     doFind(theSearchString, matchCase, searchDescription, true,
112             ignoreHidden);
113
114     /*
115      * reset to start for next search
116      */
117     sequenceIndex = 0;
118     residueIndex = -1;
119   }
120
121   @Override
122   public void findNext(String theSearchString, boolean matchCase,
123           boolean searchDescription, boolean ignoreHidden)
124   {
125     doFind(theSearchString, matchCase, searchDescription, false,
126             ignoreHidden);
127     
128     if (searchResults.isEmpty() && idMatches.isEmpty())
129     {
130       /*
131        * search failed - reset to start for next search
132        */
133       sequenceIndex = 0;
134       residueIndex = -1;
135     }
136   }
137
138   /**
139    * Performs a 'find next' or 'find all'
140    * 
141    * @param theSearchString
142    * @param matchCase
143    * @param searchDescription
144    * @param findAll
145    * @param ignoreHidden
146    */
147   protected void doFind(String theSearchString, boolean matchCase,
148           boolean searchDescription, boolean findAll, boolean ignoreHidden)
149   {
150     searchResults = new SearchResults();
151     idMatches = new ArrayList<>();
152
153     String searchString = matchCase ? theSearchString
154             : theSearchString.toUpperCase(Locale.ROOT);
155   Regex searchPattern = Platform.newRegex(searchString);
156     searchPattern.setIgnoreCase(!matchCase);
157
158     SequenceGroup selection = viewport.getSelectionGroup();
159     if (selection != null && selection.getSize() < 1)
160     {
161       selection = null; // ? ignore column-only selection
162     }
163
164     AlignmentI alignment = viewport.getAlignment();
165     int end = alignment.getHeight();
166
167     getSequence(ignoreHidden);
168
169     boolean found = false;
170     while ((!found || findAll) && sequenceIndex < end)
171     {
172       found = findNextMatch(searchString, searchPattern, searchDescription,
173               ignoreHidden);
174     }
175   }
176
177   /**
178    * Calculates and saves the sequence string to search. The string is restricted
179    * to the current selection region if there is one, and is saved with all gaps
180    * removed.
181    * <p>
182    * If there are hidden columns, and option {@ignoreHidden} is selected, then
183    * only visible positions of the sequence are included, and a mapping is also
184    * constructed from the returned string positions to the true sequence
185    * positions.
186    * <p>
187    * Note we have to do this each time {@code findNext} or {@code findAll} is
188    * called, in case the alignment, selection group or hidden columns have
189    * changed. In particular, if the sequence at offset {@code sequenceIndex} in
190    * the alignment is (no longer) in the selection group, search is advanced to
191    * the next sequence that is.
192    * <p>
193    * Sets sequence string to the empty string if there are no more sequences (in
194    * selection group if any) at or after {@code sequenceIndex}.
195    * <p>
196    * Returns true if a sequence could be found, false if end of alignment was
197    * reached
198    * 
199    * @param ignoreHidden
200    * @return
201    */
202   private boolean getSequence(boolean ignoreHidden)
203   {
204     AlignmentI alignment = viewport.getAlignment();
205     if (sequenceIndex >= alignment.getHeight())
206     {
207       seqToSearch = "";
208       return false;
209     }
210     SequenceI seq = alignment.getSequenceAt(sequenceIndex);
211     SequenceGroup selection = viewport.getSelectionGroup();
212     if (selection != null && !selection.contains(seq))
213     {
214       if (!nextSequence(ignoreHidden))
215       {
216         return false;
217       }
218       seq = alignment.getSequenceAt(sequenceIndex);
219     }
220
221     String seqString = null;
222     if (ignoreHidden)
223     {
224       seqString = getVisibleSequence(seq);
225       this.searchedSequenceStartPosition = 1;
226     }
227     else
228     {
229       int startCol = 0;
230       int endCol = seq.getLength() - 1;
231       this.searchedSequenceStartPosition = seq.getStart();
232       if (selection != null)
233       {
234         startCol = selection.getStartRes();
235         endCol = Math.min(endCol, selection.getEndRes());
236         this.searchedSequenceStartPosition = seq.findPosition(startCol);
237       }
238       seqString = seq.getSequenceAsString(startCol, endCol + 1);
239     }
240
241     /*
242      * remove gaps; note that even if this leaves an empty string, we 'search'
243      * the sequence anyway (for possible match on name or description)
244      */
245     String ungapped = AlignSeq.extractGaps(Comparison.GapChars, seqString);
246     this.seqToSearch = ungapped;
247
248     return true;
249   }
250
251   /**
252    * Returns a string consisting of only the visible residues of {@code seq} from
253    * alignment column {@ fromColumn}, restricted to the current selection region
254    * if there is one.
255    * <p>
256    * As a side-effect, also computes the mapping from the true sequence positions
257    * to the positions (1, 2, ...) of the returned sequence. This is to allow
258    * search matches in the visible sequence to be converted to sequence positions.
259    * 
260    * @param seq
261    * @return
262    */
263   private String getVisibleSequence(SequenceI seq)
264   {
265     /*
266      * get start / end columns of sequence and convert to base 0
267      * (so as to match the visible column ranges)
268      */
269     int seqStartCol = seq.findIndex(seq.getStart()) - 1;
270     int seqEndCol = seq.findIndex(seq.getStart() + seq.getLength() - 1) - 1;
271     Iterator<int[]> visibleColumns = viewport.getViewAsVisibleContigs(true);
272     StringBuilder visibleSeq = new StringBuilder(seqEndCol - seqStartCol);
273     List<int[]> fromRanges = new ArrayList<>();
274
275     while (visibleColumns.hasNext())
276     {
277       int[] range = visibleColumns.next();
278       if (range[0] > seqEndCol)
279       {
280         // beyond the end of the sequence
281         break;
282       }
283       if (range[1] < seqStartCol)
284       {
285         // before the start of the sequence
286         continue;
287       }
288       String subseq = seq.getSequenceAsString(range[0], range[1] + 1);
289       String ungapped = AlignSeq.extractGaps(Comparison.GapChars, subseq);
290       visibleSeq.append(ungapped);
291       if (!ungapped.isEmpty())
292       {
293         /*
294          * visible region includes at least one non-gap character,
295          * so add the range to the mapping being constructed
296          */
297         int seqResFrom = seq.findPosition(range[0]);
298         int seqResTo = seqResFrom + ungapped.length() - 1;
299         fromRanges.add(new int[] { seqResFrom, seqResTo });
300       }
301     }
302
303     /*
304      * construct the mapping
305      * from: visible sequence positions 1..length
306      * to:   true residue positions of the alignment sequence
307      */
308     List<int[]> toRange = Arrays
309             .asList(new int[]
310             { 1, visibleSeq.length() });
311     searchedSequenceMap = new MapList(fromRanges, toRange, 1, 1);
312
313     return visibleSeq.toString();
314   }
315
316   /**
317    * Advances the search to the next sequence in the alignment. Sequences not in
318    * the current selection group (if there is one) are skipped. The (sub-)sequence
319    * to be searched is extracted, gaps removed, and saved, or set to null if there
320    * are no more sequences to search.
321    * <p>
322    * Returns true if a sequence could be found, false if end of alignment was
323    * reached
324    * 
325    * @param ignoreHidden
326    */
327   private boolean nextSequence(boolean ignoreHidden)
328   {
329     sequenceIndex++;
330     residueIndex = -1;
331
332     return getSequence(ignoreHidden);
333   }
334
335   /**
336    * Finds the next match in the given sequence, starting at offset
337    * {@code residueIndex}. Answers true if a match is found, else false.
338    * <p>
339    * If a match is found, {@code residueIndex} is advanced to the position after
340    * the start of the matched region, ready for the next search.
341    * <p>
342    * If no match is found, {@code sequenceIndex} is advanced ready to search the
343    * next sequence.
344    * 
345    * @param seqToSearch
346    * @param searchString
347    * @param searchPattern
348    * @param matchDescription
349    * @param ignoreHidden
350    * @return
351    */
352   protected boolean findNextMatch(String searchString,
353           Regex searchPattern, boolean matchDescription,
354           boolean ignoreHidden)
355   {
356     if (residueIndex < 0)
357     {
358       /*
359        * at start of sequence; try find by residue number, in sequence id,
360        * or (optionally) in sequence description
361        */
362       if (doNonMotifSearches(searchString, searchPattern,
363               matchDescription))
364       {
365         return true;
366       }
367     }
368
369     /*
370      * search for next match in sequence string
371      */
372     int end = seqToSearch.length();
373     while (residueIndex < end)
374     {
375       boolean matched = searchPattern.searchFrom(seqToSearch, residueIndex);
376       if (matched)
377       {
378         if (recordMatch(searchPattern, ignoreHidden))
379         {
380           return true;
381         }
382       }
383       else
384       {
385         residueIndex = Integer.MAX_VALUE;
386       }
387     }
388
389     nextSequence(ignoreHidden);
390     return false;
391   }
392
393   /**
394    * Adds the match held in the <code>searchPattern</code> Regex to the
395    * <code>searchResults</code>, unless it is a subregion of the last match
396    * recorded. <code>residueIndex</code> is advanced to the position after the
397    * start of the matched region, ready for the next search. Answers true if a
398    * match was added, else false.
399    * <p>
400    * Matches that lie entirely within hidden regions of the alignment are not
401    * added.
402    * 
403    * @param searchPattern
404    * @param ignoreHidden
405    * @return
406    */
407   protected boolean recordMatch(Regex searchPattern, boolean ignoreHidden)
408   {
409     SequenceI seq = viewport.getAlignment().getSequenceAt(sequenceIndex);
410
411     /*
412      * convert start/end of the match to sequence coordinates
413      */
414     int offset = searchPattern.matchedFrom();
415     int matchStartPosition = this.searchedSequenceStartPosition + offset;
416     int matchEndPosition = matchStartPosition
417             + searchPattern.charsMatched() - 1;
418
419     /*
420      * update residueIndex to next position after the start of the match
421      * (findIndex returns a value base 1, columnIndex is held base 0)
422      */
423     residueIndex = searchPattern.matchedFrom()+1;
424
425     /*
426      * return false if the match is entirely in a hidden region
427      */
428     if (allHidden(seq, matchStartPosition, matchEndPosition))
429     {
430       return false;
431     }
432
433     /*
434      * check that this match is not a subset of the previous one (JAL-2302)
435      */
436     List<SearchResultMatchI> matches = searchResults.getResults();
437     SearchResultMatchI lastMatch = matches.isEmpty() ? null
438             : matches.get(matches.size() - 1);
439
440     if (lastMatch == null || !lastMatch.contains(seq, matchStartPosition,
441             matchEndPosition))
442     {
443       addMatch(seq, matchStartPosition, matchEndPosition, ignoreHidden);
444       return true;
445     }
446
447     return false;
448   }
449
450   /**
451    * Adds one match to the stored list. If hidden residues are being skipped, then
452    * the match may need to be split into contiguous positions of the sequence (so
453    * it does not include skipped residues).
454    * 
455    * @param seq
456    * @param matchStartPosition
457    * @param matchEndPosition
458    * @param ignoreHidden
459    */
460   private void addMatch(SequenceI seq, int matchStartPosition,
461           int matchEndPosition, boolean ignoreHidden)
462   {
463     if (!ignoreHidden)
464     {
465       /*
466        * simple case
467        */
468       searchResults.addResult(seq, matchStartPosition, matchEndPosition);
469       return;
470     }
471
472     /*
473      *  get start-end contiguous ranges in underlying sequence
474      */
475     int[] truePositions = searchedSequenceMap
476             .locateInFrom(matchStartPosition, matchEndPosition);
477     searchResults.addResult(seq, truePositions);
478   }
479
480   /**
481    * Returns true if all residues are hidden, else false
482    * 
483    * @param seq
484    * @param fromPos
485    * @param toPos
486    * @return
487    */
488   private boolean allHidden(SequenceI seq, int fromPos, int toPos)
489   {
490     if (!viewport.hasHiddenColumns())
491     {
492       return false;
493     }
494     for (int res = fromPos; res <= toPos; res++)
495     {
496       if (isVisible(seq, res))
497       {
498         return false;
499       }
500     }
501     return true;
502   }
503
504   /**
505    * Does searches other than for residue patterns. Currently this includes
506    * <ul>
507    * <li>find residue by position (if search string is a number)</li>
508    * <li>match search string to sequence id</li>
509    * <li>match search string to sequence description (optional)</li>
510    * </ul>
511    * Answers true if a match is found, else false.
512    * 
513    * @param searchString
514    * @param searchPattern
515    * @param includeDescription
516    * @return
517    */
518   protected boolean doNonMotifSearches(String searchString,
519           Regex searchPattern, boolean includeDescription)
520   {
521     SequenceI seq = viewport.getAlignment().getSequenceAt(sequenceIndex);
522
523     /*
524      * position sequence search to start of sequence
525      */
526     residueIndex = 0;
527     try
528     {
529       int res = Integer.parseInt(searchString);
530       return searchForResidueNumber(seq, res);
531     } catch (NumberFormatException ex)
532     {
533       // search pattern is not a number
534     }
535
536     if (searchSequenceName(seq, searchPattern))
537     {
538       return true;
539     }
540     if (includeDescription && searchSequenceDescription(seq, searchPattern))
541     {
542       return true;
543     }
544     return false;
545   }
546
547   /**
548    * Searches for a match with the sequence description, and if found, adds the
549    * sequence to the list of match ids (but not as a duplicate). Answers true if
550    * a match was added, else false.
551    * 
552    * @param seq
553    * @param searchPattern
554    * @return
555    */
556   protected boolean searchSequenceDescription(SequenceI seq, Regex searchPattern)
557   {
558     String desc = seq.getDescription();
559     if (desc != null && searchPattern.search(desc) && !idMatches.contains(seq))
560     {
561       idMatches.add(seq);
562       return true;
563     }
564     return false;
565   }
566
567   /**
568    * Searches for a match with the sequence name, and if found, adds the
569    * sequence to the list of match ids (but not as a duplicate). Answers true if
570    * a match was added, else false.
571    * 
572    * @param seq
573    * @param searchPattern
574    * @return
575    */
576   protected boolean searchSequenceName(SequenceI seq, Regex searchPattern)
577   {
578     if (searchPattern.search(seq.getName()) && !idMatches.contains(seq))
579     {
580       idMatches.add(seq);
581       return true;
582     }
583     return false;
584   }
585
586   /**
587    * If the residue position is valid for the sequence, and in a visible column,
588    * adds the position to the search results and returns true, else answers false.
589    * 
590    * @param seq
591    * @param resNo
592    * @return
593    */
594   protected boolean searchForResidueNumber(SequenceI seq, int resNo)
595   {
596     if (seq.getStart() <= resNo && seq.getEnd() >= resNo)
597     {
598       if (isVisible(seq, resNo))
599       {
600         searchResults.addResult(seq, resNo, resNo);
601         return true;
602       }
603     }
604     return false;
605   }
606
607   /**
608    * Returns true if the residue is in a visible column, else false
609    * 
610    * @param seq
611    * @param res
612    * @return
613    */
614   private boolean isVisible(SequenceI seq, int res)
615   {
616     if (!viewport.hasHiddenColumns())
617     {
618       return true;
619     }
620     int col = seq.findIndex(res); // base 1
621     return viewport.getAlignment().getHiddenColumns().isVisible(col - 1); // base 0
622   }
623
624   @Override
625   public List<SequenceI> getIdMatches()
626   {
627     return idMatches;
628   }
629
630   @Override
631   public SearchResultsI getSearchResults()
632   {
633     return searchResults;
634   }
635 }