formatting and error report cleanup
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.io;
19
20 import java.io.*;
21 import java.util.*;
22
23 import javax.xml.parsers.ParserConfigurationException;
24
25 import org.xml.sax.SAXException;
26
27 import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
28 import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
29 import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
30 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
31
32 import jalview.analysis.SequenceIdMatcher;
33 import jalview.datamodel.*;
34 import jalview.schemes.*;
35 import jalview.util.Format;
36
37 /**
38  * Parse and create Jalview Features files Detects GFF format features files and
39  * parses. Does not implement standard print() - call specific printFeatures or
40  * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
41  * for the features annotation - this normally works on an exact match.
42  * 
43  * @author AMW
44  * @version $Revision$
45  */
46 public class FeaturesFile extends AlignFile
47 {
48   /**
49    * work around for GFF interpretation bug where source string becomes
50    * description rather than a group
51    */
52   private boolean doGffSource = true;
53
54   /**
55    * Creates a new FeaturesFile object.
56    */
57   public FeaturesFile()
58   {
59   }
60
61   /**
62    * Creates a new FeaturesFile object.
63    * 
64    * @param inFile
65    *          DOCUMENT ME!
66    * @param type
67    *          DOCUMENT ME!
68  * @throws Exception 
69    */
70   public FeaturesFile(String inFile, String type) throws Exception
71   {
72     super(inFile, type);
73   }
74
75   public FeaturesFile(FileParse source) throws Exception
76   {
77     super(source);
78   }
79
80   /**
81    * Parse GFF or sequence features file using case-independent matching,
82    * discarding URLs
83    * 
84    * @param align
85    *          - alignment/dataset containing sequences that are to be annotated
86    * @param colours
87    *          - hashtable to store feature colour definitions
88    * @param removeHTML
89    *          - process html strings into plain text
90    * @return true if features were added
91    */
92   public boolean parse(AlignmentI align, Hashtable colours,
93           boolean removeHTML)
94   {
95     return parse(align, colours, null, removeHTML, false);
96   }
97
98   /**
99    * Parse GFF or sequence features file optionally using case-independent
100    * matching, discarding URLs
101    * 
102    * @param align
103    *          - alignment/dataset containing sequences that are to be annotated
104    * @param colours
105    *          - hashtable to store feature colour definitions
106    * @param removeHTML
107    *          - process html strings into plain text
108    * @param relaxedIdmatching
109    *          - when true, ID matches to compound sequence IDs are allowed
110    * @return true if features were added
111    */
112   public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
113           boolean relaxedIdMatching)
114   {
115     return parse(align, colours, null, removeHTML, relaxedIdMatching);
116   }
117
118   /**
119    * Parse GFF or sequence features file optionally using case-independent
120    * matching
121    * 
122    * @param align
123    *          - alignment/dataset containing sequences that are to be annotated
124    * @param colours
125    *          - hashtable to store feature colour definitions
126    * @param featureLink
127    *          - hashtable to store associated URLs
128    * @param removeHTML
129    *          - process html strings into plain text
130    * @return true if features were added
131    */
132   public boolean parse(AlignmentI align, Map colours, Map featureLink,
133           boolean removeHTML)
134   {
135     return parse(align, colours, featureLink, removeHTML, false);
136   }
137
138   /**
139    * Parse GFF or sequence features file
140    * 
141    * @param align
142    *          - alignment/dataset containing sequences that are to be annotated
143    * @param colours
144    *          - hashtable to store feature colour definitions
145    * @param featureLink
146    *          - hashtable to store associated URLs
147    * @param removeHTML
148    *          - process html strings into plain text
149    * @param relaxedIdmatching
150    *          - when true, ID matches to compound sequence IDs are allowed
151    * @return true if features were added
152    */
153   public boolean parse(AlignmentI align, Map colours, Map featureLink,
154           boolean removeHTML, boolean relaxedIdmatching)
155   {
156
157     String line = null;
158     try
159     {
160       SequenceI seq = null;
161       String type, desc, token = null;
162
163       int index, start, end;
164       float score;
165       StringTokenizer st;
166       SequenceFeature sf;
167       String featureGroup = null, groupLink = null;
168       Map typeLink = new Hashtable();
169       /**
170        * when true, assume GFF style features rather than Jalview style.
171        */
172       boolean GFFFile = true;
173       while ((line = nextLine()) != null)
174       {
175         if (line.startsWith("#"))
176         {
177           continue;
178         }
179
180         st = new StringTokenizer(line, "\t");
181         if (st.countTokens() == 1)
182         {
183           if (line.trim().equalsIgnoreCase("GFF"))
184           {
185             // Start parsing file as if it might be GFF again.
186             GFFFile = true;
187             continue;
188           }
189         }
190         if (st.countTokens() > 1 && st.countTokens() < 4)
191         {
192           GFFFile = false;
193           type = st.nextToken();
194           if (type.equalsIgnoreCase("startgroup"))
195           {
196             featureGroup = st.nextToken();
197             if (st.hasMoreElements())
198             {
199               groupLink = st.nextToken();
200               featureLink.put(featureGroup, groupLink);
201             }
202           }
203           else if (type.equalsIgnoreCase("endgroup"))
204           {
205             // We should check whether this is the current group,
206             // but at present theres no way of showing more than 1 group
207             st.nextToken();
208             featureGroup = null;
209             groupLink = null;
210           }
211           else
212           {
213             Object colour = null;
214             String colscheme = st.nextToken();
215             if (colscheme.indexOf("|") > -1
216                     || colscheme.trim().equalsIgnoreCase("label"))
217             {
218               // Parse '|' separated graduated colourscheme fields:
219               // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
220               // can either provide 'label' only, first is optional, next two
221               // colors are required (but may be
222               // left blank), next is optional, nxt two min/max are required.
223               // first is either 'label'
224               // first/second and third are both hexadecimal or word equivalent
225               // colour.
226               // next two are values parsed as floats.
227               // fifth is either 'above','below', or 'none'.
228               // sixth is a float value and only required when fifth is either
229               // 'above' or 'below'.
230               StringTokenizer gcol = new StringTokenizer(colscheme, "|",
231                       true);
232               // set defaults
233               int threshtype = AnnotationColourGradient.NO_THRESHOLD;
234               float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
235               boolean labelCol = false;
236               // Parse spec line
237               String mincol = gcol.nextToken();
238               if (mincol == "|")
239               {
240                 System.err
241                         .println("Expected either 'label' or a colour specification in the line: "
242                                 + line);
243                 continue;
244               }
245               String maxcol = null;
246               if (mincol.toLowerCase().indexOf("label") == 0)
247               {
248                 labelCol = true;
249                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
250                                                                            // '|'
251                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
252               }
253               String abso = null, minval, maxval;
254               if (mincol != null)
255               {
256                 // at least four more tokens
257                 if (mincol.equals("|"))
258                 {
259                   mincol = "";
260                 }
261                 else
262                 {
263                   gcol.nextToken(); // skip next '|'
264                 }
265                 // continue parsing rest of line
266                 maxcol = gcol.nextToken();
267                 if (maxcol.equals("|"))
268                 {
269                   maxcol = "";
270                 }
271                 else
272                 {
273                   gcol.nextToken(); // skip next '|'
274                 }
275                 abso = gcol.nextToken();
276                 gcol.nextToken(); // skip next '|'
277                 if (abso.toLowerCase().indexOf("abso") != 0)
278                 {
279                   minval = abso;
280                   abso = null;
281                 }
282                 else
283                 {
284                   minval = gcol.nextToken();
285                   gcol.nextToken(); // skip next '|'
286                 }
287                 maxval = gcol.nextToken();
288                 if (gcol.hasMoreTokens())
289                 {
290                   gcol.nextToken(); // skip next '|'
291                 }
292                 try
293                 {
294                   if (minval.length() > 0)
295                   {
296                     min = new Float(minval).floatValue();
297                   }
298                 } catch (Exception e)
299                 {
300                   System.err
301                           .println("Couldn't parse the minimum value for graduated colour for type ("
302                                   + colscheme
303                                   + ") - did you misspell 'auto' for the optional automatic colour switch ?");
304                   e.printStackTrace();
305                 }
306                 try
307                 {
308                   if (maxval.length() > 0)
309                   {
310                     max = new Float(maxval).floatValue();
311                   }
312                 } catch (Exception e)
313                 {
314                   System.err
315                           .println("Couldn't parse the maximum value for graduated colour for type ("
316                                   + colscheme + ")");
317                   e.printStackTrace();
318                 }
319               }
320               else
321               {
322                 // add in some dummy min/max colours for the label-only
323                 // colourscheme.
324                 mincol = "FFFFFF";
325                 maxcol = "000000";
326               }
327               try
328               {
329                 colour = new jalview.schemes.GraduatedColor(
330                         new UserColourScheme(mincol).findColour('A'),
331                         new UserColourScheme(maxcol).findColour('A'), min,
332                         max);
333               } catch (Exception e)
334               {
335                 System.err
336                         .println("Couldn't parse the graduated colour scheme ("
337                                 + colscheme + ")");
338                 e.printStackTrace();
339               }
340               if (colour != null)
341               {
342                 ((jalview.schemes.GraduatedColor) colour)
343                         .setColourByLabel(labelCol);
344                 ((jalview.schemes.GraduatedColor) colour)
345                         .setAutoScaled(abso == null);
346                 // add in any additional parameters
347                 String ttype = null, tval = null;
348                 if (gcol.hasMoreTokens())
349                 {
350                   // threshold type and possibly a threshold value
351                   ttype = gcol.nextToken();
352                   if (ttype.toLowerCase().startsWith("below"))
353                   {
354                     ((jalview.schemes.GraduatedColor) colour)
355                             .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
356                   }
357                   else if (ttype.toLowerCase().startsWith("above"))
358                   {
359                     ((jalview.schemes.GraduatedColor) colour)
360                             .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
361                   }
362                   else
363                   {
364                     ((jalview.schemes.GraduatedColor) colour)
365                             .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
366                     if (!ttype.toLowerCase().startsWith("no"))
367                     {
368                       System.err
369                               .println("Ignoring unrecognised threshold type : "
370                                       + ttype);
371                     }
372                   }
373                 }
374                 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
375                 {
376                   try
377                   {
378                     gcol.nextToken();
379                     tval = gcol.nextToken();
380                     ((jalview.schemes.GraduatedColor) colour)
381                             .setThresh(new Float(tval).floatValue());
382                   } catch (Exception e)
383                   {
384                     System.err
385                             .println("Couldn't parse threshold value as a float: ("
386                                     + tval + ")");
387                     e.printStackTrace();
388                   }
389                 }
390                 // parse the thresh-is-min token ?
391                 if (gcol.hasMoreTokens())
392                 {
393                   System.err
394                           .println("Ignoring additional tokens in parameters in graduated colour specification\n");
395                   while (gcol.hasMoreTokens())
396                   {
397                     System.err.println("|" + gcol.nextToken());
398                   }
399                   System.err.println("\n");
400                 }
401               }
402             }
403             else
404             {
405               UserColourScheme ucs = new UserColourScheme(colscheme);
406               colour = ucs.findColour('A');
407             }
408             if (colour != null)
409             {
410               colours.put(type, colour);
411             }
412             if (st.hasMoreElements())
413             {
414               String link = st.nextToken();
415               typeLink.put(type, link);
416               if (featureLink == null)
417               {
418                 featureLink = new Hashtable();
419               }
420               featureLink.put(type, link);
421             }
422           }
423           continue;
424         }
425         String seqId = "";
426         while (st.hasMoreElements())
427         {
428
429           if (GFFFile)
430           {
431             // Still possible this is an old Jalview file,
432             // which does not have type colours at the beginning
433             seqId = token = st.nextToken();
434             seq = findName(align, seqId, relaxedIdmatching);
435             if (seq != null)
436             {
437               desc = st.nextToken();
438               String group = null;
439               if (doGffSource && desc.indexOf(' ') == -1)
440               {
441                 // could also be a source term rather than description line
442                 group = new String(desc);
443               }
444               type = st.nextToken();
445               try
446               {
447                 String stt = st.nextToken();
448                 if (stt.length() == 0 || stt.equals("-"))
449                 {
450                   start = 0;
451                 }
452                 else
453                 {
454                   start = Integer.parseInt(stt);
455                 }
456               } catch (NumberFormatException ex)
457               {
458                 start = 0;
459               }
460               try
461               {
462                 String stt = st.nextToken();
463                 if (stt.length() == 0 || stt.equals("-"))
464                 {
465                   end = 0;
466                 }
467                 else
468                 {
469                   end = Integer.parseInt(stt);
470                 }
471               } catch (NumberFormatException ex)
472               {
473                 end = 0;
474               }
475               // TODO: decide if non positional feature assertion for input data
476               // where end==0 is generally valid
477               if (end == 0)
478               {
479                 // treat as non-positional feature, regardless.
480                 start = 0;
481               }
482               try
483               {
484                 score = new Float(st.nextToken()).floatValue();
485               } catch (NumberFormatException ex)
486               {
487                 score = 0;
488               }
489
490               sf = new SequenceFeature(type, desc, start, end, score, group);
491
492               try
493               {
494                 sf.setValue("STRAND", st.nextToken());
495                 sf.setValue("FRAME", st.nextToken());
496               } catch (Exception ex)
497               {
498               }
499
500               if (st.hasMoreTokens())
501               {
502                 StringBuffer attributes = new StringBuffer();
503                 while (st.hasMoreTokens())
504                 {
505                   attributes.append("\t" + st.nextElement());
506                 }
507                 // TODO validate and split GFF2 attributes field ? parse out
508                 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
509                 // sf.setValue(attrib, val);
510                 sf.setValue("ATTRIBUTES", attributes.toString());
511               }
512
513               seq.addSequenceFeature(sf);
514               while ((seq = align.findName(seq, seqId, true)) != null)
515               {
516                 seq.addSequenceFeature(new SequenceFeature(sf));
517               }
518               break;
519             }
520           }
521
522           if (GFFFile && seq == null)
523           {
524             desc = token;
525           }
526           else
527           {
528             desc = st.nextToken();
529           }
530           if (!st.hasMoreTokens())
531           {
532             System.err
533                     .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
534             // in all probability, this isn't a file we understand, so bail
535             // quietly.
536             return false;
537           }
538
539           token = st.nextToken();
540
541           if (!token.equals("ID_NOT_SPECIFIED"))
542           {
543             seq = findName(align, seqId = token, relaxedIdmatching);
544             st.nextToken();
545           }
546           else
547           {
548             seqId = null;
549             try
550             {
551               index = Integer.parseInt(st.nextToken());
552               seq = align.getSequenceAt(index);
553             } catch (NumberFormatException ex)
554             {
555               seq = null;
556             }
557           }
558
559           if (seq == null)
560           {
561             System.out.println("Sequence not found: " + line);
562             break;
563           }
564
565           start = Integer.parseInt(st.nextToken());
566           end = Integer.parseInt(st.nextToken());
567
568           type = st.nextToken();
569
570           if (!colours.containsKey(type))
571           {
572             // Probably the old style groups file
573             UserColourScheme ucs = new UserColourScheme(type);
574             colours.put(type, ucs.findColour('A'));
575           }
576           sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
577           if (st.hasMoreTokens())
578           {
579             try
580             {
581               score = new Float(st.nextToken()).floatValue();
582               // update colourgradient bounds if allowed to
583             } catch (NumberFormatException ex)
584             {
585               score = 0;
586             }
587             sf.setScore(score);
588           }
589           if (groupLink != null && removeHTML)
590           {
591             sf.addLink(groupLink);
592             sf.description += "%LINK%";
593           }
594           if (typeLink.containsKey(type) && removeHTML)
595           {
596             sf.addLink(typeLink.get(type).toString());
597             sf.description += "%LINK%";
598           }
599
600           parseDescriptionHTML(sf, removeHTML);
601
602           seq.addSequenceFeature(sf);
603
604           while (seqId != null
605                   && (seq = align.findName(seq, seqId, false)) != null)
606           {
607             seq.addSequenceFeature(new SequenceFeature(sf));
608           }
609           // If we got here, its not a GFFFile
610           GFFFile = false;
611         }
612       }
613       resetMatcher();
614     } catch (Exception ex)
615     {
616       System.out.println("Error parsing feature file: " + ex + "\n" + line);
617       ex.printStackTrace(System.err);
618       resetMatcher();
619       return false;
620     }
621
622     return true;
623   }
624
625   private AlignmentI lastmatchedAl = null;
626
627   private SequenceIdMatcher matcher = null;
628
629   /**
630    * clear any temporary handles used to speed up ID matching
631    */
632   private void resetMatcher()
633   {
634     lastmatchedAl = null;
635     matcher = null;
636   }
637
638   private SequenceI findName(AlignmentI align, String seqId,
639           boolean relaxedIdMatching)
640   {
641     SequenceI match = null;
642     if (relaxedIdMatching)
643     {
644       if (lastmatchedAl != align)
645       {
646         matcher = new SequenceIdMatcher(
647                 (lastmatchedAl = align).getSequencesArray());
648       }
649       match = matcher.findIdMatch(seqId);
650     }
651     else
652     {
653       match = align.findName(seqId, true);
654     }
655     return match;
656   }
657
658   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
659   {
660     if (sf.getDescription() == null)
661     {
662       return;
663     }
664     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
665             sf.getDescription(), removeHTML, newline);
666
667     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
668             : sf.description;
669     for (String link : parsed.getLinks())
670     {
671       sf.addLink(link);
672     }
673
674   }
675
676   /**
677    * generate a features file for seqs includes non-pos features by default.
678    * 
679    * @param seqs
680    *          source of sequence features
681    * @param visible
682    *          hash of feature types and colours
683    * @return features file contents
684    */
685   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
686   {
687     return printJalviewFormat(seqs, visible, true, true);
688   }
689
690   /**
691    * generate a features file for seqs with colours from visible (if any)
692    * 
693    * @param seqs
694    *          source of features
695    * @param visible
696    *          hash of Colours for each feature type
697    * @param visOnly
698    *          when true only feature types in 'visible' will be output
699    * @param nonpos
700    *          indicates if non-positional features should be output (regardless
701    *          of group or type)
702    * @return features file contents
703    */
704   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
705           boolean visOnly, boolean nonpos)
706   {
707     StringBuffer out = new StringBuffer();
708     SequenceFeature[] next;
709     boolean featuresGen = false;
710     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
711     {
712       // no point continuing.
713       return "No Features Visible";
714     }
715
716     if (visible != null && visOnly)
717     {
718       // write feature colours only if we're given them and we are generating
719       // viewed features
720       // TODO: decide if feature links should also be written here ?
721       Enumeration en = visible.keys();
722       String type, color;
723       while (en.hasMoreElements())
724       {
725         type = en.nextElement().toString();
726
727         if (visible.get(type) instanceof GraduatedColor)
728         {
729           GraduatedColor gc = (GraduatedColor) visible.get(type);
730           color = (gc.isColourByLabel() ? "label|" : "")
731                   + Format.getHexString(gc.getMinColor()) + "|"
732                   + Format.getHexString(gc.getMaxColor())
733                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
734                   + gc.getMax() + "|";
735           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
736           {
737             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
738             {
739               color += "below";
740             }
741             else
742             {
743               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
744               {
745                 System.err.println("WARNING: Unsupported threshold type ("
746                         + gc.getThreshType() + ") : Assuming 'above'");
747               }
748               color += "above";
749             }
750             // add the value
751             color += "|" + gc.getThresh();
752           }
753           else
754           {
755             color += "none";
756           }
757         }
758         else if (visible.get(type) instanceof java.awt.Color)
759         {
760           color = Format.getHexString((java.awt.Color) visible.get(type));
761         }
762         else
763         {
764           // legacy support for integer objects containing colour triplet values
765           color = Format.getHexString(new java.awt.Color(Integer
766                   .parseInt(visible.get(type).toString())));
767         }
768         out.append(type);
769         out.append("\t");
770         out.append(color);
771         out.append(newline);
772       }
773     }
774     // Work out which groups are both present and visible
775     Vector groups = new Vector();
776     int groupIndex = 0;
777     boolean isnonpos = false;
778
779     for (int i = 0; i < seqs.length; i++)
780     {
781       next = seqs[i].getSequenceFeatures();
782       if (next != null)
783       {
784         for (int j = 0; j < next.length; j++)
785         {
786           isnonpos = next[j].begin == 0 && next[j].end == 0;
787           if ((!nonpos && isnonpos)
788                   || (!isnonpos && visOnly && !visible
789                           .containsKey(next[j].type)))
790           {
791             continue;
792           }
793
794           if (next[j].featureGroup != null
795                   && !groups.contains(next[j].featureGroup))
796           {
797             groups.addElement(next[j].featureGroup);
798           }
799         }
800       }
801     }
802
803     String group = null;
804     do
805     {
806
807       if (groups.size() > 0 && groupIndex < groups.size())
808       {
809         group = groups.elementAt(groupIndex).toString();
810         out.append(newline);
811         out.append("STARTGROUP\t");
812         out.append(group);
813         out.append(newline);
814       }
815       else
816       {
817         group = null;
818       }
819
820       for (int i = 0; i < seqs.length; i++)
821       {
822         next = seqs[i].getSequenceFeatures();
823         if (next != null)
824         {
825           for (int j = 0; j < next.length; j++)
826           {
827             isnonpos = next[j].begin == 0 && next[j].end == 0;
828             if ((!nonpos && isnonpos)
829                     || (!isnonpos && visOnly && !visible
830                             .containsKey(next[j].type)))
831             {
832               // skip if feature is nonpos and we ignore them or if we only
833               // output visible and it isn't non-pos and it's not visible
834               continue;
835             }
836
837             if (group != null
838                     && (next[j].featureGroup == null || !next[j].featureGroup
839                             .equals(group)))
840             {
841               continue;
842             }
843
844             if (group == null && next[j].featureGroup != null)
845             {
846               continue;
847             }
848             // we have features to output
849             featuresGen = true;
850             if (next[j].description == null
851                     || next[j].description.equals(""))
852             {
853               out.append(next[j].type + "\t");
854             }
855             else
856             {
857               if (next[j].links != null
858                       && next[j].getDescription().indexOf("<html>") == -1)
859               {
860                 out.append("<html>");
861               }
862
863               out.append(next[j].description + " ");
864               if (next[j].links != null)
865               {
866                 for (int l = 0; l < next[j].links.size(); l++)
867                 {
868                   String label = next[j].links.elementAt(l).toString();
869                   String href = label.substring(label.indexOf("|") + 1);
870                   label = label.substring(0, label.indexOf("|"));
871
872                   if (next[j].description.indexOf(href) == -1)
873                   {
874                     out.append("<a href=\"" + href + "\">" + label + "</a>");
875                   }
876                 }
877
878                 if (next[j].getDescription().indexOf("</html>") == -1)
879                 {
880                   out.append("</html>");
881                 }
882               }
883
884               out.append("\t");
885             }
886             out.append(seqs[i].getName());
887             out.append("\t-1\t");
888             out.append(next[j].begin);
889             out.append("\t");
890             out.append(next[j].end);
891             out.append("\t");
892             out.append(next[j].type);
893             if (next[j].score != Float.NaN)
894             {
895               out.append("\t");
896               out.append(next[j].score);
897             }
898             out.append(newline);
899           }
900         }
901       }
902
903       if (group != null)
904       {
905         out.append("ENDGROUP\t");
906         out.append(group);
907         out.append(newline);
908         groupIndex++;
909       }
910       else
911       {
912         break;
913       }
914
915     } while (groupIndex < groups.size() + 1);
916
917     if (!featuresGen)
918     {
919       return "No Features Visible";
920     }
921
922     return out.toString();
923   }
924
925   /**
926    * generate a gff file for sequence features includes non-pos features by
927    * default.
928    * 
929    * @param seqs
930    * @param visible
931    * @return
932    */
933   public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
934   {
935     return printGFFFormat(seqs, visible, true, true);
936   }
937
938   public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
939           boolean visOnly, boolean nonpos)
940   {
941     StringBuffer out = new StringBuffer();
942     SequenceFeature[] next;
943     String source;
944     boolean isnonpos;
945     for (int i = 0; i < seqs.length; i++)
946     {
947       if (seqs[i].getSequenceFeatures() != null)
948       {
949         next = seqs[i].getSequenceFeatures();
950         for (int j = 0; j < next.length; j++)
951         {
952           isnonpos = next[j].begin == 0 && next[j].end == 0;
953           if ((!nonpos && isnonpos)
954                   || (!isnonpos && visOnly && !visible
955                           .containsKey(next[j].type)))
956           {
957             continue;
958           }
959
960           source = next[j].featureGroup;
961           if (source == null)
962           {
963             source = next[j].getDescription();
964           }
965
966           out.append(seqs[i].getName());
967           out.append("\t");
968           out.append(source);
969           out.append("\t");
970           out.append(next[j].type);
971           out.append("\t");
972           out.append(next[j].begin);
973           out.append("\t");
974           out.append(next[j].end);
975           out.append("\t");
976           out.append(next[j].score);
977           out.append("\t");
978
979           if (next[j].getValue("STRAND") != null)
980           {
981             out.append(next[j].getValue("STRAND"));
982             out.append("\t");
983           }
984           else
985           {
986             out.append(".\t");
987           }
988
989           if (next[j].getValue("FRAME") != null)
990           {
991             out.append(next[j].getValue("FRAME"));
992           }
993           else
994           {
995             out.append(".");
996           }
997           // TODO: verify/check GFF - should there be a /t here before attribute
998           // output ?
999
1000           if (next[j].getValue("ATTRIBUTES") != null)
1001           {
1002             out.append(next[j].getValue("ATTRIBUTES"));
1003           }
1004
1005           out.append(newline);
1006
1007         }
1008       }
1009     }
1010
1011     return out.toString();
1012   }
1013
1014   /**
1015    * this is only for the benefit of object polymorphism - method does nothing.
1016    */
1017   public void parse()
1018   {
1019     // IGNORED
1020   }
1021
1022   /**
1023    * this is only for the benefit of object polymorphism - method does nothing.
1024    * 
1025    * @return error message
1026    */
1027   public String print()
1028   {
1029     return "USE printGFFFormat() or printJalviewFormat()";
1030   }
1031
1032 }