e5fc584726ea1eedea963e5eeaf23436b55d1767
[jalview.git] / src / jalview / io / AppletFormatAdapter.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.File;
22
23 import jalview.datamodel.*;
24
25 /**
26  * A low level class for alignment and feature IO with alignment formatting
27  * methods used by both applet and application for generating flat alignment
28  * files. It also holds the lists of magic format names that the applet and
29  * application will allow the user to read or write files with.
30  * 
31  * @author $author$
32  * @version $Revision$
33  */
34 public class AppletFormatAdapter
35 {
36   /**
37    * List of valid format strings used in the isValidFormat method
38    */
39   public static final String[] READABLE_FORMATS = new String[]
40   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
41       "PDB", "JnetFile" };
42
43   /**
44    * List of valid format strings for use by callers of the formatSequences
45    * method
46    */
47   public static final String[] WRITEABLE_FORMATS = new String[]
48   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA" };
49
50   /**
51    * List of extensions corresponding to file format types in WRITABLE_FNAMES
52    * that are writable by the application.
53    */
54   public static final String[] WRITABLE_EXTENSIONS = new String[]
55   { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar" };
56
57   /**
58    * List of writable formats by the application. Order must correspond with the
59    * WRITABLE_EXTENSIONS list of formats.
60    */
61   public static final String[] WRITABLE_FNAMES = new String[]
62   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" };
63
64   /**
65    * List of readable format file extensions by application in order
66    * corresponding to READABLE_FNAMES
67    */
68   public static final String[] READABLE_EXTENSIONS = new String[]
69   { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar" };
70
71   /**
72    * List of readable formats by application in order corresponding to
73    * READABLE_EXTENSIONS
74    */
75   public static final String[] READABLE_FNAMES = new String[]
76   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" };
77
78   public static String INVALID_CHARACTERS = "Contains invalid characters";
79
80   // TODO: make these messages dynamic
81   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
82           + prettyPrint(READABLE_FORMATS);
83
84   /**
85    * 
86    * @param els
87    * @return grammatically correct(ish) list consisting of els elements.
88    */
89   public static String prettyPrint(String[] els)
90   {
91     StringBuffer list = new StringBuffer();
92     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
93     {
94       list.append(els[i]);
95       list.append(",");
96     }
97     list.append(" and " + els[els.length - 1] + ".");
98     return list.toString();
99   }
100
101   public static String FILE = "File";
102
103   public static String URL = "URL";
104
105   public static String PASTE = "Paste";
106
107   public static String CLASSLOADER = "ClassLoader";
108
109   AlignFile afile = null;
110
111   String inFile;
112
113   /**
114    * check that this format is valid for reading
115    * 
116    * @param format
117    *                a format string to be compared with READABLE_FORMATS
118    * @return true if format is readable
119    */
120   public static final boolean isValidFormat(String format)
121   {
122     return isValidFormat(format, false);
123   }
124
125   /**
126    * validate format is valid for IO
127    * 
128    * @param format
129    *                a format string to be compared with either READABLE_FORMATS
130    *                or WRITEABLE_FORMATS
131    * @param forwriting
132    *                when true, format is checked for containment in
133    *                WRITEABLE_FORMATS
134    * @return true if format is valid
135    */
136   public static final boolean isValidFormat(String format,
137           boolean forwriting)
138   {
139     boolean valid = false;
140     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
141             : READABLE_FORMATS;
142     for (int i = 0; i < format_list.length; i++)
143     {
144       if (format_list[i].equalsIgnoreCase(format))
145       {
146         return true;
147       }
148     }
149
150     return valid;
151   }
152
153   /**
154    * Constructs the correct filetype parser for a characterised datasource
155    * 
156    * @param inFile
157    *                data/data location
158    * @param type
159    *                type of datasource
160    * @param format
161    *                File format of data provided by datasource
162    * 
163    * @return DOCUMENT ME!
164    */
165   public Alignment readFile(String inFile, String type, String format)
166           throws java.io.IOException
167   {
168     // TODO: generalise mapping between format string and io. class instances
169     // using Constructor.invoke reflection
170     this.inFile = inFile;
171     try
172     {
173       if (format.equals("FASTA"))
174       {
175         afile = new FastaFile(inFile, type);
176       }
177       else if (format.equals("MSF"))
178       {
179         afile = new MSFfile(inFile, type);
180       }
181       else if (format.equals("PileUp"))
182       {
183         afile = new PileUpfile(inFile, type);
184       }
185       else if (format.equals("CLUSTAL"))
186       {
187         afile = new ClustalFile(inFile, type);
188       }
189       else if (format.equals("BLC"))
190       {
191         afile = new BLCFile(inFile, type);
192       }
193       else if (format.equals("PIR"))
194       {
195         afile = new PIRFile(inFile, type);
196       }
197       else if (format.equals("PFAM"))
198       {
199         afile = new PfamFile(inFile, type);
200       }
201       else if (format.equals("JnetFile"))
202       {
203         afile = new JPredFile(inFile, type);
204         ((JPredFile) afile).removeNonSequences();
205       }
206       else if (format.equals("PDB"))
207       {
208         afile = new MCview.PDBfile(inFile, type);
209       }
210       else if (format.equals("STH"))
211       {
212         afile = new StockholmFile(inFile, type);
213       }
214
215       Alignment al = new Alignment(afile.getSeqsAsArray());
216
217       afile.addAnnotations(al);
218
219       return al;
220     } catch (Exception e)
221     {
222       e.printStackTrace();
223       System.err.println("Failed to read alignment using the '" + format
224               + "' reader.\n" + e);
225
226       if (e.getMessage() != null
227               && e.getMessage().startsWith(INVALID_CHARACTERS))
228       {
229         throw new java.io.IOException(e.getMessage());
230       }
231
232       // Finally test if the user has pasted just the sequence, no id
233       if (type.equalsIgnoreCase("Paste"))
234       {
235         try
236         {
237           // Possible sequence is just residues with no label
238           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
239           Alignment al = new Alignment(afile.getSeqsAsArray());
240           afile.addAnnotations(al);
241           return al;
242
243         } catch (Exception ex)
244         {
245           if (ex.toString().startsWith(INVALID_CHARACTERS))
246           {
247             throw new java.io.IOException(e.getMessage());
248           }
249
250           ex.printStackTrace();
251         }
252       }
253
254       // If we get to this stage, the format was not supported
255       throw new java.io.IOException(SUPPORTED_FORMATS);
256     }
257   }
258
259   /**
260    * Constructs the correct filetype parser for an already open datasource
261    * 
262    * @param source
263    *                an existing datasource
264    * @param format
265    *                File format of data that will be provided by datasource
266    * 
267    * @return DOCUMENT ME!
268    */
269   public Alignment readFromFile(FileParse source, String format)
270           throws java.io.IOException
271   {
272     // TODO: generalise mapping between format string and io. class instances
273     // using Constructor.invoke reflection
274     // This is exactly the same as the readFile method except we substitute
275     // 'inFile, type' with 'source'
276     this.inFile = source.getInFile();
277     String type = source.type;
278     try
279     {
280       if (format.equals("FASTA"))
281       {
282         afile = new FastaFile(source);
283       }
284       else if (format.equals("MSF"))
285       {
286         afile = new MSFfile(source);
287       }
288       else if (format.equals("PileUp"))
289       {
290         afile = new PileUpfile(source);
291       }
292       else if (format.equals("CLUSTAL"))
293       {
294         afile = new ClustalFile(source);
295       }
296       else if (format.equals("BLC"))
297       {
298         afile = new BLCFile(source);
299       }
300       else if (format.equals("PIR"))
301       {
302         afile = new PIRFile(source);
303       }
304       else if (format.equals("PFAM"))
305       {
306         afile = new PfamFile(source);
307       }
308       else if (format.equals("JnetFile"))
309       {
310         afile = new JPredFile(source);
311         ((JPredFile) afile).removeNonSequences();
312       }
313       else if (format.equals("PDB"))
314       {
315         afile = new MCview.PDBfile(source);
316       }
317       else if (format.equals("STH"))
318       {
319         afile = new StockholmFile(source);
320       }
321
322       Alignment al = new Alignment(afile.getSeqsAsArray());
323
324       afile.addAnnotations(al);
325
326       return al;
327     } catch (Exception e)
328     {
329       e.printStackTrace();
330       System.err.println("Failed to read alignment using the '" + format
331               + "' reader.\n" + e);
332
333       if (e.getMessage() != null
334               && e.getMessage().startsWith(INVALID_CHARACTERS))
335       {
336         throw new java.io.IOException(e.getMessage());
337       }
338
339       // Finally test if the user has pasted just the sequence, no id
340       if (type.equalsIgnoreCase("Paste"))
341       {
342         try
343         {
344           // Possible sequence is just residues with no label
345           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
346           Alignment al = new Alignment(afile.getSeqsAsArray());
347           afile.addAnnotations(al);
348           return al;
349
350         } catch (Exception ex)
351         {
352           if (ex.toString().startsWith(INVALID_CHARACTERS))
353           {
354             throw new java.io.IOException(e.getMessage());
355           }
356
357           ex.printStackTrace();
358         }
359       }
360
361       // If we get to this stage, the format was not supported
362       throw new java.io.IOException(SUPPORTED_FORMATS);
363     }
364   }
365
366   /**
367    * Construct an output class for an alignment in a particular filetype
368    * 
369    * @param format
370    *                string name of alignment format
371    * @param alignment
372    *                the alignment to be written out
373    * @param jvsuffix
374    *                passed to AlnFile class controls whether /START-END is added
375    *                to sequence names
376    * 
377    * @return alignment flat file contents
378    */
379   public String formatSequences(String format, AlignmentI alignment,
380           boolean jvsuffix)
381   {
382     try
383     {
384       AlignFile afile = null;
385
386       if (format.equalsIgnoreCase("FASTA"))
387       {
388         afile = new FastaFile();
389       }
390       else if (format.equalsIgnoreCase("MSF"))
391       {
392         afile = new MSFfile();
393       }
394       else if (format.equalsIgnoreCase("PileUp"))
395       {
396         afile = new PileUpfile();
397       }
398       else if (format.equalsIgnoreCase("CLUSTAL"))
399       {
400         afile = new ClustalFile();
401       }
402       else if (format.equalsIgnoreCase("BLC"))
403       {
404         afile = new BLCFile();
405       }
406       else if (format.equalsIgnoreCase("PIR"))
407       {
408         afile = new PIRFile();
409       }
410       else if (format.equalsIgnoreCase("PFAM"))
411       {
412         afile = new PfamFile();
413       }
414       else if (format.equalsIgnoreCase("STH"))
415       {
416         afile = new StockholmFile();
417       }
418       else if (format.equalsIgnoreCase("AMSA"))
419       {
420         afile = new AMSAFile(alignment);
421       }
422       else
423       {
424         throw new Exception(
425                 "Implementation error: Unknown file format string");
426       }
427
428       afile.addJVSuffix(jvsuffix);
429
430       afile.setSeqs(alignment.getSequencesArray());
431
432       return afile.print();
433     } catch (Exception e)
434     {
435       System.err.println("Failed to write alignment as a '" + format
436               + "' file\n");
437       e.printStackTrace();
438     }
439
440     return null;
441   }
442
443   public static void main(String[] args)
444   {
445     int i = 0;
446     while (i < args.length)
447     {
448       File f = new File(args[i]);
449       if (f.exists())
450       {
451         try
452         {
453           System.out.println("Reading file: " + f);
454           AppletFormatAdapter afa = new AppletFormatAdapter();
455           Runtime r = Runtime.getRuntime();
456           System.gc();
457           long memf = -r.totalMemory() + r.freeMemory();
458           long t1 = -System.currentTimeMillis();
459           Alignment al = afa.readFile(args[i], FILE, new IdentifyFile()
460                   .Identify(args[i], FILE));
461           t1 += System.currentTimeMillis();
462           System.gc();
463           memf += r.totalMemory() - r.freeMemory();
464           if (al != null)
465           {
466             System.out.println("Alignment contains " + al.getHeight()
467                     + " sequences and " + al.getWidth() + " columns.");
468           }
469           else
470           {
471             System.out.println("Couldn't read alignment");
472           }
473           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
474           System.out
475                   .println("Difference between free memory now and before is "
476                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
477
478         } catch (Exception e)
479         {
480           System.err.println("Exception when dealing with " + i
481                   + "'th argument: " + args[i] + "\n" + e);
482         }
483       }
484       else
485       {
486         System.err.println("Ignoring argument '" + args[i] + "' (" + i
487                 + "'th)- not a readable file.");
488       }
489       i++;
490     }
491
492   }
493 }