Merge branch 'develop' into trialMerge
[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    * BH allows File or String
72    * 
73    * @param inFile
74    *          DOCUMENT ME!
75    * @param sourceType
76    *          DOCUMENT ME!
77    * 
78    * @throws IOException
79    *           DOCUMENT ME!
80    */
81   public JPredFile(Object inFile, DataSourceType sourceType)
82           throws IOException
83   {
84     super(inFile, sourceType);
85   }
86
87   public JPredFile(FileParse source) throws IOException
88   {
89     super(source);
90   }
91
92   /**
93    * DOCUMENT ME!
94    * 
95    * @param QuerySeqPosition
96    *          DOCUMENT ME!
97    */
98   public void setQuerySeqPosition(int QuerySeqPosition)
99   {
100     this.QuerySeqPosition = QuerySeqPosition;
101   }
102
103   /**
104    * DOCUMENT ME!
105    * 
106    * @return DOCUMENT ME!
107    */
108   public int getQuerySeqPosition()
109   {
110     return QuerySeqPosition;
111   }
112
113   /**
114    * DOCUMENT ME!
115    * 
116    * @return DOCUMENT ME!
117    */
118   public Hashtable getScores()
119   {
120     return Scores;
121   }
122
123   /**
124    * DOCUMENT ME!
125    * 
126    * @return DOCUMENT ME!
127    */
128   public Hashtable getSymscores()
129   {
130     return Symscores;
131   }
132
133   /**
134    * DOCUMENT ME!
135    */
136   @Override
137   public void initData()
138   {
139     super.initData();
140     Scores = new Hashtable();
141     ids = null;
142     conf = null;
143   }
144
145   /**
146    * parse a JPred concise file into a sequence-alignment like object.
147    */
148   @Override
149   public void parse() throws IOException
150   {
151     // JBPNote log.System.out.println("all read in ");
152     String line;
153     QuerySeqPosition = -1;
154     noSeqs = 0;
155
156     Vector seq_entries = new Vector();
157     Vector ids = new Vector();
158     Hashtable Symscores = new Hashtable();
159
160     while ((line = nextLine()) != null)
161     {
162       // Concise format allows no comments or non comma-formatted data
163       StringTokenizer str = new StringTokenizer(line, ":");
164       String id = "";
165
166       if (!str.hasMoreTokens())
167       {
168         continue;
169       }
170
171       id = str.nextToken();
172
173       String seqsym = str.nextToken();
174       StringTokenizer symbols = new StringTokenizer(seqsym, ",");
175
176       // decide if we have more than just alphanumeric symbols
177       int numSymbols = symbols.countTokens();
178
179       if (numSymbols == 0)
180       {
181         continue;
182       }
183
184       if (seqsym.length() != (2 * numSymbols))
185       {
186         // Set of scalars for some property
187         if (Scores.containsKey(id))
188         {
189           int i = 1;
190
191           while (Scores.containsKey(id + "_" + i))
192           {
193             i++;
194           }
195
196           id = id + "_" + i;
197         }
198
199         Vector scores = new Vector();
200
201         // Typecheck from first entry
202         int i = 0;
203         String ascore = "dead";
204
205         try
206         {
207           // store elements as floats...
208           while (symbols.hasMoreTokens())
209           {
210             ascore = symbols.nextToken();
211
212             Float score = Float.valueOf(ascore);
213             scores.addElement(score);
214           }
215
216           Scores.put(id, scores);
217         } catch (Exception e)
218         {
219           // or just keep them as strings
220           i = scores.size();
221
222           for (int j = 0; j < i; j++)
223           {
224             scores.setElementAt(((Float) scores.elementAt(j)).toString(),
225                     j);
226           }
227
228           scores.addElement(ascore);
229
230           while (symbols.hasMoreTokens())
231           {
232             ascore = symbols.nextToken();
233             scores.addElement(ascore);
234           }
235
236           Scores.put(id, scores);
237         }
238       }
239       else if (id.equals("jnetconf"))
240       {
241         // log.debug System.out.println("here");
242         id = "Prediction Confidence";
243         this.conf = new Vector(numSymbols);
244
245         for (int i = 0; i < numSymbols; i++)
246         {
247           conf.setElementAt(symbols.nextToken(), i);
248         }
249       }
250       else
251       {
252         // Sequence or a prediction string (rendered as sequence)
253         StringBuffer newseq = new StringBuffer();
254
255         for (int i = 0; i < numSymbols; i++)
256         {
257           newseq.append(symbols.nextToken());
258         }
259
260         if (id.indexOf(";") > -1)
261         {
262           seq_entries.addElement(newseq);
263
264           int i = 1;
265           String name = id.substring(id.indexOf(";") + 1);
266
267           while (ids.lastIndexOf(name) > -1)
268           {
269             name = id.substring(id.indexOf(";") + 1) + "_" + ++i;
270           }
271
272           if (QuerySeqPosition == -1)
273           {
274             QuerySeqPosition = ids.size();
275           }
276           ids.addElement(name);
277           noSeqs++;
278         }
279         else
280         {
281           if (id.equals("JNETPRED"))
282           {
283             id = "Predicted Secondary Structure";
284           }
285
286           seq_entries.addElement(newseq.toString());
287           ids.addElement(id);
288           Symscores.put(id, Integer.valueOf(ids.size() - 1));
289         }
290       }
291     }
292     /*
293      * leave it to the parser user to actually check this. if (noSeqs < 1) {
294      * throw new IOException( "JpredFile Parser: No sequence in the
295      * prediction!"); }
296      */
297
298     maxLength = seq_entries.elementAt(0).toString().length();
299
300     for (int i = 0; i < ids.size(); i++)
301     {
302       // Add all sequence like objects
303       Sequence newSeq = new Sequence(ids.elementAt(i).toString(),
304               seq_entries.elementAt(i).toString(), 1,
305               seq_entries.elementAt(i).toString().length());
306
307       if (maxLength != seq_entries.elementAt(i).toString().length())
308       {
309         throw new IOException(MessageManager.formatMessage(
310                 "exception.jpredconcide_entry_has_unexpected_number_of_columns",
311                 new String[]
312                 { ids.elementAt(i).toString() }));
313       }
314
315       if ((newSeq.getName().startsWith("QUERY")
316               || newSeq.getName().startsWith("align;"))
317               && (QuerySeqPosition == -1))
318       {
319         QuerySeqPosition = seqs.size();
320       }
321
322       seqs.addElement(newSeq);
323     }
324     if (seqs.size() > 0 && QuerySeqPosition > -1)
325     {
326       // try to make annotation for a prediction only input (default if no
327       // alignment is given and prediction contains a QUERY or align;sequence_id
328       // line)
329       Alignment tal = new Alignment(this.getSeqsAsArray());
330       try
331       {
332         JnetAnnotationMaker.add_annotation(this, tal, QuerySeqPosition,
333                 true);
334       } catch (Exception e)
335       {
336         tal = null;
337         IOException ex = new IOException(MessageManager.formatMessage(
338                 "exception.couldnt_parse_concise_annotation_for_prediction",
339                 new String[]
340                 { e.getMessage() }));
341         e.printStackTrace(); // java 1.1 does not have :
342                              // ex.setStackTrace(e.getStackTrace());
343         throw ex;
344       }
345       this.annotations = new Vector();
346       AlignmentAnnotation[] aan = tal.getAlignmentAnnotation();
347       for (int aai = 0; aan != null && aai < aan.length; aai++)
348       {
349         annotations.addElement(aan[aai]);
350       }
351     }
352   }
353
354   /**
355    * print
356    * 
357    * @return String
358    */
359   @Override
360   public String print(SequenceI[] sqs, boolean jvsuffix)
361   {
362     return "Not Supported";
363   }
364
365   /**
366    * 
367    * @param args
368    * @j2sIgnore
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  */