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