JAL-1620 version bump and release notes
[jalview.git] / src / jalview / io / JPredFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
3  * Copyright (C) 2014 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 /**
22  * PredFile.java
23  * JalviewX / Vamsas Project
24  * JPred.seq.concise reader
25  */
26 package jalview.io;
27
28 import java.io.*;
29 import java.util.*;
30
31 import jalview.datamodel.*;
32 import jalview.util.MessageManager;
33
34 /**
35  * Parser for the JPred/JNet concise format. This is a series of CSV lines, each
36  * line is either a sequence (QUERY), a sequence profile (align;), or jnet
37  * prediction annotation (anything else). Automagic translation happens for
38  * annotation called 'JNETPRED' (translated to Secondary Structure Prediction),
39  * or 'JNETCONF' (translates to 'Prediction Confidence'). Numeric scores are
40  * differentiated from symbolic by being parseable into a float vector. They are
41  * put in Scores. Symscores gets the others. JNetAnnotationMaker translates the
42  * data parsed by this object into annotation on an alignment. It is
43  * automatically called but can be used to transfer the annotation onto a
44  * sequence in another alignment (and insert gaps where necessary)
45  * 
46  * @author jprocter
47  * @version $Revision$
48  */
49 public class JPredFile extends AlignFile
50 {
51   Vector ids;
52
53   Vector conf;
54
55   Hashtable Scores; // Hash of names and score vectors
56
57   Hashtable Symscores; // indexes of symbol annotation properties in sequenceI
58
59   // vector
60
61   private int QuerySeqPosition;
62
63   /**
64    * Creates a new JPredFile object.
65    * 
66    * @param inFile
67    *          DOCUMENT ME!
68    * @param type
69    *          DOCUMENT ME!
70    * 
71    * @throws IOException
72    *           DOCUMENT ME!
73    */
74   public JPredFile(String inFile, String type) throws IOException
75   {
76     super(inFile, type);
77   }
78
79   public JPredFile(FileParse source) throws IOException
80   {
81     super(source);
82   }
83
84   /**
85    * DOCUMENT ME!
86    * 
87    * @param QuerySeqPosition
88    *          DOCUMENT ME!
89    */
90   public void setQuerySeqPosition(int QuerySeqPosition)
91   {
92     this.QuerySeqPosition = QuerySeqPosition;
93   }
94
95   /**
96    * DOCUMENT ME!
97    * 
98    * @return DOCUMENT ME!
99    */
100   public int getQuerySeqPosition()
101   {
102     return QuerySeqPosition;
103   }
104
105   /**
106    * DOCUMENT ME!
107    * 
108    * @return DOCUMENT ME!
109    */
110   public Hashtable getScores()
111   {
112     return Scores;
113   }
114
115   /**
116    * DOCUMENT ME!
117    * 
118    * @return DOCUMENT ME!
119    */
120   public Hashtable getSymscores()
121   {
122     return Symscores;
123   }
124
125   /**
126    * DOCUMENT ME!
127    */
128   public void initData()
129   {
130     super.initData();
131     Scores = new Hashtable();
132     ids = null;
133     conf = null;
134   }
135
136   /**
137    * parse a JPred concise file into a sequence-alignment like object.
138    */
139   public void parse() throws IOException
140   {
141     // JBPNote log.System.out.println("all read in ");
142     String line;
143     QuerySeqPosition = -1;
144     noSeqs = 0;
145
146     Vector seq_entries = new Vector();
147     Vector ids = new Vector();
148     Hashtable Symscores = new Hashtable();
149
150     while ((line = nextLine()) != null)
151     {
152       // Concise format allows no comments or non comma-formatted data
153       StringTokenizer str = new StringTokenizer(line, ":");
154       String id = "";
155
156       if (!str.hasMoreTokens())
157       {
158         continue;
159       }
160
161       id = str.nextToken();
162
163       String seqsym = str.nextToken();
164       StringTokenizer symbols = new StringTokenizer(seqsym, ",");
165
166       // decide if we have more than just alphanumeric symbols
167       int numSymbols = symbols.countTokens();
168
169       if (numSymbols == 0)
170       {
171         continue;
172       }
173
174       if (seqsym.length() != (2 * numSymbols))
175       {
176         // Set of scalars for some property
177         if (Scores.containsKey(id))
178         {
179           int i = 1;
180
181           while (Scores.containsKey(id + "_" + i))
182           {
183             i++;
184           }
185
186           id = id + "_" + i;
187         }
188
189         Vector scores = new Vector();
190
191         // Typecheck from first entry
192         int i = 0;
193         String ascore = "dead";
194
195         try
196         {
197           // store elements as floats...
198           while (symbols.hasMoreTokens())
199           {
200             ascore = symbols.nextToken();
201
202             Float score = new Float(ascore);
203             scores.addElement((Object) score);
204           }
205
206           Scores.put(id, scores);
207         } catch (Exception e)
208         {
209           // or just keep them as strings
210           i = scores.size();
211
212           for (int j = 0; j < i; j++)
213           {
214             scores.setElementAt(
215                     (Object) ((Float) scores.elementAt(j)).toString(), j);
216           }
217
218           scores.addElement((Object) ascore);
219
220           while (symbols.hasMoreTokens())
221           {
222             ascore = symbols.nextToken();
223             scores.addElement((Object) ascore);
224           }
225
226           Scores.put(id, scores);
227         }
228       }
229       else if (id.equals("jnetconf"))
230       {
231         // log.debug System.out.println("here");
232         id = "Prediction Confidence";
233         this.conf = new Vector(numSymbols);
234
235         for (int i = 0; i < numSymbols; i++)
236         {
237           conf.setElementAt(symbols.nextToken(), i);
238         }
239       }
240       else
241       {
242         // Sequence or a prediction string (rendered as sequence)
243         StringBuffer newseq = new StringBuffer();
244
245         for (int i = 0; i < numSymbols; i++)
246         {
247           newseq.append(symbols.nextToken());
248         }
249
250         if (id.indexOf(";") > -1)
251         {
252           seq_entries.addElement(newseq);
253
254           int i = 1;
255           String name = id.substring(id.indexOf(";") + 1);
256
257           while (ids.lastIndexOf(name) > -1)
258           {
259             name = id.substring(id.indexOf(";") + 1) + "_" + ++i;
260           }
261
262           if (QuerySeqPosition == -1)
263             QuerySeqPosition = ids.size();
264           ids.addElement(name);
265           noSeqs++;
266         }
267         else
268         {
269           if (id.equals("JNETPRED"))
270           {
271             id = "Predicted Secondary Structure";
272           }
273
274           seq_entries.addElement(newseq.toString());
275           ids.addElement(id);
276           Symscores.put((Object) id, (Object) new Integer(ids.size() - 1));
277         }
278       }
279     }
280     /*
281      * leave it to the parser user to actually check this. if (noSeqs < 1) {
282      * throw new IOException( "JpredFile Parser: No sequence in the
283      * prediction!"); }
284      */
285
286     maxLength = seq_entries.elementAt(0).toString().length();
287
288     for (int i = 0; i < ids.size(); i++)
289     {
290       // Add all sequence like objects
291       Sequence newSeq = new Sequence(ids.elementAt(i).toString(),
292               seq_entries.elementAt(i).toString(), 1, seq_entries
293                       .elementAt(i).toString().length());
294
295       if (maxLength != seq_entries.elementAt(i).toString().length())
296       {
297         throw new IOException(MessageManager.formatMessage("exception.jpredconcide_entry_has_unexpected_number_of_columns", new String[]{ids.elementAt(i).toString()}));
298       }
299
300       if ((newSeq.getName().startsWith("QUERY") || newSeq.getName()
301               .startsWith("align;")) && (QuerySeqPosition == -1))
302       {
303         QuerySeqPosition = seqs.size();
304       }
305
306       seqs.addElement(newSeq);
307     }
308     if (seqs.size() > 0 && QuerySeqPosition > -1)
309     {
310       // try to make annotation for a prediction only input (default if no
311       // alignment is given and prediction contains a QUERY or align;sequence_id
312       // line)
313       Alignment tal = new Alignment(this.getSeqsAsArray());
314       try
315       {
316         JnetAnnotationMaker.add_annotation(this, tal, QuerySeqPosition,
317                 true);
318       } catch (Exception e)
319       {
320         tal = null;
321         IOException ex = new IOException(MessageManager.formatMessage("exception.couldnt_parse_concise_annotation_for_prediction", new String[]{e.getMessage()}));
322         e.printStackTrace(); // java 1.1 does not have :
323                              // ex.setStackTrace(e.getStackTrace());
324         throw ex;
325       }
326       this.annotations = new Vector();
327       AlignmentAnnotation[] aan = tal.getAlignmentAnnotation();
328       for (int aai = 0; aan != null && aai < aan.length; aai++)
329       {
330         annotations.addElement(aan[aai]);
331       }
332     }
333   }
334
335   /**
336    * print
337    * 
338    * @return String
339    */
340   public String print()
341   {
342     return "Not Supported";
343   }
344
345   /**
346    * DOCUMENT ME!
347    * 
348    * @param args
349    *          DOCUMENT ME!
350    */
351   public static void main(String[] args)
352   {
353     try
354     {
355       JPredFile blc = new JPredFile(args[0], "File");
356
357       for (int i = 0; i < blc.seqs.size(); i++)
358       {
359         System.out.println(((Sequence) blc.seqs.elementAt(i)).getName()
360                 + "\n"
361                 + ((Sequence) blc.seqs.elementAt(i)).getSequenceAsString()
362                 + "\n");
363       }
364     } catch (java.io.IOException e)
365     {
366       System.err.println("Exception " + e);
367       // e.printStackTrace(); not java 1.1 compatible!
368     }
369   }
370
371   Vector annotSeqs = null;
372
373   /**
374    * removeNonSequences
375    */
376   public void removeNonSequences()
377   {
378     if (annotSeqs != null)
379     {
380       return;
381     }
382     annotSeqs = new Vector();
383     Vector newseqs = new Vector();
384     int i = 0;
385     int j = seqs.size();
386     for (; i < QuerySeqPosition; i++)
387     {
388       annotSeqs.addElement(seqs.elementAt(i));
389     }
390     // check that no stray annotations have been added at the end.
391     {
392       SequenceI sq = (SequenceI) seqs.elementAt(j - 1);
393       if (sq.getName().toUpperCase().startsWith("JPRED"))
394       {
395         annotSeqs.addElement(sq);
396         seqs.removeElementAt(--j);
397       }
398     }
399     for (; i < j; i++)
400     {
401       newseqs.addElement(seqs.elementAt(i));
402     }
403
404     seqs.removeAllElements();
405     seqs = newseqs;
406   }
407 }
408
409 /*
410  * StringBuffer out = new StringBuffer();
411  * 
412  * out.append("START PRED\n"); for (int i = 0; i < s[0].sequence.length(); i++)
413  * { out.append(s[0].sequence.substring(i, i + 1) + " ");
414  * out.append(s[1].sequence.substring(i, i + 1) + " ");
415  * out.append(s[1].score[0].elementAt(i) + " ");
416  * out.append(s[1].score[1].elementAt(i) + " ");
417  * out.append(s[1].score[2].elementAt(i) + " ");
418  * out.append(s[1].score[3].elementAt(i) + " ");
419  * 
420  * out.append("\n"); } out.append("END PRED\n"); return out.toString(); }
421  * 
422  * public static void main(String[] args) { try { BLCFile blc = new
423  * BLCFile(args[0], "File"); DrawableSequence[] s = new
424  * DrawableSequence[blc.seqs.size()]; for (int i = 0; i < blc.seqs.size(); i++)
425  * { s[i] = new DrawableSequence( (Sequence) blc.seqs.elementAt(i)); } String
426  * out = BLCFile.print(s);
427  * 
428  * AlignFrame af = new AlignFrame(null, s); af.resize(700, 500); af.show();
429  * System.out.println(out); } catch (java.io.IOException e) {
430  * System.out.println("Exception " + e); } } }
431  */