JAL-1705 derive transcript sequences from gene sequence/GFF; handle CDS
[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 (int j = 0; j < features.length; j++)
846           {
847             isnonpos = features[j].begin == 0 && features[j].end == 0;
848             if ((!nonpos && isnonpos)
849                     || (!isnonpos && visOnly && !visible
850                             .containsKey(features[j].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                     && (features[j].featureGroup == null || !features[j].featureGroup
859                             .equals(group)))
860             {
861               continue;
862             }
863
864             if (group == null && features[j].featureGroup != null)
865             {
866               continue;
867             }
868             // we have features to output
869             featuresGen = true;
870             if (features[j].description == null
871                     || features[j].description.equals(""))
872             {
873               out.append(features[j].type).append(TAB);
874             }
875             else
876             {
877               if (features[j].links != null
878                       && features[j].getDescription().indexOf("<html>") == -1)
879               {
880                 out.append("<html>");
881               }
882
883               out.append(features[j].description + " ");
884               if (features[j].links != null)
885               {
886                 for (int l = 0; l < features[j].links.size(); l++)
887                 {
888                   String label = features[j].links.elementAt(l).toString();
889                   String href = label.substring(label.indexOf("|") + 1);
890                   label = label.substring(0, label.indexOf("|"));
891
892                   if (features[j].description.indexOf(href) == -1)
893                   {
894                     out.append("<a href=\"" + href + "\">" + label + "</a>");
895                   }
896                 }
897
898                 if (features[j].getDescription().indexOf("</html>") == -1)
899                 {
900                   out.append("</html>");
901                 }
902               }
903
904               out.append(TAB);
905             }
906             out.append(sequences[i].getName());
907             out.append("\t-1\t");
908             out.append(features[j].begin);
909             out.append(TAB);
910             out.append(features[j].end);
911             out.append(TAB);
912             out.append(features[j].type);
913             if (!Float.isNaN(features[j].score))
914             {
915               out.append(TAB);
916               out.append(features[j].score);
917             }
918             out.append(newline);
919           }
920         }
921       }
922
923       if (group != null)
924       {
925         out.append("ENDGROUP").append(TAB);
926         out.append(group);
927         out.append(newline);
928         groupIndex++;
929       }
930       else
931       {
932         break;
933       }
934
935     } while (groupIndex < groups.size() + 1);
936
937     if (!featuresGen)
938     {
939       return "No Features Visible";
940     }
941
942     return out.toString();
943   }
944
945   /**
946    * Parse method that is called when a GFF file is dragged to the desktop
947    */
948   @Override
949   public void parse()
950   {
951     AlignViewportI av = getViewport();
952     if (av != null)
953     {
954       if (av.getAlignment() != null)
955       {
956         dataset = av.getAlignment().getDataset();
957       }
958       if (dataset == null)
959       {
960         // working in the applet context ?
961         dataset = av.getAlignment();
962       }
963     }
964     else
965     {
966       dataset = new Alignment(new SequenceI[] {});
967     }
968
969     boolean parseResult = parse(dataset, null, false, true);
970     if (!parseResult)
971     {
972       // pass error up somehow
973     }
974     if (av != null)
975     {
976       // update viewport with the dataset data ?
977     }
978     else
979     {
980       setSeqs(dataset.getSequencesArray());
981     }
982   }
983
984   /**
985    * Implementation of unused abstract method
986    * 
987    * @return error message
988    */
989   @Override
990   public String print()
991   {
992     return "Use printGffFormat() or printJalviewFormat()";
993   }
994
995   /**
996    * Returns features output in GFF2 format, including hidden and non-positional
997    * features
998    * 
999    * @param sequences
1000    *          the sequences whose features are to be output
1001    * @param visible
1002    *          a map whose keys are the type names of visible features
1003    * @return
1004    */
1005   public String printGffFormat(SequenceI[] sequences,
1006           Map<String, Object> visible)
1007   {
1008     return printGffFormat(sequences, visible, true, true);
1009   }
1010
1011   /**
1012    * Returns features output in GFF2 format
1013    * 
1014    * @param sequences
1015    *          the sequences whose features are to be output
1016    * @param visible
1017    *          a map whose keys are the type names of visible features
1018    * @param outputVisibleOnly
1019    * @param includeNonPositionalFeatures
1020    * @return
1021    */
1022   public String printGffFormat(SequenceI[] sequences,
1023           Map<String, Object> visible, boolean outputVisibleOnly,
1024           boolean includeNonPositionalFeatures)
1025   {
1026     StringBuilder out = new StringBuilder(256);
1027     out.append(String.format("%s %d\n", GFF_VERSION, gffVersion));
1028     String source;
1029     boolean isnonpos;
1030     for (SequenceI seq : sequences)
1031     {
1032       SequenceFeature[] features = seq.getSequenceFeatures();
1033       if (features != null)
1034       {
1035         for (SequenceFeature sf : features)
1036         {
1037           isnonpos = sf.begin == 0 && sf.end == 0;
1038           if (!includeNonPositionalFeatures && isnonpos)
1039           {
1040             /*
1041              * ignore non-positional features if not wanted
1042              */
1043             continue;
1044           }
1045           // TODO why the test !isnonpos here?
1046           // what about not visible non-positional features?
1047           if (!isnonpos && outputVisibleOnly
1048                   && !visible.containsKey(sf.type))
1049           {
1050             /*
1051              * ignore not visible features if not wanted
1052              */
1053             continue;
1054           }
1055
1056           source = sf.featureGroup;
1057           if (source == null)
1058           {
1059             source = sf.getDescription();
1060           }
1061
1062           out.append(seq.getName());
1063           out.append(TAB);
1064           out.append(source);
1065           out.append(TAB);
1066           out.append(sf.type);
1067           out.append(TAB);
1068           out.append(sf.begin);
1069           out.append(TAB);
1070           out.append(sf.end);
1071           out.append(TAB);
1072           out.append(sf.score);
1073           out.append(TAB);
1074
1075           int strand = sf.getStrand();
1076           out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1077           out.append(TAB);
1078
1079           String phase = sf.getPhase();
1080           out.append(phase == null ? "." : phase);
1081
1082           // miscellaneous key-values (GFF column 9)
1083           String attributes = sf.getAttributes();
1084           if (attributes != null)
1085           {
1086             out.append(TAB).append(attributes);
1087           }
1088
1089           out.append(newline);
1090         }
1091       }
1092     }
1093
1094     return out.toString();
1095   }
1096
1097   /**
1098    * Returns a mapping given list of one or more Align descriptors (exonerate
1099    * format)
1100    * 
1101    * @param alignedRegions
1102    *          a list of "Align fromStart toStart fromCount"
1103    * @param mapIsFromCdna
1104    *          if true, 'from' is dna, else 'from' is protein
1105    * @param strand
1106    *          either 1 (forward) or -1 (reverse)
1107    * @return
1108    * @throws IOException
1109    */
1110   protected MapList constructCodonMappingFromAlign(
1111           List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1112           throws IOException
1113   {
1114     if (strand == 0)
1115     {
1116       throw new IOException(
1117               "Invalid strand for a codon mapping (cannot be 0)");
1118     }
1119     int regions = alignedRegions.size();
1120     // arrays to hold [start, end] for each aligned region
1121     int[] fromRanges = new int[regions * 2]; // from dna
1122     int[] toRanges = new int[regions * 2]; // to protein
1123     int fromRangesIndex = 0;
1124     int toRangesIndex = 0;
1125
1126     for (String range : alignedRegions)
1127     {
1128       /* 
1129        * Align mapFromStart mapToStart mapFromCount
1130        * e.g. if mapIsFromCdna
1131        *     Align 11270 143 120
1132        * means:
1133        *     120 bases from pos 11270 align to pos 143 in peptide
1134        * if !mapIsFromCdna this would instead be
1135        *     Align 143 11270 40 
1136        */
1137       String[] tokens = range.split(" ");
1138       if (tokens.length != 3)
1139       {
1140         throw new IOException("Wrong number of fields for Align");
1141       }
1142       int fromStart = 0;
1143       int toStart = 0;
1144       int fromCount = 0;
1145       try
1146       {
1147         fromStart = Integer.parseInt(tokens[0]);
1148         toStart = Integer.parseInt(tokens[1]);
1149         fromCount = Integer.parseInt(tokens[2]);
1150       } catch (NumberFormatException nfe)
1151       {
1152         throw new IOException("Invalid number in Align field: "
1153                 + nfe.getMessage());
1154       }
1155
1156       /*
1157        * Jalview always models from dna to protein, so adjust values if the
1158        * GFF mapping is from protein to dna
1159        */
1160       if (!mapIsFromCdna)
1161       {
1162         fromCount *= 3;
1163         int temp = fromStart;
1164         fromStart = toStart;
1165         toStart = temp;
1166       }
1167       fromRanges[fromRangesIndex++] = fromStart;
1168       fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1169
1170       /*
1171        * If a codon has an intron gap, there will be contiguous 'toRanges';
1172        * this is handled for us by the MapList constructor. 
1173        * (It is not clear that exonerate ever generates this case)  
1174        */
1175       toRanges[toRangesIndex++] = toStart;
1176       toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1177     }
1178
1179     return new MapList(fromRanges, toRanges, 3, 1);
1180   }
1181
1182   /**
1183    * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1184    * hold the feature, or for its mapped sequence, or both, to be resolved
1185    * either later in the GFF file (##FASTA section), or when the user loads
1186    * additional sequences.
1187    * 
1188    * @param gffColumns
1189    * @param alignment
1190    * @param relaxedIdMatching
1191    * @param newseqs
1192    * @return
1193    */
1194   protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1195           boolean relaxedIdMatching, List<SequenceI> newseqs)
1196   {
1197     /*
1198      * GFF: seqid source type start end score strand phase [attributes]
1199      */
1200     if (gffColumns.length < 5)
1201     {
1202       System.err.println("Ignoring GFF feature line with too few columns ("
1203               + gffColumns.length + ")");
1204       return null;
1205     }
1206
1207     /*
1208      * locate referenced sequence in alignment _or_ 
1209      * as a forward or external reference (SequenceDummy)
1210      */
1211     String seqId = gffColumns[0];
1212     SequenceI seq = findSequence(seqId, alignment, newseqs,
1213             relaxedIdMatching);
1214
1215     SequenceFeature sf = null;
1216     GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1217     if (helper != null)
1218     {
1219       try
1220       {
1221         sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1222                 relaxedIdMatching);
1223         if (sf != null)
1224         {
1225           seq.addSequenceFeature(sf);
1226           while ((seq = alignment.findName(seq, seqId, true)) != null)
1227           {
1228             seq.addSequenceFeature(new SequenceFeature(sf));
1229           }
1230         }
1231       } catch (IOException e)
1232       {
1233         System.err.println("GFF parsing failed with: " + e.getMessage());
1234         return null;
1235       }
1236     }
1237
1238     return seq;
1239   }
1240
1241   /**
1242    * Process the 'column 9' data of the GFF file. This is less formally defined,
1243    * and its interpretation will vary depending on the tool that has generated
1244    * it.
1245    * 
1246    * @param attributes
1247    * @param sf
1248    */
1249   protected void processGffColumnNine(String attributes, SequenceFeature sf)
1250   {
1251     sf.setAttributes(attributes);
1252
1253     /*
1254      * Parse attributes in column 9 and add them to the sequence feature's 
1255      * 'otherData' table; use Note as a best proxy for description
1256      */
1257     char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1258     // TODO check we don't break GFF2 values which include commas here
1259     Map<String, List<String>> nameValues = GffHelperBase
1260             .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1261     for (Entry<String, List<String>> attr : nameValues.entrySet())
1262     {
1263       String values = StringUtils.listToDelimitedString(attr.getValue(),
1264               "; ");
1265       sf.setValue(attr.getKey(), values);
1266       if (NOTE.equals(attr.getKey()))
1267       {
1268         sf.setDescription(values);
1269       }
1270     }
1271   }
1272
1273   /**
1274    * After encountering ##fasta in a GFF3 file, process the remainder of the
1275    * file as FAST sequence data. Any placeholder sequences created during
1276    * feature parsing are updated with the actual sequences.
1277    * 
1278    * @param align
1279    * @param newseqs
1280    * @throws IOException
1281    */
1282   protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1283           throws IOException
1284   {
1285     try
1286     {
1287       mark();
1288     } catch (IOException q)
1289     {
1290     }
1291     FastaFile parser = new FastaFile(this);
1292     List<SequenceI> includedseqs = parser.getSeqs();
1293
1294     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1295
1296     /*
1297      * iterate over includedseqs, and replacing matching ones with newseqs
1298      * sequences. Generic iterator not used here because we modify
1299      * includedseqs as we go
1300      */
1301     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1302     {
1303       // search for any dummy seqs that this sequence can be used to update
1304       SequenceI includedSeq = includedseqs.get(p);
1305       SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1306       if (dummyseq != null && dummyseq instanceof SequenceDummy)
1307       {
1308         // probably have the pattern wrong
1309         // idea is that a flyweight proxy for a sequence ID can be created for
1310         // 1. stable reference creation
1311         // 2. addition of annotation
1312         // 3. future replacement by a real sequence
1313         // current pattern is to create SequenceDummy objects - a convenience
1314         // constructor for a Sequence.
1315         // problem is that when promoted to a real sequence, all references
1316         // need to be updated somehow. We avoid that by keeping the same object.
1317         ((SequenceDummy) dummyseq).become(includedSeq);
1318         dummyseq.createDatasetSequence();
1319
1320         /*
1321          * Update mappings so they are now to the dataset sequence
1322          */
1323         for (AlignedCodonFrame mapping : align.getCodonFrames())
1324         {
1325           mapping.updateToDataset(dummyseq);
1326         }
1327
1328         /*
1329          * replace parsed sequence with the realised forward reference
1330          */
1331         includedseqs.set(p, dummyseq);
1332
1333         /*
1334          * and remove from the newseqs list
1335          */
1336         newseqs.remove(dummyseq);
1337       }
1338     }
1339
1340     /*
1341      * finally add sequences to the dataset
1342      */
1343     for (SequenceI seq : includedseqs)
1344     {
1345       // experimental: mapping-based 'alignment' to query sequence
1346       AlignmentUtils.alignSequenceAs(seq, align,
1347               String.valueOf(align.getGapCharacter()), false, true);
1348
1349       // rename sequences if GFF handler requested this
1350       // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1351       SequenceFeature[] sfs = seq.getSequenceFeatures();
1352       if (sfs != null)
1353       {
1354         String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1355         if (newName != null)
1356         {
1357           seq.setName(newName);
1358         }
1359       }
1360       align.addSequence(seq);
1361     }
1362   }
1363
1364   /**
1365    * Process a ## directive
1366    * 
1367    * @param line
1368    * @param gffProps
1369    * @param align
1370    * @param newseqs
1371    * @throws IOException
1372    */
1373   protected void processGffPragma(String line,
1374           Map<String, String> gffProps, AlignmentI align,
1375           List<SequenceI> newseqs) throws IOException
1376   {
1377     line = line.trim();
1378     if ("###".equals(line))
1379     {
1380       // close off any open 'forward references'
1381       return;
1382     }
1383
1384     String[] tokens = line.substring(2).split(" ");
1385     String pragma = tokens[0];
1386     String value = tokens.length == 1 ? null : tokens[1];
1387
1388     if ("gff-version".equalsIgnoreCase(pragma))
1389     {
1390       if (value != null)
1391       {
1392         try
1393         {
1394           // value may be e.g. "3.1.2"
1395           gffVersion = Integer.parseInt(value.split("\\.")[0]);
1396         } catch (NumberFormatException e)
1397         {
1398           // ignore
1399         }
1400       }
1401     }
1402     else if ("sequence-region".equalsIgnoreCase(pragma))
1403     {
1404       // could capture <seqid start end> if wanted here
1405     }
1406     else if ("feature-ontology".equalsIgnoreCase(pragma))
1407     {
1408       // should resolve against the specified feature ontology URI
1409     }
1410     else if ("attribute-ontology".equalsIgnoreCase(pragma))
1411     {
1412       // URI of attribute ontology - not currently used in GFF3
1413     }
1414     else if ("source-ontology".equalsIgnoreCase(pragma))
1415     {
1416       // URI of source ontology - not currently used in GFF3
1417     }
1418     else if ("species-build".equalsIgnoreCase(pragma))
1419     {
1420       // save URI of specific NCBI taxon version of annotations
1421       gffProps.put("species-build", value);
1422     }
1423     else if ("fasta".equalsIgnoreCase(pragma))
1424     {
1425       // process the rest of the file as a fasta file and replace any dummy
1426       // sequence IDs
1427       processAsFasta(align, newseqs);
1428     }
1429     else
1430     {
1431       System.err.println("Ignoring unknown pragma: " + line);
1432     }
1433   }
1434 }