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