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