added todo regarding import of GFF2 key=value attributes
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*\r
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)\r
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle\r
4  * \r
5  * This program is free software; you can redistribute it and/or\r
6  * modify it under the terms of the GNU General Public License\r
7  * as published by the Free Software Foundation; either version 2\r
8  * of the License, or (at your option) any later version.\r
9  * \r
10  * This program is distributed in the hope that it will be useful,\r
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
13  * GNU General Public License for more details.\r
14  * \r
15  * You should have received a copy of the GNU General Public License\r
16  * along with this program; if not, write to the Free Software\r
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\r
18  */\r
19 package jalview.io;\r
20 \r
21 import java.io.*;\r
22 import java.util.*;\r
23 \r
24 import jalview.datamodel.*;\r
25 import jalview.schemes.*;\r
26 \r
27 /**\r
28  * Parse and create Jalview Features files Detects GFF format features files and\r
29  * parses. Does not implement standard print() - call specific printFeatures or\r
30  * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object\r
31  * for the features annotation - this normally works on an exact match.\r
32  * \r
33  * @author AMW\r
34  * @version $Revision$\r
35  */\r
36 public class FeaturesFile extends AlignFile\r
37 {\r
38   /**\r
39    * Creates a new FeaturesFile object.\r
40    */\r
41   public FeaturesFile()\r
42   {\r
43   }\r
44 \r
45   /**\r
46    * Creates a new FeaturesFile object.\r
47    * \r
48    * @param inFile\r
49    *                DOCUMENT ME!\r
50    * @param type\r
51    *                DOCUMENT ME!\r
52    * \r
53    * @throws IOException\r
54    *                 DOCUMENT ME!\r
55    */\r
56   public FeaturesFile(String inFile, String type) throws IOException\r
57   {\r
58     super(inFile, type);\r
59   }\r
60 \r
61   public FeaturesFile(FileParse source) throws IOException\r
62   {\r
63     super(source);\r
64   }\r
65 \r
66   /**\r
67    * The Application can render HTML, but the applet will remove HTML tags and\r
68    * replace links with %LINK% Both need to read links in HTML however\r
69    * \r
70    * @throws IOException\r
71    *                 DOCUMENT ME!\r
72    */\r
73   public boolean parse(AlignmentI align, Hashtable colours,\r
74           boolean removeHTML)\r
75   {\r
76     return parse(align, colours, null, removeHTML);\r
77   }\r
78 \r
79   /**\r
80    * The Application can render HTML, but the applet will remove HTML tags and\r
81    * replace links with %LINK% Both need to read links in HTML however\r
82    * \r
83    * @throws IOException\r
84    *                 DOCUMENT ME!\r
85    */\r
86   public boolean parse(AlignmentI align, Hashtable colours,\r
87           Hashtable featureLink, boolean removeHTML)\r
88   {\r
89     String line = null;\r
90     try\r
91     {\r
92       SequenceI seq = null;\r
93       String type, desc, token = null;\r
94 \r
95       int index, start, end;\r
96       float score;\r
97       StringTokenizer st;\r
98       SequenceFeature sf;\r
99       String featureGroup = null, groupLink = null;\r
100       Hashtable typeLink = new Hashtable();\r
101 \r
102       boolean GFFFile = true;\r
103 \r
104       while ((line = nextLine()) != null)\r
105       {\r
106         if (line.startsWith("#"))\r
107         {\r
108           continue;\r
109         }\r
110 \r
111         st = new StringTokenizer(line, "\t");\r
112         if (st.countTokens() > 1 && st.countTokens() < 4)\r
113         {\r
114           GFFFile = false;\r
115           type = st.nextToken();\r
116           if (type.equalsIgnoreCase("startgroup"))\r
117           {\r
118             featureGroup = st.nextToken();\r
119             if (st.hasMoreElements())\r
120             {\r
121               groupLink = st.nextToken();\r
122               featureLink.put(featureGroup, groupLink);\r
123             }\r
124           }\r
125           else if (type.equalsIgnoreCase("endgroup"))\r
126           {\r
127             // We should check whether this is the current group,\r
128             // but at present theres no way of showing more than 1 group\r
129             st.nextToken();\r
130             featureGroup = null;\r
131             groupLink = null;\r
132           }\r
133           else\r
134           {\r
135             UserColourScheme ucs = new UserColourScheme(st.nextToken());\r
136             colours.put(type, ucs.findColour('A'));\r
137             if (st.hasMoreElements())\r
138             {\r
139               String link = st.nextToken();\r
140               typeLink.put(type, link);\r
141               if (featureLink == null)\r
142               {\r
143                 featureLink = new Hashtable();\r
144               }\r
145               featureLink.put(type, link);\r
146             }\r
147 \r
148           }\r
149           continue;\r
150         }\r
151         String seqId = "";\r
152         while (st.hasMoreElements())\r
153         {\r
154 \r
155           if (GFFFile)\r
156           {\r
157             // Still possible this is an old Jalview file,\r
158             // which does not have type colours at the beginning\r
159             seqId = token = st.nextToken();\r
160             seq = align.findName(seqId, true);\r
161             if (seq != null)\r
162             {\r
163               desc = st.nextToken();\r
164               type = st.nextToken();\r
165               try\r
166               {\r
167                 start = Integer.parseInt(st.nextToken());\r
168               } catch (NumberFormatException ex)\r
169               {\r
170                 start = 0;\r
171               }\r
172               try\r
173               {\r
174                 end = Integer.parseInt(st.nextToken());\r
175               } catch (NumberFormatException ex)\r
176               {\r
177                 end = -1;\r
178               }\r
179               try\r
180               {\r
181                 score = new Float(st.nextToken()).floatValue();\r
182               } catch (NumberFormatException ex)\r
183               {\r
184                 score = 0;\r
185               }\r
186 \r
187               sf = new SequenceFeature(type, desc, start, end, score, null);\r
188 \r
189               try\r
190               {\r
191                 sf.setValue("STRAND", st.nextToken());\r
192                 sf.setValue("FRAME", st.nextToken());\r
193               } catch (Exception ex)\r
194               {\r
195               }\r
196 \r
197               if (st.hasMoreTokens())\r
198               {\r
199                 StringBuffer attributes = new StringBuffer();\r
200                 while (st.hasMoreTokens())\r
201                 {\r
202                   attributes.append("\t" + st.nextElement());\r
203                 }\r
204                 // TODO validate and split GFF2 attributes field ? parse out ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as sf.setValue(attrib, val); \r
205                 sf.setValue("ATTRIBUTES", attributes.toString());\r
206               }\r
207 \r
208               seq.addSequenceFeature(sf);\r
209               while ((seq = align.findName(seq, seqId, true)) != null)\r
210               {\r
211                 seq.addSequenceFeature(new SequenceFeature(sf));\r
212               }\r
213               break;\r
214             }\r
215           }\r
216 \r
217           if (GFFFile && seq == null)\r
218           {\r
219             desc = token;\r
220           }\r
221           else\r
222           {\r
223             desc = st.nextToken();\r
224           }\r
225           if (!st.hasMoreTokens())\r
226           {\r
227             System.err\r
228                     .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");\r
229             // in all probability, this isn't a file we understand, so bail\r
230             // quietly.\r
231             return false;\r
232           }\r
233 \r
234           token = st.nextToken();\r
235 \r
236           if (!token.equals("ID_NOT_SPECIFIED"))\r
237           {\r
238             seq = align.findName(seqId = token, true);\r
239             st.nextToken();\r
240           }\r
241           else\r
242           {\r
243             seqId = null;\r
244             try\r
245             {\r
246               index = Integer.parseInt(st.nextToken());\r
247               seq = align.getSequenceAt(index);\r
248             } catch (NumberFormatException ex)\r
249             {\r
250               seq = null;\r
251             }\r
252           }\r
253 \r
254           if (seq == null)\r
255           {\r
256             System.out.println("Sequence not found: " + line);\r
257             break;\r
258           }\r
259 \r
260           start = Integer.parseInt(st.nextToken());\r
261           end = Integer.parseInt(st.nextToken());\r
262 \r
263           type = st.nextToken();\r
264 \r
265           if (!colours.containsKey(type))\r
266           {\r
267             // Probably the old style groups file\r
268             UserColourScheme ucs = new UserColourScheme(type);\r
269             colours.put(type, ucs.findColour('A'));\r
270           }\r
271 \r
272           sf = new SequenceFeature(type, desc, "", start, end, featureGroup);\r
273 \r
274           if (groupLink != null && removeHTML)\r
275           {\r
276             sf.addLink(groupLink);\r
277             sf.description += "%LINK%";\r
278           }\r
279           if (typeLink.containsKey(type) && removeHTML)\r
280           {\r
281             sf.addLink(typeLink.get(type).toString());\r
282             sf.description += "%LINK%";\r
283           }\r
284 \r
285           parseDescriptionHTML(sf, removeHTML);\r
286 \r
287           seq.addSequenceFeature(sf);\r
288 \r
289           while (seqId != null\r
290                   && (seq = align.findName(seq, seqId, false)) != null)\r
291           {\r
292             seq.addSequenceFeature(new SequenceFeature(sf));\r
293           }\r
294           // If we got here, its not a GFFFile\r
295           GFFFile = false;\r
296         }\r
297       }\r
298     } catch (Exception ex)\r
299     {\r
300       System.out.println(line);\r
301       System.out.println("Error parsing feature file: " + ex + "\n" + line);\r
302       ex.printStackTrace(System.err);\r
303       return false;\r
304     }\r
305 \r
306     return true;\r
307   }\r
308 \r
309   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)\r
310   {\r
311     if (sf.getDescription() == null)\r
312     {\r
313       return;\r
314     }\r
315 \r
316     if (removeHTML\r
317             && sf.getDescription().toUpperCase().indexOf("<HTML>") == -1)\r
318     {\r
319       removeHTML = false;\r
320     }\r
321 \r
322     StringBuffer sb = new StringBuffer();\r
323     StringTokenizer st = new StringTokenizer(sf.getDescription(), "<");\r
324     String token, link;\r
325     int startTag;\r
326     String tag = null;\r
327     while (st.hasMoreElements())\r
328     {\r
329       token = st.nextToken("&>");\r
330       if (token.equalsIgnoreCase("html") || token.startsWith("/"))\r
331       {\r
332         continue;\r
333       }\r
334 \r
335       tag = null;\r
336       startTag = token.indexOf("<");\r
337 \r
338       if (startTag > -1)\r
339       {\r
340         tag = token.substring(startTag + 1);\r
341         token = token.substring(0, startTag);\r
342       }\r
343 \r
344       if (tag != null && tag.toUpperCase().startsWith("A HREF="))\r
345       {\r
346         if (token.length() > 0)\r
347         {\r
348           sb.append(token);\r
349         }\r
350         link = tag.substring(tag.indexOf("\"") + 1, tag.length() - 1);\r
351         String label = st.nextToken("<>");\r
352         sf.addLink(label + "|" + link);\r
353         sb.append(label + "%LINK%");\r
354       }\r
355       else if (tag != null && tag.equalsIgnoreCase("br"))\r
356       {\r
357         sb.append("\n");\r
358       }\r
359       else if (token.startsWith("lt;"))\r
360       {\r
361         sb.append("<" + token.substring(3));\r
362       }\r
363       else if (token.startsWith("gt;"))\r
364       {\r
365         sb.append(">" + token.substring(3));\r
366       }\r
367       else if (token.startsWith("amp;"))\r
368       {\r
369         sb.append("&" + token.substring(4));\r
370       }\r
371       else\r
372       {\r
373         sb.append(token);\r
374       }\r
375     }\r
376 \r
377     if (removeHTML)\r
378     {\r
379       sf.description = sb.toString();\r
380     }\r
381 \r
382   }\r
383 \r
384   /**\r
385    * generate a features file for seqs\r
386    * \r
387    * @param seqs\r
388    *                source of sequence features\r
389    * @param visible\r
390    *                hash of feature types and colours\r
391    * @return features file contents\r
392    */\r
393   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)\r
394   {\r
395     return printJalviewFormat(seqs, visible, true);\r
396   }\r
397 \r
398   /**\r
399    * generate a features file for seqs with colours from visible (if any)\r
400    * \r
401    * @param seqs\r
402    *                source of features\r
403    * @param visible\r
404    *                hash of Colours for each feature type\r
405    * @param visOnly\r
406    *                when true only feature types in 'visible' will be output\r
407    * @return features file contents\r
408    */\r
409   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,\r
410           boolean visOnly)\r
411   {\r
412     StringBuffer out = new StringBuffer();\r
413     SequenceFeature[] next;\r
414 \r
415     if (visOnly && (visible == null || visible.size() < 1))\r
416     {\r
417       return "No Features Visible";\r
418     }\r
419     if (visible != null && visOnly)\r
420     {\r
421       // write feature colours only if we're given them and we are generating\r
422       // viewed features\r
423       Enumeration en = visible.keys();\r
424       String type;\r
425       int color;\r
426       while (en.hasMoreElements())\r
427       {\r
428         type = en.nextElement().toString();\r
429         color = Integer.parseInt(visible.get(type).toString());\r
430         out.append(type\r
431                 + "\t"\r
432                 + jalview.util.Format\r
433                         .getHexString(new java.awt.Color(color)) + "\n");\r
434       }\r
435     }\r
436     // Work out which groups are both present and visible\r
437     Vector groups = new Vector();\r
438     int groupIndex = 0;\r
439 \r
440     for (int i = 0; i < seqs.length; i++)\r
441     {\r
442       next = seqs[i].getSequenceFeatures();\r
443       if (next != null)\r
444       {\r
445         for (int j = 0; j < next.length; j++)\r
446         {\r
447           if (visOnly && !visible.containsKey(next[j].type))\r
448           {\r
449             continue;\r
450           }\r
451 \r
452           if (next[j].featureGroup != null\r
453                   && !groups.contains(next[j].featureGroup))\r
454           {\r
455             groups.addElement(next[j].featureGroup);\r
456           }\r
457         }\r
458       }\r
459     }\r
460 \r
461     String group = null;\r
462 \r
463     do\r
464     {\r
465 \r
466       if (groups.size() > 0 && groupIndex < groups.size())\r
467       {\r
468         group = groups.elementAt(groupIndex).toString();\r
469         out.append("\nSTARTGROUP\t" + group + "\n");\r
470       }\r
471       else\r
472       {\r
473         group = null;\r
474       }\r
475 \r
476       for (int i = 0; i < seqs.length; i++)\r
477       {\r
478         next = seqs[i].getSequenceFeatures();\r
479         if (next != null)\r
480         {\r
481           for (int j = 0; j < next.length; j++)\r
482           {\r
483             if (visOnly && !visible.containsKey(next[j].type))\r
484             {\r
485               continue;\r
486             }\r
487 \r
488             if (group != null\r
489                     && (next[j].featureGroup == null || !next[j].featureGroup\r
490                             .equals(group)))\r
491             {\r
492               continue;\r
493             }\r
494 \r
495             if (group == null && next[j].featureGroup != null)\r
496             {\r
497               continue;\r
498             }\r
499 \r
500             if (next[j].description == null\r
501                     || next[j].description.equals(""))\r
502             {\r
503               out.append(next[j].type + "\t");\r
504             }\r
505             else\r
506             {\r
507               if (next[j].links != null\r
508                       && next[j].getDescription().indexOf("<html>") == -1)\r
509               {\r
510                 out.append("<html>");\r
511               }\r
512 \r
513               out.append(next[j].description + " ");\r
514               if (next[j].links != null)\r
515               {\r
516                 for (int l = 0; l < next[j].links.size(); l++)\r
517                 {\r
518                   String label = next[j].links.elementAt(l).toString();\r
519                   String href = label.substring(label.indexOf("|") + 1);\r
520                   label = label.substring(0, label.indexOf("|"));\r
521 \r
522                   if (next[j].description.indexOf(href) == -1)\r
523                   {\r
524                     out\r
525                             .append("<a href=\"" + href + "\">" + label\r
526                                     + "</a>");\r
527                   }\r
528                 }\r
529 \r
530                 if (next[j].getDescription().indexOf("</html>") == -1)\r
531                 {\r
532                   out.append("</html>");\r
533                 }\r
534               }\r
535 \r
536               out.append("\t");\r
537             }\r
538 \r
539             out.append(seqs[i].getName() + "\t-1\t" + next[j].begin + "\t"\r
540                     + next[j].end + "\t" + next[j].type + "\n");\r
541           }\r
542         }\r
543       }\r
544 \r
545       if (group != null)\r
546       {\r
547         out.append("ENDGROUP\t" + group + "\n");\r
548         groupIndex++;\r
549       }\r
550       else\r
551       {\r
552         break;\r
553       }\r
554 \r
555     } while (groupIndex < groups.size() + 1);\r
556 \r
557     return out.toString();\r
558   }\r
559 \r
560   public String printGFFFormat(SequenceI[] seqs, Hashtable visible)\r
561   {\r
562     return printGFFFormat(seqs, visible, true);\r
563   }\r
564 \r
565   public String printGFFFormat(SequenceI[] seqs, Hashtable visible,\r
566           boolean visOnly)\r
567   {\r
568     StringBuffer out = new StringBuffer();\r
569     SequenceFeature[] next;\r
570     String source;\r
571 \r
572     for (int i = 0; i < seqs.length; i++)\r
573     {\r
574       if (seqs[i].getSequenceFeatures() != null)\r
575       {\r
576         next = seqs[i].getSequenceFeatures();\r
577         for (int j = 0; j < next.length; j++)\r
578         {\r
579           if (visOnly && !visible.containsKey(next[j].type))\r
580           {\r
581             continue;\r
582           }\r
583 \r
584           source = next[j].featureGroup;\r
585           if (source == null)\r
586           {\r
587             source = next[j].getDescription();\r
588           }\r
589 \r
590           out.append(seqs[i].getName() + "\t" + source + "\t"\r
591                   + next[j].type + "\t" + next[j].begin + "\t"\r
592                   + next[j].end + "\t" + next[j].score + "\t");\r
593 \r
594           if (next[j].getValue("STRAND") != null)\r
595           {\r
596             out.append(next[j].getValue("STRAND") + "\t");\r
597           }\r
598           else\r
599           {\r
600             out.append(".\t");\r
601           }\r
602 \r
603           if (next[j].getValue("FRAME") != null)\r
604           {\r
605             out.append(next[j].getValue("FRAME"));\r
606           }\r
607           else\r
608           {\r
609             out.append(".");\r
610           }\r
611 \r
612           if (next[j].getValue("ATTRIBUTES") != null)\r
613           {\r
614             out.append(next[j].getValue("ATTRIBUTES"));\r
615           }\r
616 \r
617           out.append("\n");\r
618 \r
619         }\r
620       }\r
621     }\r
622 \r
623     return out.toString();\r
624   }\r
625 \r
626   /**\r
627    * this is only for the benefit of object polymorphism - method does nothing.\r
628    */\r
629   public void parse()\r
630   {\r
631     // IGNORED\r
632   }\r
633 \r
634   /**\r
635    * this is only for the benefit of object polymorphism - method does nothing.\r
636    * \r
637    * @return error message\r
638    */\r
639   public String print()\r
640   {\r
641     return "USE printGFFFormat() or printJalviewFormat()";\r
642   }\r
643 }\r