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