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