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