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