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