GPL license added
[jalview.git] / src / jalview / io / JPredFile.java
1 /*
2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 */
19
20 /**
21  * PredFile.java
22  * JalviewX / Vamsas Project
23  * JPred.seq.concise reader
24  */
25
26 package jalview.io;
27
28 import jalview.datamodel.*;
29 import jalview.util.*;
30
31 import java.io.*;
32 import java.util.*;
33
34 public class JPredFile
35     extends AlignFile
36 {
37   Vector ids;
38   Vector conf;
39   Hashtable Scores; // Hash of names and score vectors
40   Hashtable Symscores; // indexes of symbol annotation properties in sequenceI vector
41   private int QuerySeqPosition;
42   public void setQuerySeqPosition(int QuerySeqPosition)
43   {
44     this.QuerySeqPosition = QuerySeqPosition;
45   }
46
47   public int getQuerySeqPosition()
48   {
49     return QuerySeqPosition;
50   }
51   public Hashtable getScores() {
52     return Scores;
53   }
54   public Hashtable getSymscores() {
55     return Symscores;
56   }
57
58   public JPredFile(String inStr)
59   {
60     super(inStr);
61   }
62
63   public void initData()
64   {
65
66     super.initData();
67     Scores = new Hashtable();
68     ids = null;
69     conf = null;
70   }
71
72   public JPredFile(String inFile, String type)
73       throws IOException
74   {
75
76     super(inFile, type);
77   }
78
79   /**
80    * parse a JPred concise file into a sequence-alignment like object.
81    */
82   public void parse()
83       throws IOException
84   {
85     // JBPNote log.System.out.println("all read in ");
86     String line;
87     QuerySeqPosition = -1;
88     noSeqs = 0;
89     Vector seq_entries = new Vector();
90     Vector ids = new Vector();
91     Hashtable Symscores = new Hashtable();
92     while ( (line = nextLine()) != null)
93     {
94       // Concise format allows no comments or non comma-formatted data
95       StringTokenizer str = new StringTokenizer(line, ":");
96       String id = "";
97       if (!str.hasMoreTokens())
98       {
99         continue;
100       }
101
102       id = str.nextToken();
103       String seqsym = str.nextToken();
104       StringTokenizer symbols = new StringTokenizer(seqsym, ",");
105       // decide if we have more than just alphanumeric symbols
106       int numSymbols = symbols.countTokens();
107
108       if (numSymbols==0) {
109         continue;
110       }
111
112       if (seqsym.length() != (2 * numSymbols))
113       {
114         // Set of scalars for some property
115         if (Scores.containsKey(id))
116         {
117           int i = 1;
118           while (Scores.containsKey(id + "_" + i))
119           {
120             i++;
121           }
122           id = id + "_" + i;
123         }
124         Vector scores = new Vector();
125         // Typecheck from first entry
126         int i = 0;
127         String ascore="dead";
128         try
129         {
130           // store elements as floats...
131           while (symbols.hasMoreTokens()) {
132             ascore = symbols.nextToken();
133             Float score = new Float(ascore);
134             scores.addElement( (Object) score);
135           }
136           Scores.put(id, scores);
137         }
138         catch (Exception e)
139         {
140           // or just keep them as strings
141           i = scores.size();
142           for (int j = 0; j < i; j++)
143           {
144             scores.set(j,
145                        (Object) ( (Float) scores.get(j)).toString());
146           }
147           scores.addElement((Object) ascore);
148           while (symbols.hasMoreTokens()) {
149             {
150               ascore = symbols.nextToken();
151               scores.addElement( (Object) ascore);
152             }
153           }
154           Scores.put(id, scores);
155         }
156       }
157       else if (id.equals("jnetconf"))
158       {
159         // log.debug System.out.println("here");
160         id = "Prediction Confidence";
161         this.conf = new Vector(numSymbols);
162         for (int i = 0; i < numSymbols; i++)
163         {
164           conf.set(i, (Object) symbols.nextToken());
165         }
166       }
167       else
168         {
169           // Sequence or a prediction string (rendered as sequence)
170
171           StringBuffer newseq = new StringBuffer();
172
173           for (int i = 0; i < numSymbols; i++) {
174             newseq.append(symbols.nextToken());
175           }
176
177           if (id.indexOf(";") > -1) {
178             seq_entries.addElement(newseq);
179             int i=1;
180             String name = id.substring(id.indexOf(";")+1);
181             while (ids.lastIndexOf(name)>-1) {
182               name = id.substring(id.indexOf(";")+1)+"_"+1;
183             }
184             ids.addElement(name);
185
186             noSeqs++;
187           }
188           else
189           {
190             if (id.equals("JNETPRED")) {
191               id = "Predicted Secondary Structure";
192             }
193             seq_entries.addElement( newseq.toString() );
194             ids.addElement(id);
195             Symscores.put((Object) id, (Object) new Integer(ids.size()-1));
196           }
197       }
198     }
199
200
201     if (noSeqs < 1)
202     {
203       throw new IOException(
204       "JpredFile Parser: No sequence in the prediction!");
205     }
206     maxLength = seq_entries.elementAt(0).toString().length();
207     for (int i = 0; i < ids.size(); i++)
208     {
209       // Add all sequence like objects
210
211       Sequence newSeq = new Sequence(ids.elementAt(i).toString(),
212                                      seq_entries.elementAt(i).toString(), 1,
213                                      seq_entries.elementAt(i).toString().
214                                      length());
215       if (!Symscores.containsKey(ids.elementAt(i))
216           && !isValidProteinSequence(newSeq.getSequence()))
217       {
218         throw new IOException(
219       "JPredConcise: Not a valid protein sequence - ("
220       + ids.elementAt(i).toString() + ")");
221       }
222
223       if (maxLength != seq_entries.elementAt(i).toString().length())
224       {
225         throw new IOException("JPredConcise: Entry (" +
226                               ids.elementAt(i).toString()
227                               + ") has an unexpected number of columns");
228       }
229       if (newSeq.getName().startsWith("QUERY") && QuerySeqPosition==-1) {
230         QuerySeqPosition = seqs.size();
231       }
232
233       seqs.addElement(newSeq);
234
235     }
236   }
237
238   /**
239    * print
240    *
241    * @return String
242      */
243
244     public String print()
245     {
246       return "Not Supported";
247     }
248
249     public static void main(String[] args)
250     {
251       try
252       {
253         JPredFile blc = new JPredFile(args[0], "File");
254         for (int i = 0; i < blc.seqs.size(); i++)
255         {
256           System.out.println( ( (Sequence) blc.seqs.elementAt(i)).getName()
257                              + "\n" +
258                              ( (Sequence) blc.seqs.elementAt(i)).getSequence()
259                              + "\n");
260         }
261       }
262       catch (java.io.IOException e)
263       {
264         System.err.println("Exception " + e);
265         e.printStackTrace();
266       }
267     }
268   }
269
270   /*
271    StringBuffer out = new StringBuffer();
272
273    out.append("START PRED\n");
274    for (int i = 0; i < s[0].sequence.length(); i++)
275    {
276     out.append(s[0].sequence.substring(i, i + 1) + " ");
277     out.append(s[1].sequence.substring(i, i + 1) + " ");
278     out.append(s[1].score[0].elementAt(i) + " ");
279     out.append(s[1].score[1].elementAt(i) + " ");
280     out.append(s[1].score[2].elementAt(i) + " ");
281     out.append(s[1].score[3].elementAt(i) + " ");
282
283     out.append("\n");
284    }
285    out.append("END PRED\n");
286    return out.toString();
287    }
288
289       public static void main(String[] args)
290    {
291     try
292     {
293       BLCFile blc = new BLCFile(args[0], "File");
294       DrawableSequence[] s = new DrawableSequence[blc.seqs.size()];
295       for (int i = 0; i < blc.seqs.size(); i++)
296       {
297         s[i] = new DrawableSequence( (Sequence) blc.seqs.elementAt(i));
298       }
299       String out = BLCFile.print(s);
300
301       AlignFrame af = new AlignFrame(null, s);
302       af.resize(700, 500);
303       af.show();
304       System.out.println(out);
305     }
306     catch (java.io.IOException e)
307     {
308       System.out.println("Exception " + e);
309     }
310    }
311
312    }
313    */