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