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