update author list in license for (JAL-826)
[jalview.git] / src / jalview / io / JPredFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /**
19  * PredFile.java
20  * JalviewX / Vamsas Project
21  * JPred.seq.concise reader
22  */
23 package jalview.io;
24
25 import java.io.*;
26 import java.util.*;
27
28 import jalview.datamodel.*;
29
30 /**
31  * Parser for the JPred/JNet concise format. This is a series of CSV lines, each
32  * line is either a sequence (QUERY), a sequence profile (align;), or jnet
33  * prediction annotation (anything else). Automagic translation happens for
34  * annotation called 'JNETPRED' (translated to Secondary Structure Prediction),
35  * or 'JNETCONF' (translates to 'Prediction Confidence'). Numeric scores are
36  * differentiated from symbolic by being parseable into a float vector. They are
37  * put in Scores. Symscores gets the others. JNetAnnotationMaker translates the
38  * data parsed by this object into annotation on an alignment. It is
39  * automatically called but can be used to transfer the annotation onto a
40  * sequence in another alignment (and insert gaps where necessary)
41  * 
42  * @author jprocter
43  * @version $Revision$
44  */
45 public class JPredFile extends AlignFile
46 {
47   Vector ids;
48
49   Vector conf;
50
51   Hashtable Scores; // Hash of names and score vectors
52
53   Hashtable Symscores; // indexes of symbol annotation properties in sequenceI
54
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(
211                     (Object) ((Float) scores.elementAt(j)).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;")) && (QuerySeqPosition == -1))
300       {
301         QuerySeqPosition = seqs.size();
302       }
303
304       seqs.addElement(newSeq);
305     }
306     if (seqs.size() > 0 && QuerySeqPosition > -1)
307     {
308       // try to make annotation for a prediction only input (default if no
309       // alignment is given and prediction contains a QUERY or align;sequence_id
310       // 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 :
323                              // ex.setStackTrace(e.getStackTrace());
324         throw ex;
325       }
326       this.annotations = new Vector();
327       AlignmentAnnotation[] aan = tal.getAlignmentAnnotation();
328       for (int aai = 0; aan != null && aai < aan.length; aai++)
329       {
330         annotations.addElement(aan[aai]);
331       }
332     }
333   }
334
335   /**
336    * print
337    * 
338    * @return String
339    */
340   public String print()
341   {
342     return "Not Supported";
343   }
344
345   /**
346    * DOCUMENT ME!
347    * 
348    * @param args
349    *          DOCUMENT ME!
350    */
351   public static void main(String[] args)
352   {
353     try
354     {
355       JPredFile blc = new JPredFile(args[0], "File");
356
357       for (int i = 0; i < blc.seqs.size(); i++)
358       {
359         System.out.println(((Sequence) blc.seqs.elementAt(i)).getName()
360                 + "\n"
361                 + ((Sequence) blc.seqs.elementAt(i)).getSequenceAsString()
362                 + "\n");
363       }
364     } catch (java.io.IOException e)
365     {
366       System.err.println("Exception " + e);
367       // e.printStackTrace(); not java 1.1 compatible!
368     }
369   }
370
371   Vector annotSeqs = null;
372
373   /**
374    * removeNonSequences
375    */
376   public void removeNonSequences()
377   {
378     if (annotSeqs != null)
379     {
380       return;
381     }
382     annotSeqs = new Vector();
383     Vector newseqs = new Vector();
384     int i = 0;
385     int j = seqs.size();
386     for (; i < QuerySeqPosition; i++)
387     {
388       annotSeqs.addElement(seqs.elementAt(i));
389     }
390     // check that no stray annotations have been added at the end.
391     {
392       SequenceI sq = (SequenceI) seqs.elementAt(j - 1);
393       if (sq.getName().toUpperCase().startsWith("JPRED"))
394       {
395         annotSeqs.addElement(sq);
396         seqs.removeElementAt(--j);
397       }
398     }
399     for (; i < j; i++)
400     {
401       newseqs.addElement(seqs.elementAt(i));
402     }
403
404     seqs.removeAllElements();
405     seqs = newseqs;
406   }
407 }
408
409 /*
410  * StringBuffer out = new StringBuffer();
411  * 
412  * out.append("START PRED\n"); for (int i = 0; i < s[0].sequence.length(); i++)
413  * { out.append(s[0].sequence.substring(i, i + 1) + " ");
414  * out.append(s[1].sequence.substring(i, i + 1) + " ");
415  * out.append(s[1].score[0].elementAt(i) + " ");
416  * out.append(s[1].score[1].elementAt(i) + " ");
417  * out.append(s[1].score[2].elementAt(i) + " ");
418  * out.append(s[1].score[3].elementAt(i) + " ");
419  * 
420  * out.append("\n"); } out.append("END PRED\n"); return out.toString(); }
421  * 
422  * public static void main(String[] args) { try { BLCFile blc = new
423  * BLCFile(args[0], "File"); DrawableSequence[] s = new
424  * DrawableSequence[blc.seqs.size()]; for (int i = 0; i < blc.seqs.size(); i++)
425  * { s[i] = new DrawableSequence( (Sequence) blc.seqs.elementAt(i)); } String
426  * out = BLCFile.print(s);
427  * 
428  * AlignFrame af = new AlignFrame(null, s); af.resize(700, 500); af.show();
429  * System.out.println(out); } catch (java.io.IOException e) {
430  * System.out.println("Exception " + e); } } }
431  */