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