javadoc
[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.
40  *
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   }
297
298   /**
299    * print
300    *
301    * @return String
302    */
303   public String print()
304   {
305     return "Not Supported";
306   }
307
308   /**
309    * DOCUMENT ME!
310    *
311    * @param args DOCUMENT ME!
312    */
313   public static void main(String[] args)
314   {
315     try
316     {
317       JPredFile blc = new JPredFile(args[0], "File");
318
319       for (int i = 0; i < blc.seqs.size(); i++)
320       {
321         System.out.println( ( (Sequence) blc.seqs.elementAt(i)).getName() +
322                            "\n" +
323                            ( (Sequence) blc.seqs.elementAt(i)).getSequenceAsString() +
324                            "\n");
325       }
326     }
327     catch (java.io.IOException e)
328     {
329       System.err.println("Exception " + e);
330       e.printStackTrace();
331     }
332   }
333
334   Vector annotSeqs = null;
335   /**
336    * removeNonSequences
337    */
338   public void removeNonSequences()
339   {
340     if (annotSeqs != null)
341     {
342       return;
343     }
344     annotSeqs = new Vector();
345     Vector newseqs = new Vector();
346     int i = 0;
347     int j = seqs.size();
348     for (; i < QuerySeqPosition; i++)
349     {
350       annotSeqs.addElement(seqs.elementAt(i));
351     }
352     // check that no stray annotations have been added at the end.
353     {
354       SequenceI sq = (SequenceI) seqs.elementAt(j - 1);
355       if (sq.getName().toUpperCase().startsWith("JPRED"))
356       {
357         annotSeqs.addElement(sq);
358         seqs.removeElementAt(--j);
359       }
360     }
361     for (; i < j; i++)
362     {
363       newseqs.addElement(seqs.elementAt(i));
364     }
365
366     seqs.removeAllElements();
367     seqs = newseqs;
368   }
369 }
370
371 /*
372  StringBuffer out = new StringBuffer();
373
374  out.append("START PRED\n");
375  for (int i = 0; i < s[0].sequence.length(); i++)
376  {
377   out.append(s[0].sequence.substring(i, i + 1) + " ");
378   out.append(s[1].sequence.substring(i, i + 1) + " ");
379   out.append(s[1].score[0].elementAt(i) + " ");
380   out.append(s[1].score[1].elementAt(i) + " ");
381   out.append(s[1].score[2].elementAt(i) + " ");
382   out.append(s[1].score[3].elementAt(i) + " ");
383
384   out.append("\n");
385  }
386  out.append("END PRED\n");
387  return out.toString();
388  }
389
390     public static void main(String[] args)
391  {
392   try
393   {
394     BLCFile blc = new BLCFile(args[0], "File");
395     DrawableSequence[] s = new DrawableSequence[blc.seqs.size()];
396     for (int i = 0; i < blc.seqs.size(); i++)
397     {
398       s[i] = new DrawableSequence( (Sequence) blc.seqs.elementAt(i));
399     }
400     String out = BLCFile.print(s);
401
402     AlignFrame af = new AlignFrame(null, s);
403     af.resize(700, 500);
404     af.show();
405     System.out.println(out);
406   }
407   catch (java.io.IOException e)
408   {
409     System.out.println("Exception " + e);
410   }
411  }
412
413  }
414  */