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