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