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