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