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