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