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