fully integrate HMMER3 file format into Jalview
[jalview.git] / src / jalview / io / IdentifyFile.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 java.io.IOException;
24
25 /**
26  * DOCUMENT ME!
27  *
28  * @author $author$
29  * @version $Revision$
30  */
31 public class IdentifyFile
32 {
33   /**
34    * Identify a datasource's file content.
35    *
36    * @note Do not use this method for stream sources - create a FileParse object
37    *       instead.
38    *
39    * @param file
40    * @param sourceType
41    * @return
42    * @throws FileFormatException
43    */
44   public FileFormatI identify(String file, DataSourceType sourceType)
45           throws FileFormatException
46   {
47     String emessage = "UNIDENTIFIED FILE PARSING ERROR";
48     FileParse parser = null;
49     try
50     {
51       parser = new FileParse(file, sourceType);
52       if (parser.isValid())
53       {
54         return identify(parser);
55       }
56     } catch (Exception e)
57     {
58       System.err.println("Error whilst identifying");
59       e.printStackTrace(System.err);
60       emessage = e.getMessage();
61     }
62     if (parser != null)
63     {
64       throw new FileFormatException(parser.errormessage);
65     }
66     throw new FileFormatException(emessage);
67   }
68
69   public FileFormatI identify(FileParse source) throws FileFormatException
70   {
71     return identify(source, true);
72     // preserves original behaviour prior to version 2.3
73   }
74
75   public FileFormatI identify(AlignmentFileReaderI file, boolean closeSource)
76           throws IOException
77   {
78     FileParse fp = new FileParse(file.getInFile(), file.getDataSourceType());
79     return identify(fp, closeSource);
80   }
81
82   /**
83    * Identify contents of source, closing it or resetting source to start
84    * afterwards.
85    *
86    * @param source
87    * @param closeSource
88    * @return (best guess at) file format
89    * @throws FileFormatException
90    */
91   public FileFormatI identify(FileParse source, boolean closeSource)
92           throws FileFormatException
93   {
94     FileFormatI reply = FileFormat.Pfam;
95     String data;
96     int bytesRead = 0;
97     int trimmedLength = 0;
98     boolean lineswereskipped = false;
99     boolean isBinary = false; // true if length is non-zero and non-printable
100     // characters are encountered
101
102     try
103     {
104       if (!closeSource)
105       {
106         source.mark();
107       }
108       boolean aaIndexHeaderRead = false;
109
110       while ((data = source.nextLine()) != null)
111       {
112         bytesRead += data.length();
113         trimmedLength += data.trim().length();
114         if (!lineswereskipped)
115         {
116           for (int i = 0; !isBinary && i < data.length(); i++)
117           {
118             char c = data.charAt(i);
119             isBinary = (c < 32 && c != '\t' && c != '\n' && c != '\r'
120                     && c != 5 && c != 27); // nominal binary character filter
121             // excluding CR, LF, tab,DEL and ^E
122             // for certain blast ids
123           }
124         }
125         if (isBinary)
126         {
127           // jar files are special - since they contain all sorts of random
128           // characters.
129           if (source.inFile != null)
130           {
131             String fileStr = source.inFile.getName();
132             // possibly a Jalview archive.
133             if (fileStr.lastIndexOf(".jar") > -1
134                     || fileStr.lastIndexOf(".zip") > -1)
135             {
136               reply = FileFormat.Jalview;
137             }
138           }
139           if (!lineswereskipped && data.startsWith("PK"))
140           {
141             reply = FileFormat.Jalview; // archive.
142             break;
143           }
144         }
145         data = data.toUpperCase();
146
147         if (data.startsWith(ScoreMatrixFile.SCOREMATRIX))
148         {
149           reply = FileFormat.ScoreMatrix;
150           break;
151         }
152         if (data.startsWith("HMMER3"))
153         {
154           reply = FileFormat.HMMER3;
155           break;
156         }
157         if (data.startsWith("H ") && !aaIndexHeaderRead)
158         {
159           aaIndexHeaderRead = true;
160         }
161         if (data.startsWith("D ") && aaIndexHeaderRead)
162         {
163           reply = FileFormat.ScoreMatrix;
164           break;
165         }
166         if (data.startsWith("##GFF-VERSION"))
167         {
168           // GFF - possibly embedded in a Jalview features file!
169           reply = FileFormat.Features;
170           break;
171         }
172         if (looksLikeFeatureData(data))
173         {
174           reply = FileFormat.Features;
175           break;
176         }
177         if (data.indexOf("# STOCKHOLM") > -1)
178         {
179           reply = FileFormat.Stockholm;
180           break;
181         }
182         if (data.indexOf("_ENTRY.ID") > -1
183                 || data.indexOf("_AUDIT_AUTHOR.NAME") > -1
184                 || data.indexOf("_ATOM_SITE.") > -1)
185         {
186           reply = FileFormat.MMCif;
187           break;
188         }
189         // if (data.indexOf(">") > -1)
190         if (data.startsWith(">"))
191         {
192           // FASTA, PIR file or BLC file
193           boolean checkPIR = false, starterm = false;
194           if ((data.indexOf(">P1;") > -1) || (data.indexOf(">DL;") > -1))
195           {
196             // watch for PIR file attributes
197             checkPIR = true;
198             reply = FileFormat.PIR;
199           }
200           // could also be BLC file, read next line to confirm
201           data = source.nextLine();
202
203           if (data.indexOf(">") > -1)
204           {
205             reply = FileFormat.BLC;
206           }
207           else
208           {
209             // Is this a single line BLC file?
210             String data1 = source.nextLine();
211             String data2 = source.nextLine();
212             int c1;
213             if (checkPIR)
214             {
215               starterm = (data1 != null && data1.indexOf("*") > -1)
216                       || (data2 != null && data2.indexOf("*") > -1);
217             }
218             if (data2 != null && (c1 = data.indexOf("*")) > -1)
219             {
220               if (c1 == 0 && c1 == data2.indexOf("*"))
221               {
222                 reply = FileFormat.BLC;
223               }
224               else
225               {
226                 reply = FileFormat.Fasta; // possibly a bad choice - may be
227                                           // recognised as
228                 // PIR
229               }
230               // otherwise can still possibly be a PIR file
231             }
232             else
233             {
234               reply = FileFormat.Fasta;
235               // TODO : AMSA File is indicated if there is annotation in the
236               // FASTA file - but FASTA will automatically generate this at the
237               // mo.
238               if (!checkPIR)
239               {
240                 break;
241               }
242             }
243           }
244           // final check for PIR content. require
245           // >P1;title\n<blah>\nterminated sequence to occur at least once.
246
247           // TODO the PIR/fasta ambiguity may be the use case that is needed to
248           // have
249           // a 'Parse as type XXX' parameter for the applet/application.
250           if (checkPIR)
251           {
252             String dta = null;
253             if (!starterm)
254             {
255               do
256               {
257                 try
258                 {
259                   dta = source.nextLine();
260                 } catch (IOException ex)
261                 {
262                 }
263                 if (dta != null && dta.indexOf("*") > -1)
264                 {
265                   starterm = true;
266                 }
267               } while (dta != null && !starterm);
268             }
269             if (starterm)
270             {
271               reply = FileFormat.PIR;
272               break;
273             }
274             else
275             {
276               reply = FileFormat.Fasta; // probably a bad choice!
277             }
278           }
279           // read as a FASTA (probably)
280           break;
281         }
282         int lessThan = data.indexOf("<");
283         if ((lessThan > -1)) // possible Markup Language data i.e HTML,
284                              // RNAML, XML
285         {
286           String upper = data.toUpperCase();
287           if (upper.substring(lessThan).startsWith("<HTML"))
288           {
289             reply = FileFormat.Html;
290             break;
291           }
292           if (upper.substring(lessThan).startsWith("<RNAML"))
293           {
294             reply = FileFormat.Rnaml;
295             break;
296           }
297         }
298
299         if (data.indexOf("{\"") > -1)
300         {
301           reply = FileFormat.Json;
302           break;
303         }
304         if ((data.length() < 1) || (data.indexOf("#") == 0))
305         {
306           lineswereskipped = true;
307           continue;
308         }
309
310         if (data.indexOf("PILEUP") > -1)
311         {
312           reply = FileFormat.Pileup;
313
314           break;
315         }
316
317         if ((data.indexOf("//") == 0)
318                 || ((data.indexOf("!!") > -1) && (data.indexOf("!!") < data
319                         .indexOf("_MULTIPLE_ALIGNMENT "))))
320         {
321           reply = FileFormat.MSF;
322
323           break;
324         }
325         else if (data.indexOf("CLUSTAL") > -1)
326         {
327           reply = FileFormat.Clustal;
328
329           break;
330         }
331
332         else if (data.indexOf("HEADER") == 0 || data.indexOf("ATOM") == 0)
333         {
334           reply = FileFormat.PDB;
335           break;
336         }
337         else if (data.matches("\\s*\\d+\\s+\\d+\\s*"))
338         {
339           reply = FileFormat.Phylip;
340           break;
341         }
342         else
343         {
344           if (!lineswereskipped && looksLikeJnetData(data))
345           {
346             reply = FileFormat.Jnet;
347             break;
348           }
349         }
350
351         lineswereskipped = true; // this means there was some junk before any
352         // key file signature
353       }
354       if (closeSource)
355       {
356         source.close();
357       }
358       else
359       {
360         source.reset(bytesRead); // so the file can be parsed from the mark
361       }
362     } catch (Exception ex)
363     {
364       System.err.println("File Identification failed!\n" + ex);
365       throw new FileFormatException(source.errormessage);
366     }
367     if (trimmedLength == 0)
368     {
369       System.err
370               .println("File Identification failed! - Empty file was read.");
371       throw new FileFormatException("EMPTY DATA FILE");
372     }
373     System.out.println("File format identified as " + reply.toString());
374     return reply;
375   }
376
377   /**
378    * Returns true if the data appears to be Jnet concise annotation format
379    * 
380    * @param data
381    * @return
382    */
383   protected boolean looksLikeJnetData(String data)
384   {
385     char firstChar = data.charAt(0);
386     int colonPos = data.indexOf(":");
387     int commaPos = data.indexOf(",");
388     boolean isJnet = firstChar != '*' && firstChar != ' ' && colonPos > -1
389             && commaPos > -1 && colonPos < commaPos;
390     // && data.indexOf(",")<data.indexOf(",", data.indexOf(","))) / ??
391     return isJnet;
392   }
393
394   /**
395    * Returns true if the data has at least 6 tab-delimited fields _and_ fields 4
396    * and 5 are integer (start/end)
397    * 
398    * @param data
399    * @return
400    */
401   protected boolean looksLikeFeatureData(String data)
402   {
403     if (data == null)
404     {
405       return false;
406     }
407     String[] columns = data.split("\t");
408     if (columns.length < 6)
409     {
410       return false;
411     }
412     for (int col = 3; col < 5; col++)
413     {
414       try
415       {
416         Integer.parseInt(columns[col]);
417       } catch (NumberFormatException e)
418       {
419         return false;
420       }
421     }
422     return true;
423   }
424
425   public static void main(String[] args)
426   {
427     for (int i = 0; args != null && i < args.length; i++)
428     {
429       IdentifyFile ider = new IdentifyFile();
430       FileFormatI type = null;
431       try
432       {
433         type = ider.identify(args[i], DataSourceType.FILE);
434       } catch (FileFormatException e)
435       {
436         System.err.println(String.format(
437                 "Error '%s' identifying file type for %s", args[i],
438                 e.getMessage()));
439       }
440       System.out.println("Type of " + args[i] + " is " + type);
441     }
442     if (args == null || args.length == 0)
443     {
444       System.err.println("Usage: <Filename> [<Filename> ...]");
445     }
446   }
447 }