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