46467c53296759899ff575543c1369d5b6be5c25
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.analysis.AlignmentUtils;
24 import jalview.analysis.SequenceIdMatcher;
25 import jalview.api.AlignViewportI;
26 import jalview.api.FeatureColourI;
27 import jalview.api.FeaturesSourceI;
28 import jalview.datamodel.AlignedCodonFrame;
29 import jalview.datamodel.Alignment;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.SequenceDummy;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.io.gff.GffHelperBase;
35 import jalview.io.gff.GffHelperFactory;
36 import jalview.io.gff.GffHelperI;
37 import jalview.schemes.FeatureColour;
38 import jalview.schemes.UserColourScheme;
39 import jalview.util.MapList;
40 import jalview.util.ParseHtmlBodyAndLinks;
41 import jalview.util.StringUtils;
42
43 import java.io.IOException;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Map.Entry;
51 import java.util.StringTokenizer;
52
53 /**
54  * Parses and writes features files, which may be in Jalview, GFF2 or GFF3
55  * format. These are tab-delimited formats but with differences in the use of
56  * columns.
57  * 
58  * A Jalview feature file may define feature colours and then declare that the
59  * remainder of the file is in GFF format with the line 'GFF'.
60  * 
61  * GFF3 files may include alignment mappings for features, which Jalview will
62  * attempt to model, and may include sequence data following a ##FASTA line.
63  * 
64  * 
65  * @author AMW
66  * @author jbprocter
67  * @author gmcarstairs
68  */
69 public class FeaturesFile extends AlignFile implements FeaturesSourceI
70 {
71   private static final String ID_NOT_SPECIFIED = "ID_NOT_SPECIFIED";
72
73   private static final String NOTE = "Note";
74
75   protected static final String TAB = "\t";
76
77   protected static final String GFF_VERSION = "##gff-version";
78
79   private AlignmentI lastmatchedAl = null;
80
81   private SequenceIdMatcher matcher = null;
82
83   protected AlignmentI dataset;
84
85   protected int gffVersion;
86
87   /**
88    * Creates a new FeaturesFile object.
89    */
90   public FeaturesFile()
91   {
92   }
93
94   /**
95    * Constructor which does not parse the file immediately
96    * 
97    * @param inFile
98    * @param type
99    * @throws IOException
100    */
101   public FeaturesFile(String inFile, String type) throws IOException
102   {
103     super(false, inFile, type);
104   }
105
106   /**
107    * @param source
108    * @throws IOException
109    */
110   public FeaturesFile(FileParse source) throws IOException
111   {
112     super(source);
113   }
114
115   /**
116    * Constructor that optionally parses the file immediately
117    * 
118    * @param parseImmediately
119    * @param inFile
120    * @param type
121    * @throws IOException
122    */
123   public FeaturesFile(boolean parseImmediately, String inFile, String type)
124           throws IOException
125   {
126     super(parseImmediately, inFile, type);
127   }
128
129   /**
130    * Parse GFF or sequence features file using case-independent matching,
131    * discarding URLs
132    * 
133    * @param align
134    *          - alignment/dataset containing sequences that are to be annotated
135    * @param colours
136    *          - hashtable to store feature colour definitions
137    * @param removeHTML
138    *          - process html strings into plain text
139    * @return true if features were added
140    */
141   public boolean parse(AlignmentI align,
142           Map<String, FeatureColourI> colours,
143           boolean removeHTML)
144   {
145     return parse(align, colours, removeHTML, false);
146   }
147
148   /**
149    * Extends the default addProperties by also adding peptide-to-cDNA mappings
150    * (if any) derived while parsing a GFF file
151    */
152   @Override
153   public void addProperties(AlignmentI al)
154   {
155     super.addProperties(al);
156     if (dataset != null && dataset.getCodonFrames() != null)
157     {
158       AlignmentI ds = (al.getDataset() == null) ? al : al.getDataset();
159       for (AlignedCodonFrame codons : dataset.getCodonFrames())
160       {
161         ds.addCodonFrame(codons);
162       }
163     }
164   }
165
166   /**
167    * Parse GFF or Jalview format sequence features file
168    * 
169    * @param align
170    *          - alignment/dataset containing sequences that are to be annotated
171    * @param colours
172    *          - hashtable to store feature colour definitions
173    * @param removeHTML
174    *          - process html strings into plain text
175    * @param relaxedIdmatching
176    *          - when true, ID matches to compound sequence IDs are allowed
177    * @return true if features were added
178    */
179   public boolean parse(AlignmentI align,
180           Map<String, FeatureColourI> colours,
181           boolean removeHTML, boolean relaxedIdmatching)
182   {
183     Map<String, String> gffProps = new HashMap<String, String>();
184     /*
185      * keep track of any sequences we try to create from the data
186      */
187     List<SequenceI> newseqs = new ArrayList<SequenceI>();
188
189     String line = null;
190     try
191     {
192       String[] gffColumns;
193       String featureGroup = null;
194
195       while ((line = nextLine()) != null)
196       {
197         // skip comments/process pragmas
198         if (line.length() == 0 || line.startsWith("#"))
199         {
200           if (line.toLowerCase().startsWith("##"))
201           {
202             processGffPragma(line, gffProps, align, newseqs);
203           }
204           continue;
205         }
206
207         gffColumns = line.split("\\t"); // tab as regex
208         if (gffColumns.length == 1)
209         {
210           if (line.trim().equalsIgnoreCase("GFF"))
211           {
212             /*
213              * Jalview features file with appended GFF
214              * assume GFF2 (though it may declare ##gff-version 3)
215              */
216             gffVersion = 2;
217             continue;
218           }
219         }
220
221         if (gffColumns.length > 1 && gffColumns.length < 4)
222         {
223           /*
224            * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
225            * a feature type colour specification
226            */
227           String ft = gffColumns[0];
228           if (ft.equalsIgnoreCase("startgroup"))
229           {
230             featureGroup = gffColumns[1];
231           }
232           else if (ft.equalsIgnoreCase("endgroup"))
233           {
234             // We should check whether this is the current group,
235             // but at present there's no way of showing more than 1 group
236             featureGroup = null;
237           }
238           else
239           {
240             String colscheme = gffColumns[1];
241             FeatureColourI colour = FeatureColour
242                     .parseJalviewFeatureColour(colscheme);
243             if (colour != null)
244             {
245               colours.put(ft, colour);
246             }
247           }
248           continue;
249         }
250
251         /*
252          * if not a comment, GFF pragma, startgroup, endgroup or feature
253          * colour specification, that just leaves a feature details line
254          * in either Jalview or GFF format
255          */
256         if (gffVersion == 0)
257         {
258           parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
259                   relaxedIdmatching, featureGroup);
260         }
261         else
262         {
263           parseGff(gffColumns, align, relaxedIdmatching, newseqs);
264         }
265       }
266       resetMatcher();
267     } catch (Exception ex)
268     {
269       // should report somewhere useful for UI if necessary
270       warningMessage = ((warningMessage == null) ? "" : warningMessage)
271               + "Parsing error at\n" + line;
272       System.out.println("Error parsing feature file: " + ex + "\n" + line);
273       ex.printStackTrace(System.err);
274       resetMatcher();
275       return false;
276     }
277
278     /*
279      * experimental - add any dummy sequences with features to the alignment
280      * - we need them for Ensembl feature extraction - though maybe not otherwise
281      */
282     for (SequenceI newseq : newseqs)
283     {
284       if (newseq.getSequenceFeatures() != null)
285       {
286         align.addSequence(newseq);
287       }
288     }
289     return true;
290   }
291
292   /**
293    * Try to parse a Jalview format feature specification and add it as a
294    * sequence feature to any matching sequences in the alignment. Returns true
295    * if successful (a feature was added), or false if not.
296    * 
297    * @param line
298    * @param gffColumns
299    * @param alignment
300    * @param featureColours
301    * @param removeHTML
302    * @param relaxedIdmatching
303    * @param featureGroup
304    */
305   protected boolean parseJalviewFeature(String line, String[] gffColumns,
306           AlignmentI alignment, Map<String, FeatureColourI> featureColours,
307           boolean removeHTML, boolean relaxedIdMatching, String featureGroup)
308   {
309     /*
310      * tokens: description seqid seqIndex start end type [score]
311      */
312     if (gffColumns.length < 6)
313     {
314       System.err.println("Ignoring feature line '" + line
315               + "' with too few columns (" + gffColumns.length + ")");
316       return false;
317     }
318     String desc = gffColumns[0];
319     String seqId = gffColumns[1];
320     SequenceI seq = findSequence(seqId, alignment, null, relaxedIdMatching);
321
322     if (!ID_NOT_SPECIFIED.equals(seqId))
323     {
324       seq = findSequence(seqId, alignment, null, relaxedIdMatching);
325     }
326     else
327     {
328       seqId = null;
329       seq = null;
330       String seqIndex = gffColumns[2];
331       try
332       {
333         int idx = Integer.parseInt(seqIndex);
334         seq = alignment.getSequenceAt(idx);
335       } catch (NumberFormatException ex)
336       {
337         System.err.println("Invalid sequence index: " + seqIndex);
338       }
339     }
340
341     if (seq == null)
342     {
343       System.out.println("Sequence not found: " + line);
344       return false;
345     }
346
347     int startPos = Integer.parseInt(gffColumns[3]);
348     int endPos = Integer.parseInt(gffColumns[4]);
349
350     String ft = gffColumns[5];
351
352     if (!featureColours.containsKey(ft))
353     {
354       /* 
355        * Perhaps an old style groups file with no colours -
356        * synthesize a colour from the feature type
357        */
358       UserColourScheme ucs = new UserColourScheme(ft);
359       featureColours.put(ft, new FeatureColour(ucs.findColour('A')));
360     }
361     SequenceFeature sf = new SequenceFeature(ft, desc, "", startPos,
362             endPos, featureGroup);
363     if (gffColumns.length > 6)
364     {
365       float score = Float.NaN;
366       try
367       {
368         score = new Float(gffColumns[6]).floatValue();
369         // update colourgradient bounds if allowed to
370       } catch (NumberFormatException ex)
371       {
372         // leave as NaN
373       }
374       sf.setScore(score);
375     }
376
377     parseDescriptionHTML(sf, removeHTML);
378
379     seq.addSequenceFeature(sf);
380
381     while (seqId != null
382             && (seq = alignment.findName(seq, seqId, false)) != null)
383     {
384       seq.addSequenceFeature(new SequenceFeature(sf));
385     }
386     return true;
387   }
388
389   /**
390    * Process a feature type colour specification
391    * 
392    * @param line
393    *          the current input line (for error messages only)
394    * @param featureType
395    *          the first token on the line
396    * @param gffColumns
397    *          holds tokens on the line
398    * @param colours
399    *          map to which to add derived colour specification
400    */
401   protected void parseFeatureColour(String line, String featureType,
402           String[] gffColumns, Map<String, FeatureColourI> colours)
403   {
404     FeatureColourI colour = null;
405     String colscheme = gffColumns[1];
406     if (colscheme.indexOf("|") > -1
407             || colscheme.trim().equalsIgnoreCase("label"))
408     {
409       colour = parseGraduatedColourScheme(line, colscheme);
410     }
411     else
412     {
413       UserColourScheme ucs = new UserColourScheme(colscheme);
414       colour = new FeatureColour(ucs.findColour('A'));
415     }
416     if (colour != null)
417     {
418       colours.put(featureType, colour);
419     }
420   }
421
422   /**
423    * Parse a Jalview graduated colour descriptor
424    * 
425    * @param line
426    * @param colourDescriptor
427    * @return
428    */
429   protected FeatureColourI parseGraduatedColourScheme(String line,
430           String colourDescriptor)
431   {
432     // Parse '|' separated graduated colourscheme fields:
433     // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
434     // can either provide 'label' only, first is optional, next two
435     // colors are required (but may be
436     // left blank), next is optional, nxt two min/max are required.
437     // first is either 'label'
438     // first/second and third are both hexadecimal or word equivalent
439     // colour.
440     // next two are values parsed as floats.
441     // fifth is either 'above','below', or 'none'.
442     // sixth is a float value and only required when fifth is either
443     // 'above' or 'below'.
444     StringTokenizer gcol = new StringTokenizer(colourDescriptor, "|", true);
445     // set defaults
446     float min = Float.MIN_VALUE, max = Float.MAX_VALUE;
447     boolean labelCol = false;
448     // Parse spec line
449     String mincol = gcol.nextToken();
450     if (mincol == "|")
451     {
452       System.err
453               .println("Expected either 'label' or a colour specification in the line: "
454                       + line);
455       return null;
456     }
457     String maxcol = null;
458     if (mincol.toLowerCase().indexOf("label") == 0)
459     {
460       labelCol = true;
461       mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip '|'
462       mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
463     }
464     String abso = null, minval, maxval;
465     if (mincol != null)
466     {
467       // at least four more tokens
468       if (mincol.equals("|"))
469       {
470         mincol = "";
471       }
472       else
473       {
474         gcol.nextToken(); // skip next '|'
475       }
476       // continue parsing rest of line
477       maxcol = gcol.nextToken();
478       if (maxcol.equals("|"))
479       {
480         maxcol = "";
481       }
482       else
483       {
484         gcol.nextToken(); // skip next '|'
485       }
486       abso = gcol.nextToken();
487       gcol.nextToken(); // skip next '|'
488       if (abso.toLowerCase().indexOf("abso") != 0)
489       {
490         minval = abso;
491         abso = null;
492       }
493       else
494       {
495         minval = gcol.nextToken();
496         gcol.nextToken(); // skip next '|'
497       }
498       maxval = gcol.nextToken();
499       if (gcol.hasMoreTokens())
500       {
501         gcol.nextToken(); // skip next '|'
502       }
503       try
504       {
505         if (minval.length() > 0)
506         {
507           min = Float.valueOf(minval);
508         }
509       } catch (Exception e)
510       {
511         System.err
512                 .println("Couldn't parse the minimum value for graduated colour for type ("
513                         + colourDescriptor
514                         + ") - did you misspell 'auto' for the optional automatic colour switch ?");
515         e.printStackTrace();
516       }
517       try
518       {
519         if (maxval.length() > 0)
520         {
521           max = Float.valueOf(maxval);
522         }
523       } catch (Exception e)
524       {
525         System.err
526                 .println("Couldn't parse the maximum value for graduated colour for type ("
527                         + colourDescriptor + ")");
528         e.printStackTrace();
529       }
530     }
531     else
532     {
533       // add in some dummy min/max colours for the label-only
534       // colourscheme.
535       mincol = "FFFFFF";
536       maxcol = "000000";
537     }
538
539     FeatureColourI colour = null;
540     try
541     {
542       colour = new FeatureColour(
543               new UserColourScheme(mincol).findColour('A'),
544               new UserColourScheme(maxcol).findColour('A'), min, max);
545     } catch (Exception e)
546     {
547       System.err.println("Couldn't parse the graduated colour scheme ("
548               + colourDescriptor + ")");
549       e.printStackTrace();
550     }
551     if (colour != null)
552     {
553       colour.setColourByLabel(labelCol);
554       colour.setAutoScaled(abso == null);
555       // add in any additional parameters
556       String ttype = null, tval = null;
557       boolean hasThreshold = false;
558       if (gcol.hasMoreTokens())
559       {
560         // threshold type and possibly a threshold value
561         ttype = gcol.nextToken();
562         if (ttype.toLowerCase().startsWith("below"))
563         {
564           colour.setBelowThreshold(true);
565           hasThreshold = true;
566         }
567         else if (ttype.toLowerCase().startsWith("above"))
568         {
569           colour.setAboveThreshold(true);
570           hasThreshold = true;
571         }
572         else
573         {
574           if (!ttype.toLowerCase().startsWith("no"))
575           {
576             System.err.println("Ignoring unrecognised threshold type : "
577                     + ttype);
578           }
579         }
580       }
581       if (hasThreshold)
582       {
583         try
584         {
585           gcol.nextToken();
586           tval = gcol.nextToken();
587           colour.setThreshold(new Float(tval).floatValue());
588         } catch (Exception e)
589         {
590           System.err.println("Couldn't parse threshold value as a float: ("
591                   + tval + ")");
592           e.printStackTrace();
593         }
594       }
595       // parse the thresh-is-min token ?
596       if (gcol.hasMoreTokens())
597       {
598         System.err
599                 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
600         while (gcol.hasMoreTokens())
601         {
602           System.err.println("|" + gcol.nextToken());
603         }
604         System.err.println("\n");
605       }
606     }
607     return colour;
608   }
609
610   /**
611    * clear any temporary handles used to speed up ID matching
612    */
613   protected void resetMatcher()
614   {
615     lastmatchedAl = null;
616     matcher = null;
617   }
618
619   /**
620    * Returns a sequence matching the given id, as follows
621    * <ul>
622    * <li>strict matching is on exact sequence name</li>
623    * <li>relaxed matching allows matching on a token within the sequence name,
624    * or a dbxref</li>
625    * <li>first tries to find a match in the alignment sequences</li>
626    * <li>else tries to find a match in the new sequences already generated while
627    * parsing the features file</li>
628    * <li>else creates a new placeholder sequence, adds it to the new sequences
629    * list, and returns it</li>
630    * </ul>
631    * 
632    * @param seqId
633    * @param align
634    * @param newseqs
635    * @param relaxedIdMatching
636    * 
637    * @return
638    */
639   protected SequenceI findSequence(String seqId, AlignmentI align,
640           List<SequenceI> newseqs, boolean relaxedIdMatching)
641   {
642     // TODO encapsulate in SequenceIdMatcher, share the matcher
643     // with the GffHelper (removing code duplication)
644     SequenceI match = null;
645     if (relaxedIdMatching)
646     {
647       if (lastmatchedAl != align)
648       {
649         lastmatchedAl = align;
650         matcher = new SequenceIdMatcher(align.getSequencesArray());
651         if (newseqs != null)
652         {
653           matcher.addAll(newseqs);
654         }
655       }
656       match = matcher.findIdMatch(seqId);
657     }
658     else
659     {
660       match = align.findName(seqId, true);
661       if (match == null && newseqs != null)
662       {
663         for (SequenceI m : newseqs)
664         {
665           if (seqId.equals(m.getName()))
666           {
667             return m;
668           }
669         }
670       }
671
672     }
673     if (match == null && newseqs != null)
674     {
675       match = new SequenceDummy(seqId);
676       if (relaxedIdMatching)
677       {
678         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
679       }
680       // add dummy sequence to the newseqs list
681       newseqs.add(match);
682     }
683     return match;
684   }
685
686   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
687   {
688     if (sf.getDescription() == null)
689     {
690       return;
691     }
692     ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
693             sf.getDescription(), removeHTML, newline);
694
695     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
696             : sf.description;
697     for (String link : parsed.getLinks())
698     {
699       sf.addLink(link);
700     }
701
702   }
703
704   /**
705    * generate a features file for seqs includes non-pos features by default.
706    * 
707    * @param sequences
708    *          source of sequence features
709    * @param visible
710    *          hash of feature types and colours
711    * @return features file contents
712    */
713   public String printJalviewFormat(SequenceI[] sequences,
714           Map<String, FeatureColourI> visible)
715   {
716     return printJalviewFormat(sequences, visible, true, true);
717   }
718
719   /**
720    * generate a features file for seqs with colours from visible (if any)
721    * 
722    * @param sequences
723    *          source of features
724    * @param featureColours
725    *          hash of Colours for each feature type
726    * @param visOnly
727    *          when true only feature types in 'visible' will be output
728    * @param nonpos
729    *          indicates if non-positional features should be output (regardless
730    *          of group or type)
731    * @return features file contents
732    */
733   public String printJalviewFormat(SequenceI[] sequences,
734           Map<String, FeatureColourI> featureColours, boolean visOnly,
735           boolean nonpos)
736   {
737     StringBuilder out = new StringBuilder(256);
738     boolean featuresGen = false;
739     if (visOnly && !nonpos
740             && (featureColours == null || featureColours.size() < 1))
741     {
742       // no point continuing.
743       return "No Features Visible";
744     }
745
746     if (featureColours != null && visOnly)
747     {
748       // write feature colours only if we're given them and we are generating
749       // viewed features
750       // TODO: decide if feature links should also be written here ?
751       Iterator<String> en = featureColours.keySet().iterator();
752       while (en.hasNext())
753       {
754         String featureType = en.next();
755         FeatureColourI colour = featureColours.get(featureType);
756         out.append(colour.toJalviewFormat(featureType)).append(newline);
757       }
758     }
759
760     // Work out which groups are both present and visible
761     List<String> groups = new ArrayList<String>();
762     int groupIndex = 0;
763     boolean isnonpos = false;
764
765     SequenceFeature[] features;
766     for (int i = 0; i < sequences.length; i++)
767     {
768       features = sequences[i].getSequenceFeatures();
769       if (features != null)
770       {
771         for (int j = 0; j < features.length; j++)
772         {
773           isnonpos = features[j].begin == 0 && features[j].end == 0;
774           if ((!nonpos && isnonpos)
775                   || (!isnonpos && visOnly && !featureColours
776                           .containsKey(features[j].type)))
777           {
778             continue;
779           }
780
781           if (features[j].featureGroup != null
782                   && !groups.contains(features[j].featureGroup))
783           {
784             groups.add(features[j].featureGroup);
785           }
786         }
787       }
788     }
789
790     String group = null;
791     do
792     {
793       if (groups.size() > 0 && groupIndex < groups.size())
794       {
795         group = groups.get(groupIndex);
796         out.append(newline);
797         out.append("STARTGROUP").append(TAB);
798         out.append(group);
799         out.append(newline);
800       }
801       else
802       {
803         group = null;
804       }
805
806       for (int i = 0; i < sequences.length; i++)
807       {
808         features = sequences[i].getSequenceFeatures();
809         if (features != null)
810         {
811           for (SequenceFeature sequenceFeature : features)
812           {
813             isnonpos = sequenceFeature.begin == 0 && sequenceFeature.end == 0;
814             if ((!nonpos && isnonpos)
815                     || (!isnonpos && visOnly && !featureColours
816                             .containsKey(sequenceFeature.type)))
817             {
818               // skip if feature is nonpos and we ignore them or if we only
819               // output visible and it isn't non-pos and it's not visible
820               continue;
821             }
822
823             if (group != null
824                     && (sequenceFeature.featureGroup == null || !sequenceFeature.featureGroup
825                             .equals(group)))
826             {
827               continue;
828             }
829
830             if (group == null && sequenceFeature.featureGroup != null)
831             {
832               continue;
833             }
834             // we have features to output
835             featuresGen = true;
836             if (sequenceFeature.description == null
837                     || sequenceFeature.description.equals(""))
838             {
839               out.append(sequenceFeature.type).append(TAB);
840             }
841             else
842             {
843               if (sequenceFeature.links != null
844                       && sequenceFeature.getDescription().indexOf("<html>") == -1)
845               {
846                 out.append("<html>");
847               }
848
849               out.append(sequenceFeature.description);
850               if (sequenceFeature.links != null)
851               {
852                 for (int l = 0; l < sequenceFeature.links.size(); l++)
853                 {
854                   String label = sequenceFeature.links.elementAt(l);
855                   String href = label.substring(label.indexOf("|") + 1);
856                   label = label.substring(0, label.indexOf("|"));
857
858                   if (sequenceFeature.description.indexOf(href) == -1)
859                   {
860                     out.append(" <a href=\"" + href + "\">" + label
861                             + "</a>");
862                   }
863                 }
864
865                 if (sequenceFeature.getDescription().indexOf("</html>") == -1)
866                 {
867                   out.append("</html>");
868                 }
869               }
870
871               out.append(TAB);
872             }
873             out.append(sequences[i].getName());
874             out.append("\t-1\t");
875             out.append(sequenceFeature.begin);
876             out.append(TAB);
877             out.append(sequenceFeature.end);
878             out.append(TAB);
879             out.append(sequenceFeature.type);
880             if (!Float.isNaN(sequenceFeature.score))
881             {
882               out.append(TAB);
883               out.append(sequenceFeature.score);
884             }
885             out.append(newline);
886           }
887         }
888       }
889
890       if (group != null)
891       {
892         out.append("ENDGROUP").append(TAB);
893         out.append(group);
894         out.append(newline);
895         groupIndex++;
896       }
897       else
898       {
899         break;
900       }
901
902     } while (groupIndex < groups.size() + 1);
903
904     if (!featuresGen)
905     {
906       return "No Features Visible";
907     }
908
909     return out.toString();
910   }
911
912   /**
913    * Parse method that is called when a GFF file is dragged to the desktop
914    */
915   @Override
916   public void parse()
917   {
918     AlignViewportI av = getViewport();
919     if (av != null)
920     {
921       if (av.getAlignment() != null)
922       {
923         dataset = av.getAlignment().getDataset();
924       }
925       if (dataset == null)
926       {
927         // working in the applet context ?
928         dataset = av.getAlignment();
929       }
930     }
931     else
932     {
933       dataset = new Alignment(new SequenceI[] {});
934     }
935
936     boolean parseResult = parse(dataset, null, false, true);
937     if (!parseResult)
938     {
939       // pass error up somehow
940     }
941     if (av != null)
942     {
943       // update viewport with the dataset data ?
944     }
945     else
946     {
947       setSeqs(dataset.getSequencesArray());
948     }
949   }
950
951   /**
952    * Implementation of unused abstract method
953    * 
954    * @return error message
955    */
956   @Override
957   public String print()
958   {
959     return "Use printGffFormat() or printJalviewFormat()";
960   }
961
962   /**
963    * Returns features output in GFF2 format, including hidden and non-positional
964    * features
965    * 
966    * @param sequences
967    *          the sequences whose features are to be output
968    * @param visible
969    *          a map whose keys are the type names of visible features
970    * @return
971    */
972   public String printGffFormat(SequenceI[] sequences,
973           Map<String, FeatureColourI> visible)
974   {
975     return printGffFormat(sequences, visible, true, true);
976   }
977
978   /**
979    * Returns features output in GFF2 format
980    * 
981    * @param sequences
982    *          the sequences whose features are to be output
983    * @param featureColours
984    *          a map whose keys are the type names of visible features
985    * @param outputVisibleOnly
986    * @param includeNonPositionalFeatures
987    * @return
988    */
989   public String printGffFormat(SequenceI[] sequences,
990           Map<String, FeatureColourI> featureColours,
991           boolean outputVisibleOnly,
992           boolean includeNonPositionalFeatures)
993   {
994     StringBuilder out = new StringBuilder(256);
995     int version = gffVersion == 0 ? 2 : gffVersion;
996     out.append(String.format("%s %d\n", GFF_VERSION, version));
997     String source;
998     boolean isnonpos;
999     for (SequenceI seq : sequences)
1000     {
1001       SequenceFeature[] features = seq.getSequenceFeatures();
1002       if (features != null)
1003       {
1004         for (SequenceFeature sf : features)
1005         {
1006           isnonpos = sf.begin == 0 && sf.end == 0;
1007           if (!includeNonPositionalFeatures && isnonpos)
1008           {
1009             /*
1010              * ignore non-positional features if not wanted
1011              */
1012             continue;
1013           }
1014           // TODO why the test !isnonpos here?
1015           // what about not visible non-positional features?
1016           if (!isnonpos && outputVisibleOnly
1017                   && !featureColours.containsKey(sf.type))
1018           {
1019             /*
1020              * ignore not visible features if not wanted
1021              */
1022             continue;
1023           }
1024
1025           source = sf.featureGroup;
1026           if (source == null)
1027           {
1028             source = sf.getDescription();
1029           }
1030
1031           out.append(seq.getName());
1032           out.append(TAB);
1033           out.append(source);
1034           out.append(TAB);
1035           out.append(sf.type);
1036           out.append(TAB);
1037           out.append(sf.begin);
1038           out.append(TAB);
1039           out.append(sf.end);
1040           out.append(TAB);
1041           out.append(sf.score);
1042           out.append(TAB);
1043
1044           int strand = sf.getStrand();
1045           out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1046           out.append(TAB);
1047
1048           String phase = sf.getPhase();
1049           out.append(phase == null ? "." : phase);
1050
1051           // miscellaneous key-values (GFF column 9)
1052           String attributes = sf.getAttributes();
1053           if (attributes != null)
1054           {
1055             out.append(TAB).append(attributes);
1056           }
1057
1058           out.append(newline);
1059         }
1060       }
1061     }
1062
1063     return out.toString();
1064   }
1065
1066   /**
1067    * Returns a mapping given list of one or more Align descriptors (exonerate
1068    * format)
1069    * 
1070    * @param alignedRegions
1071    *          a list of "Align fromStart toStart fromCount"
1072    * @param mapIsFromCdna
1073    *          if true, 'from' is dna, else 'from' is protein
1074    * @param strand
1075    *          either 1 (forward) or -1 (reverse)
1076    * @return
1077    * @throws IOException
1078    */
1079   protected MapList constructCodonMappingFromAlign(
1080           List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1081           throws IOException
1082   {
1083     if (strand == 0)
1084     {
1085       throw new IOException(
1086               "Invalid strand for a codon mapping (cannot be 0)");
1087     }
1088     int regions = alignedRegions.size();
1089     // arrays to hold [start, end] for each aligned region
1090     int[] fromRanges = new int[regions * 2]; // from dna
1091     int[] toRanges = new int[regions * 2]; // to protein
1092     int fromRangesIndex = 0;
1093     int toRangesIndex = 0;
1094
1095     for (String range : alignedRegions)
1096     {
1097       /* 
1098        * Align mapFromStart mapToStart mapFromCount
1099        * e.g. if mapIsFromCdna
1100        *     Align 11270 143 120
1101        * means:
1102        *     120 bases from pos 11270 align to pos 143 in peptide
1103        * if !mapIsFromCdna this would instead be
1104        *     Align 143 11270 40 
1105        */
1106       String[] tokens = range.split(" ");
1107       if (tokens.length != 3)
1108       {
1109         throw new IOException("Wrong number of fields for Align");
1110       }
1111       int fromStart = 0;
1112       int toStart = 0;
1113       int fromCount = 0;
1114       try
1115       {
1116         fromStart = Integer.parseInt(tokens[0]);
1117         toStart = Integer.parseInt(tokens[1]);
1118         fromCount = Integer.parseInt(tokens[2]);
1119       } catch (NumberFormatException nfe)
1120       {
1121         throw new IOException("Invalid number in Align field: "
1122                 + nfe.getMessage());
1123       }
1124
1125       /*
1126        * Jalview always models from dna to protein, so adjust values if the
1127        * GFF mapping is from protein to dna
1128        */
1129       if (!mapIsFromCdna)
1130       {
1131         fromCount *= 3;
1132         int temp = fromStart;
1133         fromStart = toStart;
1134         toStart = temp;
1135       }
1136       fromRanges[fromRangesIndex++] = fromStart;
1137       fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1138
1139       /*
1140        * If a codon has an intron gap, there will be contiguous 'toRanges';
1141        * this is handled for us by the MapList constructor. 
1142        * (It is not clear that exonerate ever generates this case)  
1143        */
1144       toRanges[toRangesIndex++] = toStart;
1145       toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1146     }
1147
1148     return new MapList(fromRanges, toRanges, 3, 1);
1149   }
1150
1151   /**
1152    * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1153    * hold the feature, or for its mapped sequence, or both, to be resolved
1154    * either later in the GFF file (##FASTA section), or when the user loads
1155    * additional sequences.
1156    * 
1157    * @param gffColumns
1158    * @param alignment
1159    * @param relaxedIdMatching
1160    * @param newseqs
1161    * @return
1162    */
1163   protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1164           boolean relaxedIdMatching, List<SequenceI> newseqs)
1165   {
1166     /*
1167      * GFF: seqid source type start end score strand phase [attributes]
1168      */
1169     if (gffColumns.length < 5)
1170     {
1171       System.err.println("Ignoring GFF feature line with too few columns ("
1172               + gffColumns.length + ")");
1173       return null;
1174     }
1175
1176     /*
1177      * locate referenced sequence in alignment _or_ 
1178      * as a forward or external reference (SequenceDummy)
1179      */
1180     String seqId = gffColumns[0];
1181     SequenceI seq = findSequence(seqId, alignment, newseqs,
1182             relaxedIdMatching);
1183
1184     SequenceFeature sf = null;
1185     GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1186     if (helper != null)
1187     {
1188       try
1189       {
1190         sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1191                 relaxedIdMatching);
1192         if (sf != null)
1193         {
1194           seq.addSequenceFeature(sf);
1195           while ((seq = alignment.findName(seq, seqId, true)) != null)
1196           {
1197             seq.addSequenceFeature(new SequenceFeature(sf));
1198           }
1199         }
1200       } catch (IOException e)
1201       {
1202         System.err.println("GFF parsing failed with: " + e.getMessage());
1203         return null;
1204       }
1205     }
1206
1207     return seq;
1208   }
1209
1210   /**
1211    * Process the 'column 9' data of the GFF file. This is less formally defined,
1212    * and its interpretation will vary depending on the tool that has generated
1213    * it.
1214    * 
1215    * @param attributes
1216    * @param sf
1217    */
1218   protected void processGffColumnNine(String attributes, SequenceFeature sf)
1219   {
1220     sf.setAttributes(attributes);
1221
1222     /*
1223      * Parse attributes in column 9 and add them to the sequence feature's 
1224      * 'otherData' table; use Note as a best proxy for description
1225      */
1226     char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1227     // TODO check we don't break GFF2 values which include commas here
1228     Map<String, List<String>> nameValues = GffHelperBase
1229             .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1230     for (Entry<String, List<String>> attr : nameValues.entrySet())
1231     {
1232       String values = StringUtils.listToDelimitedString(attr.getValue(),
1233               "; ");
1234       sf.setValue(attr.getKey(), values);
1235       if (NOTE.equals(attr.getKey()))
1236       {
1237         sf.setDescription(values);
1238       }
1239     }
1240   }
1241
1242   /**
1243    * After encountering ##fasta in a GFF3 file, process the remainder of the
1244    * file as FAST sequence data. Any placeholder sequences created during
1245    * feature parsing are updated with the actual sequences.
1246    * 
1247    * @param align
1248    * @param newseqs
1249    * @throws IOException
1250    */
1251   protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1252           throws IOException
1253   {
1254     try
1255     {
1256       mark();
1257     } catch (IOException q)
1258     {
1259     }
1260     FastaFile parser = new FastaFile(this);
1261     List<SequenceI> includedseqs = parser.getSeqs();
1262
1263     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1264
1265     /*
1266      * iterate over includedseqs, and replacing matching ones with newseqs
1267      * sequences. Generic iterator not used here because we modify
1268      * includedseqs as we go
1269      */
1270     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1271     {
1272       // search for any dummy seqs that this sequence can be used to update
1273       SequenceI includedSeq = includedseqs.get(p);
1274       SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1275       if (dummyseq != null && dummyseq instanceof SequenceDummy)
1276       {
1277         // probably have the pattern wrong
1278         // idea is that a flyweight proxy for a sequence ID can be created for
1279         // 1. stable reference creation
1280         // 2. addition of annotation
1281         // 3. future replacement by a real sequence
1282         // current pattern is to create SequenceDummy objects - a convenience
1283         // constructor for a Sequence.
1284         // problem is that when promoted to a real sequence, all references
1285         // need to be updated somehow. We avoid that by keeping the same object.
1286         ((SequenceDummy) dummyseq).become(includedSeq);
1287         dummyseq.createDatasetSequence();
1288
1289         /*
1290          * Update mappings so they are now to the dataset sequence
1291          */
1292         for (AlignedCodonFrame mapping : align.getCodonFrames())
1293         {
1294           mapping.updateToDataset(dummyseq);
1295         }
1296
1297         /*
1298          * replace parsed sequence with the realised forward reference
1299          */
1300         includedseqs.set(p, dummyseq);
1301
1302         /*
1303          * and remove from the newseqs list
1304          */
1305         newseqs.remove(dummyseq);
1306       }
1307     }
1308
1309     /*
1310      * finally add sequences to the dataset
1311      */
1312     for (SequenceI seq : includedseqs)
1313     {
1314       // experimental: mapping-based 'alignment' to query sequence
1315       AlignmentUtils.alignSequenceAs(seq, align,
1316               String.valueOf(align.getGapCharacter()), false, true);
1317
1318       // rename sequences if GFF handler requested this
1319       // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1320       SequenceFeature[] sfs = seq.getSequenceFeatures();
1321       if (sfs != null)
1322       {
1323         String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1324         if (newName != null)
1325         {
1326           seq.setName(newName);
1327         }
1328       }
1329       align.addSequence(seq);
1330     }
1331   }
1332
1333   /**
1334    * Process a ## directive
1335    * 
1336    * @param line
1337    * @param gffProps
1338    * @param align
1339    * @param newseqs
1340    * @throws IOException
1341    */
1342   protected void processGffPragma(String line,
1343           Map<String, String> gffProps, AlignmentI align,
1344           List<SequenceI> newseqs) throws IOException
1345   {
1346     line = line.trim();
1347     if ("###".equals(line))
1348     {
1349       // close off any open 'forward references'
1350       return;
1351     }
1352
1353     String[] tokens = line.substring(2).split(" ");
1354     String pragma = tokens[0];
1355     String value = tokens.length == 1 ? null : tokens[1];
1356
1357     if ("gff-version".equalsIgnoreCase(pragma))
1358     {
1359       if (value != null)
1360       {
1361         try
1362         {
1363           // value may be e.g. "3.1.2"
1364           gffVersion = Integer.parseInt(value.split("\\.")[0]);
1365         } catch (NumberFormatException e)
1366         {
1367           // ignore
1368         }
1369       }
1370     }
1371     else if ("sequence-region".equalsIgnoreCase(pragma))
1372     {
1373       // could capture <seqid start end> if wanted here
1374     }
1375     else if ("feature-ontology".equalsIgnoreCase(pragma))
1376     {
1377       // should resolve against the specified feature ontology URI
1378     }
1379     else if ("attribute-ontology".equalsIgnoreCase(pragma))
1380     {
1381       // URI of attribute ontology - not currently used in GFF3
1382     }
1383     else if ("source-ontology".equalsIgnoreCase(pragma))
1384     {
1385       // URI of source ontology - not currently used in GFF3
1386     }
1387     else if ("species-build".equalsIgnoreCase(pragma))
1388     {
1389       // save URI of specific NCBI taxon version of annotations
1390       gffProps.put("species-build", value);
1391     }
1392     else if ("fasta".equalsIgnoreCase(pragma))
1393     {
1394       // process the rest of the file as a fasta file and replace any dummy
1395       // sequence IDs
1396       processAsFasta(align, newseqs);
1397     }
1398     else
1399     {
1400       System.err.println("Ignoring unknown pragma: " + line);
1401     }
1402   }
1403 }