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