6732e8281694dc8e8f963493af5ab1be97e5e8b8
[jalview.git] / src / jalview / io / JPredFile.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 /**
22  * PredFile.java
23  * JalviewX / Vamsas Project
24  * JPred.seq.concise reader
25  */
26 package jalview.io;
27
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceI;
32 import jalview.util.MessageManager;
33
34 import java.io.IOException;
35 import java.util.Hashtable;
36 import java.util.StringTokenizer;
37 import java.util.Vector;
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 sourceType
74    *          DOCUMENT ME!
75    * 
76    * @throws IOException
77    *           DOCUMENT ME!
78    */
79   public JPredFile(String inFile, DataSourceType sourceType)
80           throws IOException
81   {
82     super(inFile, sourceType);
83   }
84
85   public JPredFile(FileParse source) throws IOException
86   {
87     super(source);
88   }
89
90   /**
91    * DOCUMENT ME!
92    * 
93    * @param QuerySeqPosition
94    *          DOCUMENT ME!
95    */
96   public void setQuerySeqPosition(int QuerySeqPosition)
97   {
98     this.QuerySeqPosition = QuerySeqPosition;
99   }
100
101   /**
102    * DOCUMENT ME!
103    * 
104    * @return DOCUMENT ME!
105    */
106   public int getQuerySeqPosition()
107   {
108     return QuerySeqPosition;
109   }
110
111   /**
112    * DOCUMENT ME!
113    * 
114    * @return DOCUMENT ME!
115    */
116   public Hashtable getScores()
117   {
118     return Scores;
119   }
120
121   /**
122    * DOCUMENT ME!
123    * 
124    * @return DOCUMENT ME!
125    */
126   public Hashtable getSymscores()
127   {
128     return Symscores;
129   }
130
131   /**
132    * DOCUMENT ME!
133    */
134   @Override
135   public void initData()
136   {
137     super.initData();
138     Scores = new Hashtable();
139     ids = null;
140     conf = null;
141   }
142
143   /**
144    * parse a JPred concise file into a sequence-alignment like object.
145    */
146   @Override
147   public void parse() throws IOException
148   {
149     // JBPNote log.System.out.println("all read in ");
150     String line;
151     QuerySeqPosition = -1;
152     noSeqs = 0;
153
154     Vector seq_entries = new Vector();
155     Vector ids = new Vector();
156     Hashtable Symscores = new Hashtable();
157
158     while ((line = nextLine()) != null)
159     {
160       // Concise format allows no comments or non comma-formatted data
161       StringTokenizer str = new StringTokenizer(line, ":");
162       String id = "";
163
164       if (!str.hasMoreTokens())
165       {
166         continue;
167       }
168
169       id = str.nextToken();
170
171       String seqsym = str.nextToken();
172       StringTokenizer symbols = new StringTokenizer(seqsym, ",");
173
174       // decide if we have more than just alphanumeric symbols
175       int numSymbols = symbols.countTokens();
176
177       if (numSymbols == 0)
178       {
179         continue;
180       }
181
182       if (seqsym.length() != (2 * numSymbols))
183       {
184         // Set of scalars for some property
185         if (Scores.containsKey(id))
186         {
187           int i = 1;
188
189           while (Scores.containsKey(id + "_" + i))
190           {
191             i++;
192           }
193
194           id = id + "_" + i;
195         }
196
197         Vector scores = new Vector();
198
199         // Typecheck from first entry
200         int i = 0;
201         String ascore = "dead";
202
203         try
204         {
205           // store elements as floats...
206           while (symbols.hasMoreTokens())
207           {
208             ascore = symbols.nextToken();
209
210             Float score = Float.valueOf(ascore);
211             scores.addElement(score);
212           }
213
214           Scores.put(id, scores);
215         } catch (Exception e)
216         {
217           // or just keep them as strings
218           i = scores.size();
219
220           for (int j = 0; j < i; j++)
221           {
222             scores.setElementAt(((Float) scores.elementAt(j)).toString(),
223                     j);
224           }
225
226           scores.addElement(ascore);
227
228           while (symbols.hasMoreTokens())
229           {
230             ascore = symbols.nextToken();
231             scores.addElement(ascore);
232           }
233
234           Scores.put(id, scores);
235         }
236       }
237       else if (id.equals("jnetconf"))
238       {
239         // log.debug System.out.println("here");
240         id = "Prediction Confidence";
241         this.conf = new Vector(numSymbols);
242
243         for (int i = 0; i < numSymbols; i++)
244         {
245           conf.setElementAt(symbols.nextToken(), i);
246         }
247       }
248       else
249       {
250         // Sequence or a prediction string (rendered as sequence)
251         StringBuffer newseq = new StringBuffer();
252
253         for (int i = 0; i < numSymbols; i++)
254         {
255           newseq.append(symbols.nextToken());
256         }
257
258         if (id.indexOf(";") > -1)
259         {
260           seq_entries.addElement(newseq);
261
262           int i = 1;
263           String name = id.substring(id.indexOf(";") + 1);
264
265           while (ids.lastIndexOf(name) > -1)
266           {
267             name = id.substring(id.indexOf(";") + 1) + "_" + ++i;
268           }
269
270           if (QuerySeqPosition == -1)
271           {
272             QuerySeqPosition = ids.size();
273           }
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(id, Integer.valueOf(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,
303               seq_entries.elementAt(i).toString().length());
304
305       if (maxLength != seq_entries.elementAt(i).toString().length())
306       {
307         throw new IOException(MessageManager.formatMessage(
308                 "exception.jpredconcide_entry_has_unexpected_number_of_columns",
309                 new String[]
310                 { ids.elementAt(i).toString() }));
311       }
312
313       if ((newSeq.getName().startsWith("QUERY")
314               || newSeq.getName().startsWith("align;"))
315               && (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(MessageManager.formatMessage(
336                 "exception.couldnt_parse_concise_annotation_for_prediction",
337                 new String[]
338                 { e.getMessage() }));
339         e.printStackTrace(); // java 1.1 does not have :
340                              // ex.setStackTrace(e.getStackTrace());
341         throw ex;
342       }
343       this.annotations = new Vector();
344       AlignmentAnnotation[] aan = tal.getAlignmentAnnotation();
345       for (int aai = 0; aan != null && aai < aan.length; aai++)
346       {
347         annotations.addElement(aan[aai]);
348       }
349     }
350   }
351
352   /**
353    * print
354    * 
355    * @return String
356    */
357   @Override
358   public String print(SequenceI[] sqs, boolean jvsuffix)
359   {
360     return "Not Supported";
361   }
362
363   /**
364    * DOCUMENT ME!
365    * 
366    * @param args
367    *          DOCUMENT ME!
368    */
369   public static void main(String[] args)
370   {
371     try
372     {
373       JPredFile jpred = new JPredFile(args[0], DataSourceType.FILE);
374
375       for (int i = 0; i < jpred.seqs.size(); i++)
376       {
377         System.out.println(((Sequence) jpred.seqs.elementAt(i)).getName()
378                 + "\n"
379                 + ((Sequence) jpred.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 = 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  */