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