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