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