minor optimization. apply gpl development license
[jalview.git] / src / jalview / io / MSFfile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 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 package jalview.io;
20
21 import java.io.*;
22 import java.util.*;
23
24 import jalview.datamodel.*;
25 import jalview.util.*;
26
27 /**
28  * DOCUMENT ME!
29  * 
30  * @author $author$
31  * @version $Revision$
32  */
33 public class MSFfile extends AlignFile
34 {
35
36   /**
37    * Creates a new MSFfile object.
38    */
39   public MSFfile()
40   {
41   }
42
43   /**
44    * Creates a new MSFfile object.
45    * 
46    * @param inFile
47    *                DOCUMENT ME!
48    * @param type
49    *                DOCUMENT ME!
50    * 
51    * @throws IOException
52    *                 DOCUMENT ME!
53    */
54   public MSFfile(String inFile, String type) throws IOException
55   {
56     super(inFile, type);
57   }
58
59   public MSFfile(FileParse source) throws IOException
60   {
61     super(source);
62   }
63
64   {
65     // TODO Auto-generated constructor stub
66   }
67
68   /**
69    * DOCUMENT ME!
70    */
71   public void parse() throws IOException
72   {
73     int i = 0;
74     boolean seqFlag = false;
75     String key = new String();
76     Vector headers = new Vector();
77     Hashtable seqhash = new Hashtable();
78     String line;
79
80     try
81     {
82       while ((line = nextLine()) != null)
83       {
84         StringTokenizer str = new StringTokenizer(line);
85
86         while (str.hasMoreTokens())
87         {
88           String inStr = str.nextToken();
89
90           // If line has header information add to the headers vector
91           if (inStr.indexOf("Name:") != -1)
92           {
93             key = str.nextToken();
94             headers.addElement(key);
95           }
96
97           // if line has // set SeqFlag to 1 so we know sequences are coming
98           if (inStr.indexOf("//") != -1)
99           {
100             seqFlag = true;
101           }
102
103           // Process lines as sequence lines if seqFlag is set
104           if ((inStr.indexOf("//") == -1) && (seqFlag == true))
105           {
106             // seqeunce id is the first field
107             key = inStr;
108
109             StringBuffer tempseq;
110
111             // Get sequence from hash if it exists
112             if (seqhash.containsKey(key))
113             {
114               tempseq = (StringBuffer) seqhash.get(key);
115             }
116             else
117             {
118               tempseq = new StringBuffer();
119               seqhash.put(key, tempseq);
120             }
121
122             // loop through the rest of the words
123             while (str.hasMoreTokens())
124             {
125               // append the word to the sequence
126               tempseq.append(str.nextToken());
127             }
128           }
129         }
130       }
131     } catch (IOException e)
132     {
133       System.err.println("Exception parsing MSFFile " + e);
134       e.printStackTrace();
135     }
136
137     this.noSeqs = headers.size();
138
139     // Add sequences to the hash
140     for (i = 0; i < headers.size(); i++)
141     {
142       if (seqhash.get(headers.elementAt(i)) != null)
143       {
144         String head = headers.elementAt(i).toString();
145         String seq = seqhash.get(head).toString();
146
147         if (maxLength < head.length())
148         {
149           maxLength = head.length();
150         }
151
152         // Replace ~ with a sensible gap character
153         seq = seq.replace('~', '-');
154
155         Sequence newSeq = parseId(head);
156
157         newSeq.setSequence(seq);
158
159         seqs.addElement(newSeq);
160       }
161       else
162       {
163         System.err.println("MSFFile Parser: Can't find sequence for "
164                 + headers.elementAt(i));
165       }
166     }
167   }
168
169   /**
170    * DOCUMENT ME!
171    * 
172    * @param seq
173    *                DOCUMENT ME!
174    * 
175    * @return DOCUMENT ME!
176    */
177   public int checkSum(String seq)
178   {
179     int check = 0;
180     String sequence = seq.toUpperCase();
181
182     for (int i = 0; i < sequence.length(); i++)
183     {
184       try
185       {
186
187         int value = sequence.charAt(i);
188         if (value != -1)
189         {
190           check += (i % 57 + 1) * value;
191         }
192       } catch (Exception e)
193       {
194         System.err.println("Exception during MSF Checksum calculation");
195         e.printStackTrace();
196       }
197     }
198
199     return check % 10000;
200   }
201
202   /**
203    * DOCUMENT ME!
204    * 
205    * @param s
206    *                DOCUMENT ME!
207    * @param is_NA
208    *                DOCUMENT ME!
209    * 
210    * @return DOCUMENT ME!
211    */
212   public String print(SequenceI[] seqs)
213   {
214
215     boolean is_NA = jalview.util.Comparison.isNucleotide(seqs);
216
217     SequenceI[] s = new SequenceI[seqs.length];
218
219     StringBuffer out = new StringBuffer("!!" + (is_NA ? "NA" : "AA")
220             + "_MULTIPLE_ALIGNMENT 1.0\n\n"); // TODO: JBPNote : Jalview doesn't
221                                               // remember NA or AA yet.
222
223     int max = 0;
224     int maxid = 0;
225     int i = 0;
226
227     while ((i < seqs.length) && (seqs[i] != null))
228     {
229       // Replace all internal gaps with . and external spaces with ~
230       s[i] = new Sequence(seqs[i].getName(), seqs[i].getSequenceAsString()
231               .replace('-', '.'));
232
233       StringBuffer sb = new StringBuffer();
234       sb.append(s[i].getSequence());
235
236       for (int ii = 0; ii < sb.length(); ii++)
237       {
238         if (sb.charAt(ii) == '.')
239         {
240           sb.setCharAt(ii, '~');
241         }
242         else
243         {
244           break;
245         }
246       }
247
248       for (int ii = sb.length() - 1; ii > 0; ii--)
249       {
250         if (sb.charAt(ii) == '.')
251         {
252           sb.setCharAt(ii, '~');
253         }
254         else
255         {
256           break;
257         }
258       }
259
260       s[i].setSequence(sb.toString());
261
262       if (s[i].getSequence().length > max)
263       {
264         max = s[i].getSequence().length;
265       }
266
267       i++;
268     }
269
270     Format maxLenpad = new Format("%" + (new String("" + max)).length()
271             + "d");
272     Format maxChkpad = new Format("%" + (new String("1" + max)).length()
273             + "d");
274     i = 0;
275
276     int bigChecksum = 0;
277     int[] checksums = new int[s.length];
278     while (i < s.length)
279     {
280       checksums[i] = checkSum(s[i].getSequenceAsString());
281       bigChecksum += checksums[i];
282       i++;
283     }
284
285     long maxNB = 0;
286     out.append("   MSF: " + s[0].getSequence().length + "   Type: "
287             + (is_NA ? "N" : "P") + "    Check:  " + (bigChecksum % 10000)
288             + "   ..\n\n\n");
289
290     String[] nameBlock = new String[s.length];
291     String[] idBlock = new String[s.length];
292
293     i = 0;
294     while ((i < s.length) && (s[i] != null))
295     {
296
297       nameBlock[i] = new String("  Name: " + printId(s[i]) + " ");
298
299       idBlock[i] = new String("Len: "
300               + maxLenpad.form(s[i].getSequence().length) + "  Check: "
301               + maxChkpad.form(checksums[i]) + "  Weight: 1.00\n");
302
303       if (s[i].getName().length() > maxid)
304       {
305         maxid = s[i].getName().length();
306       }
307
308       if (nameBlock[i].length() > maxNB)
309       {
310         maxNB = nameBlock[i].length();
311       }
312
313       i++;
314     }
315
316     if (maxid < 10)
317     {
318       maxid = 10;
319     }
320
321     if (maxNB < 15)
322     {
323       maxNB = 15;
324     }
325
326     Format nbFormat = new Format("%-" + maxNB + "s");
327
328     for (i = 0; (i < s.length) && (s[i] != null); i++)
329     {
330       out.append(nbFormat.form(nameBlock[i]) + idBlock[i]);
331     }
332
333     maxid++;
334     out.append("\n\n//\n\n");
335
336     int len = 50;
337
338     int nochunks = (max / len) + 1;
339
340     if ((max % len) == 0)
341     {
342       nochunks--;
343     }
344
345     for (i = 0; i < nochunks; i++)
346     {
347       int j = 0;
348
349       while ((j < s.length) && (s[j] != null))
350       {
351         String name = printId(s[j]);
352
353         out.append(new Format("%-" + maxid + "s").form(name + " "));
354
355         for (int k = 0; k < 5; k++)
356         {
357           int start = (i * 50) + (k * 10);
358           int end = start + 10;
359
360           if ((end < s[j].getSequence().length)
361                   && (start < s[j].getSequence().length))
362           {
363             out.append(s[j].getSequence(start, end));
364
365             if (k < 4)
366             {
367               out.append(" ");
368             }
369             else
370             {
371               out.append("\n");
372             }
373           }
374           else
375           {
376             if (start < s[j].getSequence().length)
377             {
378               out.append(s[j].getSequenceAsString().substring(start));
379               out.append("\n");
380             }
381             else
382             {
383               if (k == 0)
384               {
385                 out.append("\n");
386               }
387             }
388           }
389         }
390
391         j++;
392       }
393
394       out.append("\n");
395     }
396
397     return out.toString();
398   }
399
400   /**
401    * DOCUMENT ME!
402    * 
403    * @return DOCUMENT ME!
404    */
405   public String print()
406   {
407     return print(getSeqsAsArray());
408   }
409 }