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