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