Merge branch 'develop' into update_212_Dec_merge_with_21125_chamges
[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.bin.Cache;
24 import jalview.bin.Console;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.HiddenMarkovModel;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31
32 import java.util.ArrayList;
33 import java.util.Enumeration;
34 import java.util.HashMap;
35 import java.util.Hashtable;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Objects;
40 import java.util.Optional;
41 import java.util.Vector;
42 import static java.lang.String.format;
43
44 public class SeqsetUtils
45 {
46   public static class SequenceInfo {
47     private String name;
48     private int start;
49     private int end;
50     private Optional<String> description = Optional.empty();
51     private Optional<List<SequenceFeature>> features = Optional.empty();
52     private Optional<List<PDBEntry>> pdbId = Optional.empty();
53     private Optional<SequenceI> dataset = Optional.empty();
54     private Optional<HiddenMarkovModel> hmm = Optional.empty();
55     private Optional<AlignmentAnnotation[]> searchScores = Optional.empty();
56
57     private SequenceInfo(String name, int start, int end) {
58       this.name = name;
59       this.start = start;
60       this.end = end;
61     }
62   }
63
64   /**
65    * Store essential properties of a sequence in a hashtable for later recovery
66    * Keys are Name, Start, End, SeqFeatures, PdbId, HMM
67    * 
68    * @param seq
69    *          SequenceI
70    * @return Hashtable
71    */
72   public static SequenceInfo SeqCharacterHash(SequenceI seq)
73   {
74     SequenceInfo sqinfo = new SequenceInfo(seq.getName(), seq.getStart(), seq.getEnd());
75     sqinfo.description = Optional.ofNullable(seq.getDescription());
76     sqinfo.dataset = Optional.ofNullable(seq.getDatasetSequence());
77     if (!sqinfo.dataset.isPresent())
78     {
79       ArrayList<SequenceFeature> feats = new ArrayList<>(
80           seq.getFeatures().getAllFeatures());
81       sqinfo.features = Optional.of(feats);
82       sqinfo.pdbId = Optional.of(Objects.requireNonNullElse(
83           seq.getAllPDBEntries(), new ArrayList<>()));
84     }
85     if (seq.hasHMMProfile())
86     {
87       sqinfo.hmm = Optional.of(seq.getHMM());
88     }
89     sqinfo.searchScores = Optional.ofNullable(seq.getAnnotation("Search Scores"));
90     return sqinfo;
91   }
92
93   /**
94    * Recover essential properties of a sequence from a hashtable TODO: replace
95    * these methods with something more elegant.
96    * 
97    * @param sq
98    *          SequenceI
99    * @param sqinfo
100    *          Hashtable
101    * @return boolean true if name was not updated from sqinfo Name entry
102    */
103   public static boolean SeqCharacterUnhash(SequenceI sq, SequenceInfo sqinfo)
104   {
105     if (sqinfo == null)
106     {
107       return false;
108     }
109     if (sqinfo.name != null)
110     {
111       sq.setName(sqinfo.name);
112     }
113     sq.setStart(sqinfo.start);
114     sq.setEnd(sqinfo.end);
115     if (sqinfo.pdbId.isPresent() && !sqinfo.pdbId.get().isEmpty())
116       sq.setPDBId(new Vector<>(sqinfo.pdbId.get()));
117     if (sqinfo.features.isPresent() && !sqinfo.features.get().isEmpty())
118       sq.setSequenceFeatures(sqinfo.features.get());
119     if (sqinfo.description.isPresent())
120       sq.setDescription(sqinfo.description.get());
121     if (sqinfo.dataset.isPresent())
122     {
123       if (sqinfo.features.isPresent())
124       {
125         Console.warn("Setting dataset sequence for a sequence which has " +
126             "sequence features. Dataset sequence features will not be visible.");
127         assert false;
128       }
129       sq.setDatasetSequence(sqinfo.dataset.get());
130     }
131     if (sqinfo.hmm.isPresent())
132       sq.setHMM(new HiddenMarkovModel(sqinfo.hmm.get(), sq));
133     if (sqinfo.searchScores.isPresent())
134     {
135       for (AlignmentAnnotation score : sqinfo.searchScores.get())
136       {
137         sq.addAlignmentAnnotation(score);
138       }
139     }
140     return sqinfo.name != null;
141   }
142
143   /**
144    * Form of the unique name used in uniquify for the i'th sequence in an
145    * ordered vector of sequences.
146    * 
147    * @param i
148    *          int
149    * @return String
150    */
151   public static String unique_name(int i)
152   {
153     return String.format("Sequence%d", i);
154   }
155
156   /**
157    * Generates a hash of SeqCharacterHash properties for each sequence in a
158    * sequence set, and optionally renames the sequences to an unambiguous 'safe'
159    * name.
160    * 
161    * @param sequences
162    *          SequenceI[]
163    * @param write_names
164    *          boolean set this to rename each of the sequences to its
165    *          unique_name(index) name
166    * @return Hashtable to be passed to
167    * @see deuniquify to recover original names (and properties) for renamed
168    *      sequences
169    */
170   public static Map<String, SequenceInfo> uniquify(SequenceI[] sequences,
171           boolean write_names)
172   {
173     // Generate a safely named sequence set and a hash to recover the sequence
174     // names
175     HashMap<String, SequenceInfo> map = new HashMap<>();
176     // String[] un_names = new String[sequences.length];
177
178     for (int i = 0; i < sequences.length; i++)
179     {
180       String safename = unique_name(i);
181       map.put(safename, SeqCharacterHash(sequences[i]));
182
183       if (write_names)
184       {
185         sequences[i].setName(safename);
186       }
187     }
188
189     return map;
190   }
191
192   /**
193    * recover unsafe sequence names and original properties for a sequence set
194    * using a map generated by
195    * 
196    * @see uniquify(sequences,true)
197    * @param map
198    *          Hashtable
199    * @param sequences
200    *          SequenceI[]
201    * @return boolean
202    */
203   public static boolean deuniquify(Map<String, SequenceInfo> map,
204       SequenceI[] sequences)
205   {
206     return deuniquify(map, sequences, true);
207   }
208
209   /**
210    * recover unsafe sequence names and original properties for a sequence set
211    * using a map generated by
212    * 
213    * @see uniquify(sequences,true)
214    * @param map
215    *          Hashtable
216    * @param sequences
217    *          SequenceI[]
218    * @param quiet
219    *          when false, don't complain about sequences without any data in the
220    *          map.
221    * @return boolean
222    */
223   public static boolean deuniquify(Map<String, SequenceInfo> map,
224       SequenceI[] sequences, boolean quiet)
225   {
226     jalview.analysis.SequenceIdMatcher matcher = new SequenceIdMatcher(
227             sequences);
228     SequenceI msq = null;
229     Iterator<String> keys = map.keySet().iterator();
230     Vector<SequenceI> unmatched = new Vector<>();
231     for (int i = 0, j = sequences.length; i < j; i++)
232     {
233       unmatched.addElement(sequences[i]);
234     }
235     while (keys.hasNext())
236     {
237       String key = keys.next();
238       try {
239         if ((msq = matcher.findIdMatch((String) key)) != null)
240         {
241           SequenceInfo sqinfo = map.get(key);
242           unmatched.removeElement(msq);
243           SeqCharacterUnhash(msq, sqinfo);
244         }
245         else
246         {
247           if (!quiet)
248           {
249             Console.warn(format("Can't find '%s' in uniquified alignment",
250                 key));
251           }
252         }
253       } catch (ClassCastException ccastex) {
254         if (!quiet)
255         {
256           Console.error("Unexpected object in SeqSet map : "+ key.getClass());
257         }
258       }
259     }
260     if (unmatched.size() > 0 && !quiet)
261     {
262       StringBuilder sb = new StringBuilder("Did not find match for sequences: ");
263       Enumeration<SequenceI> i = unmatched.elements();
264       sb.append(i.nextElement().getName());
265       for (; i.hasMoreElements();)
266       {
267         sb.append(", " + i.nextElement().getName());
268       }
269       Console.warn(sb.toString());
270       return false;
271     }
272
273     return true;
274   }
275
276   /**
277    * returns a subset of the sequenceI seuqences, including only those that
278    * contain at least one residue.
279    * 
280    * @param sequences
281    *          SequenceI[]
282    * @return SequenceI[]
283    */
284   public static SequenceI[] getNonEmptySequenceSet(SequenceI[] sequences)
285   {
286     // Identify first row of alignment with residues for prediction
287     boolean ungapped[] = new boolean[sequences.length];
288     int msflen = 0;
289     for (int i = 0, j = sequences.length; i < j; i++)
290     {
291       String tempseq = jalview.analysis.AlignSeq.extractGaps(
292               jalview.util.Comparison.GapChars,
293               sequences[i].getSequenceAsString());
294
295       if (tempseq.length() == 0)
296       {
297         ungapped[i] = false;
298       }
299       else
300       {
301         ungapped[i] = true;
302         msflen++;
303       }
304     }
305     if (msflen == 0)
306     {
307       return null; // no minimal set
308     }
309     // compose minimal set
310     SequenceI[] mset = new SequenceI[msflen];
311     for (int i = 0, j = sequences.length, k = 0; i < j; i++)
312     {
313       if (ungapped[i])
314       {
315         mset[k++] = sequences[i];
316       }
317     }
318     ungapped = null;
319     return mset;
320   }
321 }