JAL-2629 evalues and bit scores now conserved after hmmalign is run
[jalview.git] / src / jalview / analysis / SeqsetUtils.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 jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.HiddenMarkovModel;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29
30 import java.util.Enumeration;
31 import java.util.Hashtable;
32 import java.util.List;
33 import java.util.Vector;
34
35 public class SeqsetUtils
36 {
37
38   /**
39    * Store essential properties of a sequence in a hashtable for later recovery
40    * Keys are Name, Start, End, SeqFeatures, PdbId, HMM
41    * 
42    * @param seq
43    *          SequenceI
44    * @return Hashtable
45    */
46   public static Hashtable SeqCharacterHash(SequenceI seq)
47   {
48     Hashtable sqinfo = new Hashtable();
49     sqinfo.put("Name", seq.getName());
50     sqinfo.put("Start", Integer.valueOf(seq.getStart()));
51     sqinfo.put("End", Integer.valueOf(seq.getEnd()));
52     if (seq.getDescription() != null)
53     {
54       sqinfo.put("Description", seq.getDescription());
55     }
56
57     Vector<SequenceFeature> sfeat = new Vector<>();
58     List<SequenceFeature> sfs = seq.getFeatures().getAllFeatures();
59     sfeat.addAll(sfs);
60
61     if (seq.getDatasetSequence() == null)
62     {
63       sqinfo.put("SeqFeatures", sfeat);
64       sqinfo.put("PdbId",
65               (seq.getAllPDBEntries() != null) ? seq.getAllPDBEntries()
66                       : new Vector<PDBEntry>());
67     }
68     else
69     {
70       sqinfo.put("datasetSequence",
71               (seq.getDatasetSequence() != null) ? seq.getDatasetSequence()
72                       : new Sequence("THISISAPLACEHOLDER", ""));
73     }
74     if (seq.hasHMMProfile())
75     {
76       sqinfo.put("HMM", seq.getHMM());
77     }
78
79     if (seq.getAnnotation("Search Scores") != null)
80     {
81       sqinfo.put("Score", seq.getAnnotation("Search Scores"));
82     }
83
84     return sqinfo;
85   }
86
87   /**
88    * Recover essential properties of a sequence from a hashtable TODO: replace
89    * these methods with something more elegant.
90    * 
91    * @param sq
92    *          SequenceI
93    * @param sqinfo
94    *          Hashtable
95    * @return boolean true if name was not updated from sqinfo Name entry
96    */
97   public static boolean SeqCharacterUnhash(SequenceI sq, Hashtable sqinfo)
98   {
99     boolean namePresent = true;
100     if (sqinfo == null)
101     {
102       return false;
103     }
104     String oldname = (String) sqinfo.get("Name");
105     Integer start = (Integer) sqinfo.get("Start");
106     Integer end = (Integer) sqinfo.get("End");
107     Vector<SequenceFeature> sfeatures = (Vector<SequenceFeature>) sqinfo
108             .get("SeqFeatures");
109     Vector<PDBEntry> pdbid = (Vector<PDBEntry>) sqinfo.get("PdbId");
110     String description = (String) sqinfo.get("Description");
111     Sequence seqds = (Sequence) sqinfo.get("datasetSequence");
112     HiddenMarkovModel hmm = (HiddenMarkovModel) sqinfo.get("HMM");
113     AlignmentAnnotation[] scores = (AlignmentAnnotation[]) sqinfo
114             .get("Score");
115
116     if (oldname == null)
117     {
118       namePresent = false;
119     }
120     else
121     {
122       sq.setName(oldname);
123     }
124     if (pdbid != null && pdbid.size() > 0)
125     {
126       sq.setPDBId(pdbid);
127     }
128
129     if ((start != null) && (end != null))
130     {
131       sq.setStart(start.intValue());
132       sq.setEnd(end.intValue());
133     }
134
135     if (sfeatures != null && !sfeatures.isEmpty())
136     {
137       sq.setSequenceFeatures(sfeatures);
138     }
139     if (description != null)
140     {
141       sq.setDescription(description);
142     }
143     if ((seqds != null) && !(seqds.getName().equals("THISISAPLACEHOLDER")
144             && seqds.getLength() == 0))
145     {
146       if (sfeatures != null)
147       {
148         System.err.println(
149                 "Implementation error: setting dataset sequence for a sequence which has sequence features.\n\tDataset sequence features will not be visible.");
150       }
151       sq.setDatasetSequence(seqds);
152     }
153
154     if (hmm != null)
155     {
156       sq.setHMM(new HiddenMarkovModel(hmm, sq));
157     }
158
159     if (scores != null)
160     {
161       for (AlignmentAnnotation score : scores)
162       {
163         sq.addAlignmentAnnotation(score);
164       }
165     }
166     return namePresent;
167   }
168
169   /**
170    * Form of the unique name used in uniquify for the i'th sequence in an
171    * ordered vector of sequences.
172    * 
173    * @param i
174    *          int
175    * @return String
176    */
177   public static String unique_name(int i)
178   {
179     return new String("Sequence" + i);
180   }
181
182   /**
183    * Generates a hash of SeqCharacterHash properties for each sequence in a
184    * sequence set, and optionally renames the sequences to an unambiguous 'safe'
185    * name.
186    * 
187    * @param sequences
188    *          SequenceI[]
189    * @param write_names
190    *          boolean set this to rename each of the sequences to its
191    *          unique_name(index) name
192    * @return Hashtable to be passed to
193    * @see deuniquify to recover original names (and properties) for renamed
194    *      sequences
195    */
196   public static Hashtable uniquify(SequenceI[] sequences,
197           boolean write_names)
198   {
199     // Generate a safely named sequence set and a hash to recover the sequence
200     // names
201     Hashtable map = new Hashtable();
202     // String[] un_names = new String[sequences.length];
203
204     for (int i = 0; i < sequences.length; i++)
205     {
206       String safename = unique_name(i);
207       map.put(safename, SeqCharacterHash(sequences[i]));
208
209       if (write_names)
210       {
211         sequences[i].setName(safename);
212       }
213     }
214
215     return map;
216   }
217
218   /**
219    * recover unsafe sequence names and original properties for a sequence set
220    * using a map generated by
221    * 
222    * @see uniquify(sequences,true)
223    * @param map
224    *          Hashtable
225    * @param sequences
226    *          SequenceI[]
227    * @return boolean
228    */
229   public static boolean deuniquify(Hashtable map, SequenceI[] sequences)
230   {
231     return deuniquify(map, sequences, true);
232   }
233
234   /**
235    * recover unsafe sequence names and original properties for a sequence set
236    * using a map generated by
237    * 
238    * @see uniquify(sequences,true)
239    * @param map
240    *          Hashtable
241    * @param sequences
242    *          SequenceI[]
243    * @param quiet
244    *          when false, don't complain about sequences without any data in the
245    *          map.
246    * @return boolean
247    */
248   public static boolean deuniquify(Hashtable map, SequenceI[] sequences,
249           boolean quiet)
250   {
251     jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(
252             sequences);
253     SequenceI msq = null;
254     Enumeration keys = map.keys();
255     Vector unmatched = new Vector();
256     for (int i = 0, j = sequences.length; i < j; i++)
257     {
258       unmatched.addElement(sequences[i]);
259     }
260     while (keys.hasMoreElements())
261     {
262       Object key = keys.nextElement();
263       if (key instanceof String)
264       {
265         if ((msq = matcher.findIdMatch((String) key)) != null)
266         {
267           Hashtable sqinfo = (Hashtable) map.get(key);
268           unmatched.removeElement(msq);
269           SeqCharacterUnhash(msq, sqinfo);
270         }
271         else
272         {
273           if (!quiet)
274           {
275             System.err.println("Can't find '" + ((String) key)
276                     + "' in uniquified alignment");
277           }
278         }
279       }
280     }
281     if (unmatched.size() > 0 && !quiet)
282     {
283       System.err.println("Did not find matches for :");
284       for (Enumeration i = unmatched.elements(); i
285               .hasMoreElements(); System.out
286                       .println(((SequenceI) i.nextElement()).getName()))
287       {
288         ;
289       }
290       return false;
291     }
292
293     return true;
294   }
295
296   /**
297    * returns a subset of the sequenceI seuqences, including only those that
298    * contain at least one residue.
299    * 
300    * @param sequences
301    *          SequenceI[]
302    * @return SequenceI[]
303    */
304   public static SequenceI[] getNonEmptySequenceSet(SequenceI[] sequences)
305   {
306     // Identify first row of alignment with residues for prediction
307     boolean ungapped[] = new boolean[sequences.length];
308     int msflen = 0;
309     for (int i = 0, j = sequences.length; i < j; i++)
310     {
311       String tempseq = jalview.analysis.AlignSeq.extractGaps(
312               jalview.util.Comparison.GapChars,
313               sequences[i].getSequenceAsString());
314
315       if (tempseq.length() == 0)
316       {
317         ungapped[i] = false;
318       }
319       else
320       {
321         ungapped[i] = true;
322         msflen++;
323       }
324     }
325     if (msflen == 0)
326     {
327       return null; // no minimal set
328     }
329     // compose minimal set
330     SequenceI[] mset = new SequenceI[msflen];
331     for (int i = 0, j = sequences.length, k = 0; i < j; i++)
332     {
333       if (ungapped[i])
334       {
335         mset[k++] = sequences[i];
336       }
337     }
338     ungapped = null;
339     return mset;
340   }
341 }