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