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