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