merge from 2_4_Release branch
[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                 sf.setValue("ATTRIBUTES", attributes.toString());\r
205               }\r
206 \r
207               seq.addSequenceFeature(sf);\r
208               while ((seq = align.findName(seq, seqId, true)) != null)\r
209               {\r
210                 seq.addSequenceFeature(new SequenceFeature(sf));\r
211               }\r
212               break;\r
213             }\r
214           }\r
215 \r
216           if (GFFFile && seq == null)\r
217           {\r
218             desc = token;\r
219           }\r
220           else\r
221           {\r
222             desc = st.nextToken();\r
223           }\r
224           if (!st.hasMoreTokens())\r
225           {\r
226             System.err\r
227                     .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");\r
228             // in all probability, this isn't a file we understand, so bail\r
229             // quietly.\r
230             return false;\r
231           }\r
232 \r
233           token = st.nextToken();\r
234 \r
235           if (!token.equals("ID_NOT_SPECIFIED"))\r
236           {\r
237             seq = align.findName(seqId = token, true);\r
238             st.nextToken();\r
239           }\r
240           else\r
241           {\r
242             seqId = null;\r
243             try\r
244             {\r
245               index = Integer.parseInt(st.nextToken());\r
246               seq = align.getSequenceAt(index);\r
247             } catch (NumberFormatException ex)\r
248             {\r
249               seq = null;\r
250             }\r
251           }\r
252 \r
253           if (seq == null)\r
254           {\r
255             System.out.println("Sequence not found: " + line);\r
256             break;\r
257           }\r
258 \r
259           start = Integer.parseInt(st.nextToken());\r
260           end = Integer.parseInt(st.nextToken());\r
261 \r
262           type = st.nextToken();\r
263 \r
264           if (!colours.containsKey(type))\r
265           {\r
266             // Probably the old style groups file\r
267             UserColourScheme ucs = new UserColourScheme(type);\r
268             colours.put(type, ucs.findColour('A'));\r
269           }\r
270 \r
271           sf = new SequenceFeature(type, desc, "", start, end, featureGroup);\r
272 \r
273           if (groupLink != null && removeHTML)\r
274           {\r
275             sf.addLink(groupLink);\r
276             sf.description += "%LINK%";\r
277           }\r
278           if (typeLink.containsKey(type) && removeHTML)\r
279           {\r
280             sf.addLink(typeLink.get(type).toString());\r
281             sf.description += "%LINK%";\r
282           }\r
283 \r
284           parseDescriptionHTML(sf, removeHTML);\r
285 \r
286           seq.addSequenceFeature(sf);\r
287 \r
288           while (seqId != null\r
289                   && (seq = align.findName(seq, seqId, false)) != null)\r
290           {\r
291             seq.addSequenceFeature(new SequenceFeature(sf));\r
292           }\r
293           // If we got here, its not a GFFFile\r
294           GFFFile = false;\r
295         }\r
296       }\r
297     } catch (Exception ex)\r
298     {\r
299       System.out.println(line);\r
300       System.out.println("Error parsing feature file: " + ex + "\n" + line);\r
301       ex.printStackTrace(System.err);\r
302       return false;\r
303     }\r
304 \r
305     return true;\r
306   }\r
307 \r
308   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)\r
309   {\r
310     if (sf.getDescription() == null)\r
311     {\r
312       return;\r
313     }\r
314 \r
315     if (removeHTML\r
316             && sf.getDescription().toUpperCase().indexOf("<HTML>") == -1)\r
317     {\r
318       removeHTML = false;\r
319     }\r
320 \r
321     StringBuffer sb = new StringBuffer();\r
322     StringTokenizer st = new StringTokenizer(sf.getDescription(), "<");\r
323     String token, link;\r
324     int startTag;\r
325     String tag = null;\r
326     while (st.hasMoreElements())\r
327     {\r
328       token = st.nextToken("&>");\r
329       if (token.equalsIgnoreCase("html") || token.startsWith("/"))\r
330       {\r
331         continue;\r
332       }\r
333 \r
334       tag = null;\r
335       startTag = token.indexOf("<");\r
336 \r
337       if (startTag > -1)\r
338       {\r
339         tag = token.substring(startTag + 1);\r
340         token = token.substring(0, startTag);\r
341       }\r
342 \r
343       if (tag != null && tag.toUpperCase().startsWith("A HREF="))\r
344       {\r
345         if (token.length() > 0)\r
346         {\r
347           sb.append(token);\r
348         }\r
349         link = tag.substring(tag.indexOf("\"") + 1, tag.length() - 1);\r
350         String label = st.nextToken("<>");\r
351         sf.addLink(label + "|" + link);\r
352         sb.append(label + "%LINK%");\r
353       }\r
354       else if (tag != null && tag.equalsIgnoreCase("br"))\r
355       {\r
356         sb.append("\n");\r
357       }\r
358       else if (token.startsWith("lt;"))\r
359       {\r
360         sb.append("<" + token.substring(3));\r
361       }\r
362       else if (token.startsWith("gt;"))\r
363       {\r
364         sb.append(">" + token.substring(3));\r
365       }\r
366       else if (token.startsWith("amp;"))\r
367       {\r
368         sb.append("&" + token.substring(4));\r
369       }\r
370       else\r
371       {\r
372         sb.append(token);\r
373       }\r
374     }\r
375 \r
376     if (removeHTML)\r
377     {\r
378       sf.description = sb.toString();\r
379     }\r
380 \r
381   }\r
382 \r
383   /**\r
384    * generate a features file for seqs\r
385    * \r
386    * @param seqs\r
387    *                source of sequence features\r
388    * @param visible\r
389    *                hash of feature types and colours\r
390    * @return features file contents\r
391    */\r
392   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)\r
393   {\r
394     return printJalviewFormat(seqs, visible, true);\r
395   }\r
396 \r
397   /**\r
398    * generate a features file for seqs with colours from visible (if any)\r
399    * \r
400    * @param seqs\r
401    *                source of features\r
402    * @param visible\r
403    *                hash of Colours for each feature type\r
404    * @param visOnly\r
405    *                when true only feature types in 'visible' will be output\r
406    * @return features file contents\r
407    */\r
408   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,\r
409           boolean visOnly)\r
410   {\r
411     StringBuffer out = new StringBuffer();\r
412     SequenceFeature[] next;\r
413 \r
414     if (visOnly && (visible == null || visible.size() < 1))\r
415     {\r
416       return "No Features Visible";\r
417     }\r
418     if (visible != null && visOnly)\r
419     {\r
420       // write feature colours only if we're given them and we are generating\r
421       // viewed features\r
422       Enumeration en = visible.keys();\r
423       String type;\r
424       int color;\r
425       while (en.hasMoreElements())\r
426       {\r
427         type = en.nextElement().toString();\r
428         color = Integer.parseInt(visible.get(type).toString());\r
429         out.append(type\r
430                 + "\t"\r
431                 + jalview.util.Format\r
432                         .getHexString(new java.awt.Color(color)) + "\n");\r
433       }\r
434     }\r
435     // Work out which groups are both present and visible\r
436     Vector groups = new Vector();\r
437     int groupIndex = 0;\r
438 \r
439     for (int i = 0; i < seqs.length; i++)\r
440     {\r
441       next = seqs[i].getSequenceFeatures();\r
442       if (next != null)\r
443       {\r
444         for (int j = 0; j < next.length; j++)\r
445         {\r
446           if (visOnly && !visible.containsKey(next[j].type))\r
447           {\r
448             continue;\r
449           }\r
450 \r
451           if (next[j].featureGroup != null\r
452                   && !groups.contains(next[j].featureGroup))\r
453           {\r
454             groups.addElement(next[j].featureGroup);\r
455           }\r
456         }\r
457       }\r
458     }\r
459 \r
460     String group = null;\r
461 \r
462     do\r
463     {\r
464 \r
465       if (groups.size() > 0 && groupIndex < groups.size())\r
466       {\r
467         group = groups.elementAt(groupIndex).toString();\r
468         out.append("\nSTARTGROUP\t" + group + "\n");\r
469       }\r
470       else\r
471       {\r
472         group = null;\r
473       }\r
474 \r
475       for (int i = 0; i < seqs.length; i++)\r
476       {\r
477         next = seqs[i].getSequenceFeatures();\r
478         if (next != null)\r
479         {\r
480           for (int j = 0; j < next.length; j++)\r
481           {\r
482             if (visOnly && !visible.containsKey(next[j].type))\r
483             {\r
484               continue;\r
485             }\r
486 \r
487             if (group != null\r
488                     && (next[j].featureGroup == null || !next[j].featureGroup\r
489                             .equals(group)))\r
490             {\r
491               continue;\r
492             }\r
493 \r
494             if (group == null && next[j].featureGroup != null)\r
495             {\r
496               continue;\r
497             }\r
498 \r
499             if (next[j].description == null\r
500                     || next[j].description.equals(""))\r
501             {\r
502               out.append(next[j].type + "\t");\r
503             }\r
504             else\r
505             {\r
506               if (next[j].links != null\r
507                       && next[j].getDescription().indexOf("<html>") == -1)\r
508               {\r
509                 out.append("<html>");\r
510               }\r
511 \r
512               out.append(next[j].description + " ");\r
513               if (next[j].links != null)\r
514               {\r
515                 for (int l = 0; l < next[j].links.size(); l++)\r
516                 {\r
517                   String label = next[j].links.elementAt(l).toString();\r
518                   String href = label.substring(label.indexOf("|") + 1);\r
519                   label = label.substring(0, label.indexOf("|"));\r
520 \r
521                   if (next[j].description.indexOf(href) == -1)\r
522                   {\r
523                     out\r
524                             .append("<a href=\"" + href + "\">" + label\r
525                                     + "</a>");\r
526                   }\r
527                 }\r
528 \r
529                 if (next[j].getDescription().indexOf("</html>") == -1)\r
530                 {\r
531                   out.append("</html>");\r
532                 }\r
533               }\r
534 \r
535               out.append("\t");\r
536             }\r
537 \r
538             out.append(seqs[i].getName() + "\t-1\t" + next[j].begin + "\t"\r
539                     + next[j].end + "\t" + next[j].type + "\n");\r
540           }\r
541         }\r
542       }\r
543 \r
544       if (group != null)\r
545       {\r
546         out.append("ENDGROUP\t" + group + "\n");\r
547         groupIndex++;\r
548       }\r
549       else\r
550       {\r
551         break;\r
552       }\r
553 \r
554     } while (groupIndex < groups.size() + 1);\r
555 \r
556     return out.toString();\r
557   }\r
558 \r
559   public String printGFFFormat(SequenceI[] seqs, Hashtable visible)\r
560   {\r
561     return printGFFFormat(seqs, visible, true);\r
562   }\r
563 \r
564   public String printGFFFormat(SequenceI[] seqs, Hashtable visible,\r
565           boolean visOnly)\r
566   {\r
567     StringBuffer out = new StringBuffer();\r
568     SequenceFeature[] next;\r
569     String source;\r
570 \r
571     for (int i = 0; i < seqs.length; i++)\r
572     {\r
573       if (seqs[i].getSequenceFeatures() != null)\r
574       {\r
575         next = seqs[i].getSequenceFeatures();\r
576         for (int j = 0; j < next.length; j++)\r
577         {\r
578           if (visOnly && !visible.containsKey(next[j].type))\r
579           {\r
580             continue;\r
581           }\r
582 \r
583           source = next[j].featureGroup;\r
584           if (source == null)\r
585           {\r
586             source = next[j].getDescription();\r
587           }\r
588 \r
589           out.append(seqs[i].getName() + "\t" + source + "\t"\r
590                   + next[j].type + "\t" + next[j].begin + "\t"\r
591                   + next[j].end + "\t" + next[j].score + "\t");\r
592 \r
593           if (next[j].getValue("STRAND") != null)\r
594           {\r
595             out.append(next[j].getValue("STRAND") + "\t");\r
596           }\r
597           else\r
598           {\r
599             out.append(".\t");\r
600           }\r
601 \r
602           if (next[j].getValue("FRAME") != null)\r
603           {\r
604             out.append(next[j].getValue("FRAME"));\r
605           }\r
606           else\r
607           {\r
608             out.append(".");\r
609           }\r
610 \r
611           if (next[j].getValue("ATTRIBUTES") != null)\r
612           {\r
613             out.append(next[j].getValue("ATTRIBUTES"));\r
614           }\r
615 \r
616           out.append("\n");\r
617 \r
618         }\r
619       }\r
620     }\r
621 \r
622     return out.toString();\r
623   }\r
624 \r
625   /**\r
626    * this is only for the benefit of object polymorphism - method does nothing.\r
627    */\r
628   public void parse()\r
629   {\r
630     // IGNORED\r
631   }\r
632 \r
633   /**\r
634    * this is only for the benefit of object polymorphism - method does nothing.\r
635    * \r
636    * @return error message\r
637    */\r
638   public String print()\r
639   {\r
640     return "USE printGFFFormat() or printJalviewFormat()";\r
641   }\r
642 }\r