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