JAL-345 javadoc and note about JAL-2300
[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.Arrays;
25 import java.util.BitSet;
26 import java.util.List;
27
28 /**
29  * Holds a list of search result matches, where each match is a contiguous
30  * stretch of a single sequence.
31  * 
32  * @author gmcarstairs amwaterhouse
33  *
34  */
35 public class SearchResults implements SearchResultsI
36 {
37
38   private List<SearchResultMatchI> matches = new ArrayList<SearchResultMatchI>();
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     SequenceI sequence;
47
48     /**
49      * Start position of match in sequence (base 1)
50      */
51     int start;
52
53     /**
54      * End position (inclusive) (base 1)
55      */
56     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     /* (non-Javadoc)
96      * @see jalview.datamodel.SearchResultMatchI#getSequence()
97      */
98     @Override
99     public SequenceI getSequence()
100     {
101       return sequence;
102     }
103
104     /* (non-Javadoc)
105      * @see jalview.datamodel.SearchResultMatchI#getStart()
106      */
107     @Override
108     public int getStart()
109     {
110       return start;
111     }
112
113     /* (non-Javadoc)
114      * @see jalview.datamodel.SearchResultMatchI#getEnd()
115      */
116     @Override
117     public int getEnd()
118     {
119       return end;
120     }
121
122     /**
123      * Returns the string of characters in the matched region, prefixed by the
124      * start position, e.g. "12CGT" or "208K"
125      */
126     @Override
127     public String toString()
128     {
129       final int from = Math.max(start - 1, 0);
130       String startPosition = String.valueOf(from);
131       return startPosition + getCharacters();
132     }
133
134     /* (non-Javadoc)
135      * @see jalview.datamodel.SearchResultMatchI#getCharacters()
136      */
137     @Override
138     public String getCharacters()
139     {
140       char[] chars = sequence.getSequence();
141       // convert start/end to base 0 (with bounds check)
142       final int from = Math.max(start - 1, 0);
143       final int to = Math.min(end, chars.length + 1);
144       return String.valueOf(Arrays.copyOfRange(chars, from, to));
145     }
146
147     public void setSequence(SequenceI seq)
148     {
149       this.sequence = seq;
150     }
151
152     /**
153      * Hashcode is the hashcode of the matched sequence plus a hash of start and
154      * end positions. Match objects that pass the test for equals are guaranteed
155      * to have the same hashcode.
156      */
157     @Override
158     public int hashCode()
159     {
160       int hash = sequence == null ? 0 : sequence.hashCode();
161       hash += 31 * start;
162       hash += 67 * end;
163       return hash;
164     }
165
166     /**
167      * Two Match objects are equal if they are for the same sequence, start and
168      * end positions
169      */
170     @Override
171     public boolean equals(Object obj)
172     {
173       if (obj == null || !(obj instanceof SearchResultMatchI))
174       {
175         return false;
176       }
177       SearchResultMatchI m = (SearchResultMatchI) obj;
178       return (sequence == m.getSequence() && start == m.getStart() && end == m
179               .getEnd());
180     }
181   }
182
183   /* (non-Javadoc)
184    * @see jalview.datamodel.SearchResultsI#addResult(jalview.datamodel.SequenceI, int, int)
185    */
186   @Override
187   public SearchResultMatchI addResult(SequenceI seq, int start, int end)
188   {
189     Match m = new Match(seq, start, end);
190     matches.add(m);
191     return m;
192   }
193
194   /* (non-Javadoc)
195    * @see jalview.datamodel.SearchResultsI#involvesSequence(jalview.datamodel.SequenceI)
196    */
197   @Override
198   public boolean involvesSequence(SequenceI sequence)
199   {
200     SequenceI ds = sequence.getDatasetSequence();
201     Match m;
202     for (SearchResultMatchI _m : matches)
203     {
204       m = (Match) _m;
205       if (m.sequence != null
206               && (m.sequence == sequence || m.sequence == ds))
207       {
208         return true;
209       }
210     }
211     return false;
212   }
213
214   /* (non-Javadoc)
215    * @see jalview.datamodel.SearchResultsI#getResults(jalview.datamodel.SequenceI, int, int)
216    */
217   @Override
218   public int[] getResults(SequenceI sequence, int start, int end)
219   {
220     if (matches.isEmpty())
221     {
222       return null;
223     }
224
225     int[] result = null;
226     int[] tmp = null;
227     int resultLength, matchStart = 0, matchEnd = 0;
228     boolean mfound;
229     Match m;
230     for (SearchResultMatchI _m : matches)
231     {
232       m = (Match) _m;
233
234       mfound = false;
235       if (m.sequence == sequence)
236       {
237         mfound = true;
238         // locate aligned position
239         matchStart = sequence.findIndex(m.start) - 1;
240         matchEnd = sequence.findIndex(m.end) - 1;
241       }
242       else if (m.sequence == sequence.getDatasetSequence())
243       {
244         mfound = true;
245         // locate region in local context
246         matchStart = sequence.findIndex(m.start) - 1;
247         matchEnd = sequence.findIndex(m.end) - 1;
248       }
249       if (mfound)
250       {
251         if (matchStart <= end && matchEnd >= start)
252         {
253           if (matchStart < start)
254           {
255             matchStart = start;
256           }
257
258           if (matchEnd > end)
259           {
260             matchEnd = end;
261           }
262
263           if (result == null)
264           {
265             result = new int[] { matchStart, matchEnd };
266           }
267           else
268           {
269             resultLength = result.length;
270             tmp = new int[resultLength + 2];
271             System.arraycopy(result, 0, tmp, 0, resultLength);
272             result = tmp;
273             result[resultLength] = matchStart;
274             result[resultLength + 1] = matchEnd;
275           }
276         }
277         else
278         {
279           // debug
280           // System.err.println("Outwith bounds!" + matchStart+">"+end +"  or "
281           // + matchEnd+"<"+start);
282         }
283       }
284     }
285     return result;
286   }
287
288   @Override
289   public int markColumns(SequenceCollectionI sqcol, BitSet bs)
290   {
291     int count = 0;
292     BitSet mask = new BitSet();
293     for (SequenceI s : sqcol.getSequences())
294     {
295       int[] cols = getResults(s, sqcol.getStartRes(), sqcol.getEndRes());
296       if (cols != null)
297       {
298         for (int pair = 0; pair < cols.length; pair += 2)
299         {
300           mask.set(cols[pair], cols[pair + 1] + 1);
301         }
302       }
303     }
304     // compute columns that were newly selected
305     BitSet original = (BitSet) bs.clone();
306     original.and(mask);
307     count = mask.cardinality() - original.cardinality();
308     // and mark ranges not already marked
309     bs.or(mask);
310     return count;
311   }
312
313   /* (non-Javadoc)
314    * @see jalview.datamodel.SearchResultsI#getSize()
315    */
316   @Override
317   public int getSize()
318   {
319     return matches.size();
320   }
321
322   /* (non-Javadoc)
323    * @see jalview.datamodel.SearchResultsI#getResultSequence(int)
324    */
325   @Override
326   public SequenceI getResultSequence(int index)
327   {
328     return matches.get(index).getSequence();
329   }
330
331   /* (non-Javadoc)
332    * @see jalview.datamodel.SearchResultsI#getResultStart(int)
333    */
334   @Override
335   public int getResultStart(int i)
336   {
337     return matches.get(i).getStart();
338   }
339
340   /* (non-Javadoc)
341    * @see jalview.datamodel.SearchResultsI#getResultEnd(int)
342    */
343   @Override
344   public int getResultEnd(int i)
345   {
346     return matches.get(i).getEnd();
347   }
348
349   /* (non-Javadoc)
350    * @see jalview.datamodel.SearchResultsI#isEmpty()
351    */
352   @Override
353   public boolean isEmpty()
354   {
355     return matches.isEmpty();
356   }
357
358   /* (non-Javadoc)
359    * @see jalview.datamodel.SearchResultsI#getResults()
360    */
361   @Override
362   public List<SearchResultMatchI> getResults()
363   {
364     return matches;
365   }
366
367   /**
368    * Return the results as a string of characters (bases) prefixed by start
369    * position(s). Meant for use when the context ensures that all matches are to
370    * regions of the same sequence (otherwise the result is meaningless).
371    * 
372    * @return
373    */
374   @Override
375   public String toString()
376   {
377     StringBuilder result = new StringBuilder(256);
378     for (SearchResultMatchI m : matches)
379     {
380       result.append(m.toString());
381     }
382     return result.toString();
383   }
384
385   /**
386    * Return the results as a string of characters (bases). Meant for use when
387    * the context ensures that all matches are to regions of the same sequence
388    * (otherwise the result is meaningless).
389    * 
390    * @return
391    */
392   public String getCharacters()
393   {
394     StringBuilder result = new StringBuilder(256);
395     for (SearchResultMatchI m : matches)
396     {
397       result.append(m.getCharacters());
398     }
399     return result.toString();
400   }
401
402   /**
403    * Hashcode is has derived from the list of matches. This ensures that when
404    * two SearchResults objects satisfy the test for equals(), then they have the
405    * same hashcode.
406    */
407   @Override
408   public int hashCode()
409   {
410     return matches.hashCode();
411   }
412
413   /**
414    * Two SearchResults are considered equal if they contain the same matches in
415    * the same order.
416    */
417   @Override
418   public boolean equals(Object obj)
419   {
420     if (obj == null || !(obj instanceof SearchResultsI))
421     {
422       return false;
423     }
424     SearchResultsI sr = (SearchResultsI) obj;
425     return matches.equals(sr.getResults());
426   }
427 }