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