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