JAL-3490 match count independent of contiguous matches count
[jalview.git] / src / jalview / datamodel / SearchResults.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.datamodel;
22
23 import java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.List;
26
27 /**
28  * Holds a list of search result matches, where each match is a contiguous
29  * stretch of a single sequence.
30  * 
31  * @author gmcarstairs amwaterhouse
32  *
33  */
34 public class SearchResults implements SearchResultsI
35 {
36   private int count;
37
38   private List<SearchResultMatchI> matches = new ArrayList<>();
39
40   /**
41    * One match consists of a sequence reference, start and end positions.
42    * Discontiguous ranges in a sequence require two or more Match objects.
43    */
44   public class Match implements SearchResultMatchI
45   {
46     final SequenceI sequence;
47
48     /**
49      * Start position of match in sequence (base 1)
50      */
51     final int start;
52
53     /**
54      * End position (inclusive) (base 1)
55      */
56     final int end;
57
58     /**
59      * create a Match on a range of sequence. Match always holds region in
60      * forwards order, even if given in reverse order (such as from a mapping to
61      * a reverse strand); this avoids trouble for routines that highlight search
62      * results etc
63      * 
64      * @param seq
65      *          a sequence
66      * @param start
67      *          start position of matched range (base 1)
68      * @param end
69      *          end of matched range (inclusive, base 1)
70      */
71     public Match(SequenceI seq, int start, int end)
72     {
73       sequence = seq;
74
75       /*
76        * always hold in forwards order, even if given in reverse order
77        * (such as from a mapping to a reverse strand); this avoids
78        * trouble for routines that highlight search results etc
79        */
80       if (start <= end)
81       {
82         this.start = start;
83         this.end = end;
84       }
85       else
86       {
87         // TODO: JBP could mark match as being specified in reverse direction
88         // for use
89         // by caller ? e.g. visualizing reverse strand highlight
90         this.start = end;
91         this.end = start;
92       }
93     }
94
95     @Override
96     public SequenceI getSequence()
97     {
98       return sequence;
99     }
100
101     @Override
102     public int getStart()
103     {
104       return start;
105     }
106
107     @Override
108     public int getEnd()
109     {
110       return end;
111     }
112
113     /**
114      * Returns a representation as "seqid/start-end"
115      */
116     @Override
117     public String toString()
118     {
119       StringBuilder sb = new StringBuilder();
120       if (sequence != null)
121       {
122         sb.append(sequence.getName()).append("/");
123       }
124       sb.append(start).append("-").append(end);
125       return sb.toString();
126     }
127
128     /**
129      * Hashcode is the hashcode of the matched sequence plus a hash of start and
130      * end positions. Match objects that pass the test for equals are guaranteed
131      * to have the same hashcode.
132      */
133     @Override
134     public int hashCode()
135     {
136       int hash = sequence == null ? 0 : sequence.hashCode();
137       hash += 31 * start;
138       hash += 67 * end;
139       return hash;
140     }
141
142     /**
143      * Two Match objects are equal if they are for the same sequence, start and
144      * end positions
145      */
146     @Override
147     public boolean equals(Object obj)
148     {
149       if (obj == null || !(obj instanceof SearchResultMatchI))
150       {
151         return false;
152       }
153       SearchResultMatchI m = (SearchResultMatchI) obj;
154       return (sequence == m.getSequence() && start == m.getStart()
155               && end == m.getEnd());
156     }
157
158     @Override
159     public boolean contains(SequenceI seq, int from, int to)
160     {
161       return (sequence == seq && start <= from && end >= to);
162     }
163   }
164
165   @Override
166   public SearchResultMatchI addResult(SequenceI seq, int start, int end)
167   {
168     Match m = new Match(seq, start, end);
169     if (!matches.contains(m))
170     {
171       matches.add(m);
172       count++;
173     }
174     return m;
175   }
176
177   @Override
178   public void addResult(SequenceI seq, int[] positions)
179   {
180     /*
181      * we only increment the match count by 1 - or not at all,
182      * if the matches are all duplicates of existing
183      */
184     int beforeCount = count;
185     for (int i = 0; i < positions.length - 1; i += 2)
186     {
187       addResult(seq, positions[i], positions[i + 1]);
188     }
189     if (count > beforeCount)
190     {
191       count = beforeCount + 1;
192     }
193   }
194
195   @Override
196   public boolean involvesSequence(SequenceI sequence)
197   {
198     final int start = sequence.getStart();
199     final int end = sequence.getEnd();
200
201     SequenceI ds = sequence.getDatasetSequence();
202     for (SearchResultMatchI m : matches)
203     {
204       SequenceI matched = m.getSequence();
205       if (matched != null && (matched == sequence || matched == ds)
206               && (m.getEnd() >= start) && (m.getStart() <= end))
207       {
208         return true;
209       }
210     }
211     return false;
212   }
213
214   @Override
215   public int[] getResults(SequenceI sequence, int start, int end)
216   {
217     if (matches.isEmpty())
218     {
219       return null;
220     }
221
222     int[] result = null;
223     int[] tmp = null;
224     int resultLength, matchStart = 0, matchEnd = 0;
225     boolean mfound;
226     Match m;
227     for (SearchResultMatchI _m : matches)
228     {
229       m = (Match) _m;
230
231       mfound = false;
232       if (m.sequence == sequence
233               || m.sequence == sequence.getDatasetSequence())
234       {
235         mfound = true;
236         matchStart = sequence.findIndex(m.start) - 1;
237         matchEnd = m.start == m.end ? matchStart : sequence
238                 .findIndex(m.end) - 1;
239       }
240
241       if (mfound)
242       {
243         if (matchStart <= end && matchEnd >= start)
244         {
245           if (matchStart < start)
246           {
247             matchStart = start;
248           }
249
250           if (matchEnd > end)
251           {
252             matchEnd = end;
253           }
254
255           if (result == null)
256           {
257             result = new int[] { matchStart, matchEnd };
258           }
259           else
260           {
261             resultLength = result.length;
262             tmp = new int[resultLength + 2];
263             System.arraycopy(result, 0, tmp, 0, resultLength);
264             result = tmp;
265             result[resultLength] = matchStart;
266             result[resultLength + 1] = matchEnd;
267           }
268         }
269         else
270         {
271           // debug
272           // System.err.println("Outwith bounds!" + matchStart+">"+end +" or "
273           // + matchEnd+"<"+start);
274         }
275       }
276     }
277     return result;
278   }
279
280   @Override
281   public int markColumns(SequenceCollectionI sqcol, BitSet bs)
282   {
283     int count = 0;
284     BitSet mask = new BitSet();
285     int startRes = sqcol.getStartRes();
286     int endRes = sqcol.getEndRes();
287
288     for (SequenceI s : sqcol.getSequences())
289     {
290       int[] cols = getResults(s, startRes, endRes);
291       if (cols != null)
292       {
293         for (int pair = 0; pair < cols.length; pair += 2)
294         {
295           mask.set(cols[pair], cols[pair + 1] + 1);
296         }
297       }
298     }
299     // compute columns that were newly selected
300     BitSet original = (BitSet) bs.clone();
301     original.and(mask);
302     count = mask.cardinality() - original.cardinality();
303     // and mark ranges not already marked
304     bs.or(mask);
305     return count;
306   }
307
308   @Override
309   public int getCount()
310   {
311     return count;
312   }
313
314   @Override
315   public boolean isEmpty()
316   {
317     return matches.isEmpty();
318   }
319
320   @Override
321   public List<SearchResultMatchI> getResults()
322   {
323     return matches;
324   }
325
326   /**
327    * Return the results as a list of matches [seq1/from-to, seq2/from-to, ...]
328    * 
329    * @return
330    */
331   @Override
332   public String toString()
333   {
334     return matches == null ? "" : matches.toString();
335   }
336
337   /**
338    * Hashcode is derived from the list of matches. This ensures that when two
339    * SearchResults objects satisfy the test for equals(), then they have the
340    * same hashcode.
341    * 
342    * @see Match#hashCode()
343    * @see java.util.AbstractList#hashCode()
344    */
345   @Override
346   public int hashCode()
347   {
348     return matches.hashCode();
349   }
350
351   /**
352    * Two SearchResults are considered equal if they contain the same matches in
353    * the same order.
354    */
355   @Override
356   public boolean equals(Object obj)
357   {
358     if (obj == null || !(obj instanceof SearchResultsI))
359     {
360       return false;
361     }
362     SearchResultsI sr = (SearchResultsI) obj;
363     return matches.equals(sr.getResults());
364   }
365
366   @Override
367   public void addSearchResults(SearchResultsI toAdd)
368   {
369     matches.addAll(toAdd.getResults());
370   }
371 }