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