JAL-3899 Refactor sequence de/uniquification.
[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.AlignmentAnnotation;
24 import jalview.datamodel.HiddenMarkovModel;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29
30 import java.util.ArrayList;
31 import java.util.Enumeration;
32 import java.util.HashMap;
33 import java.util.Hashtable;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Objects;
38 import java.util.Optional;
39 import java.util.Vector;
40
41 public class SeqsetUtils
42 {
43   public static class SequenceInfo {
44     private String name;
45     private int start;
46     private int end;
47     private Optional<String> description = Optional.empty();
48     private Optional<List<SequenceFeature>> features = Optional.empty();
49     private Optional<List<PDBEntry>> pdbId = Optional.empty();
50     private Optional<SequenceI> dataset = Optional.empty();
51     private Optional<HiddenMarkovModel> hmm = Optional.empty();
52     private Optional<AlignmentAnnotation[]> searchScores = Optional.empty();
53
54     private SequenceInfo(String name, int start, int end) {
55       this.name = name;
56       this.start = start;
57       this.end = end;
58     }
59   }
60
61   /**
62    * Store essential properties of a sequence in a hashtable for later recovery
63    * Keys are Name, Start, End, SeqFeatures, PdbId, HMM
64    * 
65    * @param seq
66    *          SequenceI
67    * @return Hashtable
68    */
69   public static SequenceInfo SeqCharacterHash(SequenceI seq)
70   {
71     SequenceInfo sqinfo = new SequenceInfo(seq.getName(), seq.getStart(), seq.getEnd());
72     sqinfo.description = Optional.ofNullable(seq.getDescription());
73     sqinfo.dataset = Optional.ofNullable(seq.getDatasetSequence());
74     if (!sqinfo.dataset.isPresent())
75     {
76       ArrayList<SequenceFeature> feats = new ArrayList<>(
77           seq.getFeatures().getAllFeatures());
78       sqinfo.features = Optional.of(feats);
79       sqinfo.pdbId = Optional.of(Objects.requireNonNullElse(
80           seq.getAllPDBEntries(), new ArrayList<>()));
81     }
82     if (seq.hasHMMProfile())
83     {
84       sqinfo.hmm = Optional.of(seq.getHMM());
85     }
86     sqinfo.searchScores = Optional.ofNullable(seq.getAnnotation("Search Scores"));
87     return sqinfo;
88   }
89
90   /**
91    * Recover essential properties of a sequence from a hashtable TODO: replace
92    * these methods with something more elegant.
93    * 
94    * @param sq
95    *          SequenceI
96    * @param sqinfo
97    *          Hashtable
98    * @return boolean true if name was not updated from sqinfo Name entry
99    */
100   public static boolean SeqCharacterUnhash(SequenceI sq, SequenceInfo sqinfo)
101   {
102     if (sqinfo == null)
103     {
104       return false;
105     }
106     if (sqinfo.name != null)
107     {
108       sq.setName(sqinfo.name);
109     }
110     sq.setStart(sqinfo.start);
111     sq.setEnd(sqinfo.end);
112     if (sqinfo.pdbId.isPresent() && !sqinfo.pdbId.get().isEmpty())
113       sq.setPDBId(new Vector<>(sqinfo.pdbId.get()));
114     if (sqinfo.features.isPresent() && !sqinfo.features.get().isEmpty())
115       sq.setSequenceFeatures(sqinfo.features.get());
116     if (sqinfo.description.isPresent())
117       sq.setDescription(sqinfo.description.get());
118     if (sqinfo.dataset.isPresent())
119     {
120       assert sqinfo.features.isEmpty() :
121         "Setting dataset sequence for a sequence which has sequence features. " +
122           "Dataset sequence features will not be visible.";
123       sq.setDatasetSequence(sqinfo.dataset.get());
124     }
125     if (sqinfo.hmm.isPresent())
126       sq.setHMM(new HiddenMarkovModel(sqinfo.hmm.get(), sq));
127     if (sqinfo.searchScores.isPresent())
128     {
129       for (AlignmentAnnotation score : sqinfo.searchScores.get())
130       {
131         sq.addAlignmentAnnotation(score);
132       }
133     }
134     return sqinfo.name != null;
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 String.format("Sequence%d", 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 Map<String, SequenceInfo> 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     HashMap<String, SequenceInfo> map = new HashMap<>();
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(Map<String, SequenceInfo> map,
198       SequenceI[] sequences)
199   {
200     return deuniquify(map, sequences, true);
201   }
202
203   /**
204    * recover unsafe sequence names and original properties for a sequence set
205    * using a map generated by
206    * 
207    * @see uniquify(sequences,true)
208    * @param map
209    *          Hashtable
210    * @param sequences
211    *          SequenceI[]
212    * @param quiet
213    *          when false, don't complain about sequences without any data in the
214    *          map.
215    * @return boolean
216    */
217   public static boolean deuniquify(Map<String, SequenceInfo> map,
218       SequenceI[] sequences, boolean quiet)
219   {
220     jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(
221             sequences);
222     SequenceI msq = null;
223     Iterator<String> keys = map.keySet().iterator();
224     Vector<SequenceI> unmatched = new Vector<>();
225     for (int i = 0, j = sequences.length; i < j; i++)
226     {
227       unmatched.addElement(sequences[i]);
228     }
229     while (keys.hasNext())
230     {
231       String key = keys.next();
232       try {
233         if ((msq = matcher.findIdMatch((String) key)) != null)
234         {
235           SequenceInfo sqinfo = 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       } catch (ClassCastException ccastex) {
248         if (!quiet)
249         {
250           System.err.println("Unexpected object in SeqSet map : "+key.getClass());
251         }
252       }
253     }
254     if (unmatched.size() > 0 && !quiet)
255     {
256       System.err.println("Did not find matches for :");
257       for (Enumeration<SequenceI> i = unmatched.elements();
258           i.hasMoreElements();)
259       {
260         System.out.println(((SequenceI) i.nextElement()).getName());
261       }
262       return false;
263     }
264
265     return true;
266   }
267
268   /**
269    * returns a subset of the sequenceI seuqences, including only those that
270    * contain at least one residue.
271    * 
272    * @param sequences
273    *          SequenceI[]
274    * @return SequenceI[]
275    */
276   public static SequenceI[] getNonEmptySequenceSet(SequenceI[] sequences)
277   {
278     // Identify first row of alignment with residues for prediction
279     boolean ungapped[] = new boolean[sequences.length];
280     int msflen = 0;
281     for (int i = 0, j = sequences.length; i < j; i++)
282     {
283       String tempseq = jalview.analysis.AlignSeq.extractGaps(
284               jalview.util.Comparison.GapChars,
285               sequences[i].getSequenceAsString());
286
287       if (tempseq.length() == 0)
288       {
289         ungapped[i] = false;
290       }
291       else
292       {
293         ungapped[i] = true;
294         msflen++;
295       }
296     }
297     if (msflen == 0)
298     {
299       return null; // no minimal set
300     }
301     // compose minimal set
302     SequenceI[] mset = new SequenceI[msflen];
303     for (int i = 0, j = sequences.length, k = 0; i < j; i++)
304     {
305       if (ungapped[i])
306       {
307         mset[k++] = sequences[i];
308       }
309     }
310     ungapped = null;
311     return mset;
312   }
313 }