proxy commit for Anne Menard <menard.annec@gmail.com> throw generic exceptions (just...
[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(line);
617       System.out.println("Error parsing feature file: " + ex + "\n" + line);
618       ex.printStackTrace(System.err);
619       resetMatcher();
620       return false;
621     }
622
623     return true;
624   }
625
626   private AlignmentI lastmatchedAl = null;
627
628   private SequenceIdMatcher matcher = null;
629
630   /**
631    * clear any temporary handles used to speed up ID matching
632    */
633   private void resetMatcher()
634   {
635     lastmatchedAl = null;
636     matcher = null;
637   }
638
639   private SequenceI findName(AlignmentI align, String seqId,
640           boolean relaxedIdMatching)
641   {
642     SequenceI match = null;
643     if (relaxedIdMatching)
644     {
645       if (lastmatchedAl != align)
646       {
647         matcher = new SequenceIdMatcher(
648                 (lastmatchedAl = align).getSequencesArray());
649       }
650       match = matcher.findIdMatch(seqId);
651     }
652     else
653     {
654       match = align.findName(seqId, true);
655     }
656     return match;
657   }
658
659   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
660   {
661     if (sf.getDescription() == null)
662     {
663       return;
664     }
665     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
666             sf.getDescription(), removeHTML, newline);
667
668     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
669             : sf.description;
670     for (String link : parsed.getLinks())
671     {
672       sf.addLink(link);
673     }
674
675   }
676
677   /**
678    * generate a features file for seqs includes non-pos features by default.
679    * 
680    * @param seqs
681    *          source of sequence features
682    * @param visible
683    *          hash of feature types and colours
684    * @return features file contents
685    */
686   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
687   {
688     return printJalviewFormat(seqs, visible, true, true);
689   }
690
691   /**
692    * generate a features file for seqs with colours from visible (if any)
693    * 
694    * @param seqs
695    *          source of features
696    * @param visible
697    *          hash of Colours for each feature type
698    * @param visOnly
699    *          when true only feature types in 'visible' will be output
700    * @param nonpos
701    *          indicates if non-positional features should be output (regardless
702    *          of group or type)
703    * @return features file contents
704    */
705   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
706           boolean visOnly, boolean nonpos)
707   {
708     StringBuffer out = new StringBuffer();
709     SequenceFeature[] next;
710     boolean featuresGen = false;
711     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
712     {
713       // no point continuing.
714       return "No Features Visible";
715     }
716
717     if (visible != null && visOnly)
718     {
719       // write feature colours only if we're given them and we are generating
720       // viewed features
721       // TODO: decide if feature links should also be written here ?
722       Enumeration en = visible.keys();
723       String type, color;
724       while (en.hasMoreElements())
725       {
726         type = en.nextElement().toString();
727
728         if (visible.get(type) instanceof GraduatedColor)
729         {
730           GraduatedColor gc = (GraduatedColor) visible.get(type);
731           color = (gc.isColourByLabel() ? "label|" : "")
732                   + Format.getHexString(gc.getMinColor()) + "|"
733                   + Format.getHexString(gc.getMaxColor())
734                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
735                   + gc.getMax() + "|";
736           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
737           {
738             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
739             {
740               color += "below";
741             }
742             else
743             {
744               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
745               {
746                 System.err.println("WARNING: Unsupported threshold type ("
747                         + gc.getThreshType() + ") : Assuming 'above'");
748               }
749               color += "above";
750             }
751             // add the value
752             color += "|" + gc.getThresh();
753           }
754           else
755           {
756             color += "none";
757           }
758         }
759         else if (visible.get(type) instanceof java.awt.Color)
760         {
761           color = Format.getHexString((java.awt.Color) visible.get(type));
762         }
763         else
764         {
765           // legacy support for integer objects containing colour triplet values
766           color = Format.getHexString(new java.awt.Color(Integer
767                   .parseInt(visible.get(type).toString())));
768         }
769         out.append(type);
770         out.append("\t");
771         out.append(color);
772         out.append(newline);
773       }
774     }
775     // Work out which groups are both present and visible
776     Vector groups = new Vector();
777     int groupIndex = 0;
778     boolean isnonpos = false;
779
780     for (int i = 0; i < seqs.length; i++)
781     {
782       next = seqs[i].getSequenceFeatures();
783       if (next != null)
784       {
785         for (int j = 0; j < next.length; j++)
786         {
787           isnonpos = next[j].begin == 0 && next[j].end == 0;
788           if ((!nonpos && isnonpos)
789                   || (!isnonpos && visOnly && !visible
790                           .containsKey(next[j].type)))
791           {
792             continue;
793           }
794
795           if (next[j].featureGroup != null
796                   && !groups.contains(next[j].featureGroup))
797           {
798             groups.addElement(next[j].featureGroup);
799           }
800         }
801       }
802     }
803
804     String group = null;
805     do
806     {
807
808       if (groups.size() > 0 && groupIndex < groups.size())
809       {
810         group = groups.elementAt(groupIndex).toString();
811         out.append(newline);
812         out.append("STARTGROUP\t");
813         out.append(group);
814         out.append(newline);
815       }
816       else
817       {
818         group = null;
819       }
820
821       for (int i = 0; i < seqs.length; i++)
822       {
823         next = seqs[i].getSequenceFeatures();
824         if (next != null)
825         {
826           for (int j = 0; j < next.length; j++)
827           {
828             isnonpos = next[j].begin == 0 && next[j].end == 0;
829             if ((!nonpos && isnonpos)
830                     || (!isnonpos && visOnly && !visible
831                             .containsKey(next[j].type)))
832             {
833               // skip if feature is nonpos and we ignore them or if we only
834               // output visible and it isn't non-pos and it's not visible
835               continue;
836             }
837
838             if (group != null
839                     && (next[j].featureGroup == null || !next[j].featureGroup
840                             .equals(group)))
841             {
842               continue;
843             }
844
845             if (group == null && next[j].featureGroup != null)
846             {
847               continue;
848             }
849             // we have features to output
850             featuresGen = true;
851             if (next[j].description == null
852                     || next[j].description.equals(""))
853             {
854               out.append(next[j].type + "\t");
855             }
856             else
857             {
858               if (next[j].links != null
859                       && next[j].getDescription().indexOf("<html>") == -1)
860               {
861                 out.append("<html>");
862               }
863
864               out.append(next[j].description + " ");
865               if (next[j].links != null)
866               {
867                 for (int l = 0; l < next[j].links.size(); l++)
868                 {
869                   String label = next[j].links.elementAt(l).toString();
870                   String href = label.substring(label.indexOf("|") + 1);
871                   label = label.substring(0, label.indexOf("|"));
872
873                   if (next[j].description.indexOf(href) == -1)
874                   {
875                     out.append("<a href=\"" + href + "\">" + label + "</a>");
876                   }
877                 }
878
879                 if (next[j].getDescription().indexOf("</html>") == -1)
880                 {
881                   out.append("</html>");
882                 }
883               }
884
885               out.append("\t");
886             }
887             out.append(seqs[i].getName());
888             out.append("\t-1\t");
889             out.append(next[j].begin);
890             out.append("\t");
891             out.append(next[j].end);
892             out.append("\t");
893             out.append(next[j].type);
894             if (next[j].score != Float.NaN)
895             {
896               out.append("\t");
897               out.append(next[j].score);
898             }
899             out.append(newline);
900           }
901         }
902       }
903
904       if (group != null)
905       {
906         out.append("ENDGROUP\t");
907         out.append(group);
908         out.append(newline);
909         groupIndex++;
910       }
911       else
912       {
913         break;
914       }
915
916     } while (groupIndex < groups.size() + 1);
917
918     if (!featuresGen)
919     {
920       return "No Features Visible";
921     }
922
923     return out.toString();
924   }
925
926   /**
927    * generate a gff file for sequence features includes non-pos features by
928    * default.
929    * 
930    * @param seqs
931    * @param visible
932    * @return
933    */
934   public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
935   {
936     return printGFFFormat(seqs, visible, true, true);
937   }
938
939   public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
940           boolean visOnly, boolean nonpos)
941   {
942     StringBuffer out = new StringBuffer();
943     SequenceFeature[] next;
944     String source;
945     boolean isnonpos;
946     for (int i = 0; i < seqs.length; i++)
947     {
948       if (seqs[i].getSequenceFeatures() != null)
949       {
950         next = seqs[i].getSequenceFeatures();
951         for (int j = 0; j < next.length; j++)
952         {
953           isnonpos = next[j].begin == 0 && next[j].end == 0;
954           if ((!nonpos && isnonpos)
955                   || (!isnonpos && visOnly && !visible
956                           .containsKey(next[j].type)))
957           {
958             continue;
959           }
960
961           source = next[j].featureGroup;
962           if (source == null)
963           {
964             source = next[j].getDescription();
965           }
966
967           out.append(seqs[i].getName());
968           out.append("\t");
969           out.append(source);
970           out.append("\t");
971           out.append(next[j].type);
972           out.append("\t");
973           out.append(next[j].begin);
974           out.append("\t");
975           out.append(next[j].end);
976           out.append("\t");
977           out.append(next[j].score);
978           out.append("\t");
979
980           if (next[j].getValue("STRAND") != null)
981           {
982             out.append(next[j].getValue("STRAND"));
983             out.append("\t");
984           }
985           else
986           {
987             out.append(".\t");
988           }
989
990           if (next[j].getValue("FRAME") != null)
991           {
992             out.append(next[j].getValue("FRAME"));
993           }
994           else
995           {
996             out.append(".");
997           }
998           // TODO: verify/check GFF - should there be a /t here before attribute
999           // output ?
1000
1001           if (next[j].getValue("ATTRIBUTES") != null)
1002           {
1003             out.append(next[j].getValue("ATTRIBUTES"));
1004           }
1005
1006           out.append(newline);
1007
1008         }
1009       }
1010     }
1011
1012     return out.toString();
1013   }
1014
1015   /**
1016    * this is only for the benefit of object polymorphism - method does nothing.
1017    */
1018   public void parse()
1019   {
1020     // IGNORED
1021   }
1022
1023   /**
1024    * this is only for the benefit of object polymorphism - method does nothing.
1025    * 
1026    * @return error message
1027    */
1028   public String print()
1029   {
1030     return "USE printGFFFormat() or printJalviewFormat()";
1031   }
1032
1033 }