JAL-2675 bump version for branch to 2.10.2b1
[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.HashMap;
48 import java.util.Iterator;
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 inFile
98    * @param paste
99    * @throws IOException
100    */
101   public FeaturesFile(String inFile, DataSourceType paste)
102           throws IOException
103   {
104     super(false, inFile, 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 inFile
121    * @param type
122    * @throws IOException
123    */
124   public FeaturesFile(boolean parseImmediately, String inFile,
125           DataSourceType type) throws IOException
126   {
127     super(parseImmediately, inFile, 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.getSequenceFeatures() != null)
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 = new SequenceFeature(ft, desc, "", startPos, endPos,
363             featureGroup);
364     if (gffColumns.length > 6)
365     {
366       float score = Float.NaN;
367       try
368       {
369         score = new Float(gffColumns[6]).floatValue();
370         // update colourgradient bounds if allowed to
371       } catch (NumberFormatException ex)
372       {
373         // leave as NaN
374       }
375       sf.setScore(score);
376     }
377
378     parseDescriptionHTML(sf, removeHTML);
379
380     seq.addSequenceFeature(sf);
381
382     while (seqId != null
383             && (seq = alignment.findName(seq, seqId, false)) != null)
384     {
385       seq.addSequenceFeature(new SequenceFeature(sf));
386     }
387     return true;
388   }
389
390   /**
391    * clear any temporary handles used to speed up ID matching
392    */
393   protected void resetMatcher()
394   {
395     lastmatchedAl = null;
396     matcher = null;
397   }
398
399   /**
400    * Returns a sequence matching the given id, as follows
401    * <ul>
402    * <li>strict matching is on exact sequence name</li>
403    * <li>relaxed matching allows matching on a token within the sequence name,
404    * or a dbxref</li>
405    * <li>first tries to find a match in the alignment sequences</li>
406    * <li>else tries to find a match in the new sequences already generated while
407    * parsing the features file</li>
408    * <li>else creates a new placeholder sequence, adds it to the new sequences
409    * list, and returns it</li>
410    * </ul>
411    * 
412    * @param seqId
413    * @param align
414    * @param newseqs
415    * @param relaxedIdMatching
416    * 
417    * @return
418    */
419   protected SequenceI findSequence(String seqId, AlignmentI align,
420           List<SequenceI> newseqs, boolean relaxedIdMatching)
421   {
422     // TODO encapsulate in SequenceIdMatcher, share the matcher
423     // with the GffHelper (removing code duplication)
424     SequenceI match = null;
425     if (relaxedIdMatching)
426     {
427       if (lastmatchedAl != align)
428       {
429         lastmatchedAl = align;
430         matcher = new SequenceIdMatcher(align.getSequencesArray());
431         if (newseqs != null)
432         {
433           matcher.addAll(newseqs);
434         }
435       }
436       match = matcher.findIdMatch(seqId);
437     }
438     else
439     {
440       match = align.findName(seqId, true);
441       if (match == null && newseqs != null)
442       {
443         for (SequenceI m : newseqs)
444         {
445           if (seqId.equals(m.getName()))
446           {
447             return m;
448           }
449         }
450       }
451
452     }
453     if (match == null && newseqs != null)
454     {
455       match = new SequenceDummy(seqId);
456       if (relaxedIdMatching)
457       {
458         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
459       }
460       // add dummy sequence to the newseqs list
461       newseqs.add(match);
462     }
463     return match;
464   }
465
466   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
467   {
468     if (sf.getDescription() == null)
469     {
470       return;
471     }
472     ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
473             sf.getDescription(), removeHTML, newline);
474
475     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
476             : sf.description;
477     for (String link : parsed.getLinks())
478     {
479       sf.addLink(link);
480     }
481
482   }
483
484   /**
485    * generate a features file for seqs includes non-pos features by default.
486    * 
487    * @param sequences
488    *          source of sequence features
489    * @param visible
490    *          hash of feature types and colours
491    * @return features file contents
492    */
493   public String printJalviewFormat(SequenceI[] sequences,
494           Map<String, FeatureColourI> visible)
495   {
496     return printJalviewFormat(sequences, visible, true, true);
497   }
498
499   /**
500    * generate a features file for seqs with colours from visible (if any)
501    * 
502    * @param sequences
503    *          source of features
504    * @param visible
505    *          hash of Colours for each feature type
506    * @param visOnly
507    *          when true only feature types in 'visible' will be output
508    * @param nonpos
509    *          indicates if non-positional features should be output (regardless
510    *          of group or type)
511    * @return features file contents
512    */
513   public String printJalviewFormat(SequenceI[] sequences,
514           Map<String, FeatureColourI> visible, boolean visOnly,
515           boolean nonpos)
516   {
517     StringBuilder out = new StringBuilder(256);
518     boolean featuresGen = false;
519     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
520     {
521       // no point continuing.
522       return "No Features Visible";
523     }
524
525     if (visible != null && visOnly)
526     {
527       // write feature colours only if we're given them and we are generating
528       // viewed features
529       // TODO: decide if feature links should also be written here ?
530       Iterator<String> en = visible.keySet().iterator();
531       while (en.hasNext())
532       {
533         String featureType = en.next().toString();
534         FeatureColourI colour = visible.get(featureType);
535         out.append(colour.toJalviewFormat(featureType)).append(newline);
536       }
537     }
538
539     // Work out which groups are both present and visible
540     List<String> groups = new ArrayList<String>();
541     int groupIndex = 0;
542     boolean isnonpos = false;
543
544     SequenceFeature[] features;
545     for (int i = 0; i < sequences.length; i++)
546     {
547       features = sequences[i].getSequenceFeatures();
548       if (features != null)
549       {
550         for (int j = 0; j < features.length; j++)
551         {
552           isnonpos = features[j].begin == 0 && features[j].end == 0;
553           if ((!nonpos && isnonpos) || (!isnonpos && visOnly
554                   && !visible.containsKey(features[j].type)))
555           {
556             continue;
557           }
558
559           if (features[j].featureGroup != null
560                   && !groups.contains(features[j].featureGroup))
561           {
562             groups.add(features[j].featureGroup);
563           }
564         }
565       }
566     }
567
568     String group = null;
569     do
570     {
571       if (groups.size() > 0 && groupIndex < groups.size())
572       {
573         group = groups.get(groupIndex);
574         out.append(newline);
575         out.append("STARTGROUP").append(TAB);
576         out.append(group);
577         out.append(newline);
578       }
579       else
580       {
581         group = null;
582       }
583
584       for (int i = 0; i < sequences.length; i++)
585       {
586         features = sequences[i].getSequenceFeatures();
587         if (features != null)
588         {
589           for (SequenceFeature sequenceFeature : features)
590           {
591             isnonpos = sequenceFeature.begin == 0
592                     && sequenceFeature.end == 0;
593             if ((!nonpos && isnonpos) || (!isnonpos && visOnly
594                     && !visible.containsKey(sequenceFeature.type)))
595             {
596               // skip if feature is nonpos and we ignore them or if we only
597               // output visible and it isn't non-pos and it's not visible
598               continue;
599             }
600
601             if (group != null && (sequenceFeature.featureGroup == null
602                     || !sequenceFeature.featureGroup.equals(group)))
603             {
604               continue;
605             }
606
607             if (group == null && sequenceFeature.featureGroup != null)
608             {
609               continue;
610             }
611             // we have features to output
612             featuresGen = true;
613             if (sequenceFeature.description == null
614                     || sequenceFeature.description.equals(""))
615             {
616               out.append(sequenceFeature.type).append(TAB);
617             }
618             else
619             {
620               if (sequenceFeature.links != null && sequenceFeature
621                       .getDescription().indexOf("<html>") == -1)
622               {
623                 out.append("<html>");
624               }
625
626               out.append(sequenceFeature.description);
627               if (sequenceFeature.links != null)
628               {
629                 for (int l = 0; l < sequenceFeature.links.size(); l++)
630                 {
631                   String label = sequenceFeature.links.elementAt(l);
632                   String href = label.substring(label.indexOf("|") + 1);
633                   label = label.substring(0, label.indexOf("|"));
634
635                   if (sequenceFeature.description.indexOf(href) == -1)
636                   {
637                     out.append(
638                             " <a href=\"" + href + "\">" + label + "</a>");
639                   }
640                 }
641
642                 if (sequenceFeature.getDescription()
643                         .indexOf("</html>") == -1)
644                 {
645                   out.append("</html>");
646                 }
647               }
648
649               out.append(TAB);
650             }
651             out.append(sequences[i].getName());
652             out.append("\t-1\t");
653             out.append(sequenceFeature.begin);
654             out.append(TAB);
655             out.append(sequenceFeature.end);
656             out.append(TAB);
657             out.append(sequenceFeature.type);
658             if (!Float.isNaN(sequenceFeature.score))
659             {
660               out.append(TAB);
661               out.append(sequenceFeature.score);
662             }
663             out.append(newline);
664           }
665         }
666       }
667
668       if (group != null)
669       {
670         out.append("ENDGROUP").append(TAB);
671         out.append(group);
672         out.append(newline);
673         groupIndex++;
674       }
675       else
676       {
677         break;
678       }
679
680     } while (groupIndex < groups.size() + 1);
681
682     if (!featuresGen)
683     {
684       return "No Features Visible";
685     }
686
687     return out.toString();
688   }
689
690   /**
691    * Parse method that is called when a GFF file is dragged to the desktop
692    */
693   @Override
694   public void parse()
695   {
696     AlignViewportI av = getViewport();
697     if (av != null)
698     {
699       if (av.getAlignment() != null)
700       {
701         dataset = av.getAlignment().getDataset();
702       }
703       if (dataset == null)
704       {
705         // working in the applet context ?
706         dataset = av.getAlignment();
707       }
708     }
709     else
710     {
711       dataset = new Alignment(new SequenceI[] {});
712     }
713
714     Map<String, FeatureColourI> featureColours = new HashMap<String, FeatureColourI>();
715     boolean parseResult = parse(dataset, featureColours, false, true);
716     if (!parseResult)
717     {
718       // pass error up somehow
719     }
720     if (av != null)
721     {
722       // update viewport with the dataset data ?
723     }
724     else
725     {
726       setSeqs(dataset.getSequencesArray());
727     }
728   }
729
730   /**
731    * Implementation of unused abstract method
732    * 
733    * @return error message
734    */
735   @Override
736   public String print(SequenceI[] sqs, boolean jvsuffix)
737   {
738     System.out.println("Use printGffFormat() or printJalviewFormat()");
739     return null;
740   }
741
742   /**
743    * Returns features output in GFF2 format, including hidden and non-positional
744    * features
745    * 
746    * @param sequences
747    *          the sequences whose features are to be output
748    * @param visible
749    *          a map whose keys are the type names of visible features
750    * @return
751    */
752   public String printGffFormat(SequenceI[] sequences,
753           Map<String, FeatureColourI> visible)
754   {
755     return printGffFormat(sequences, visible, true, true);
756   }
757
758   /**
759    * Returns features output in GFF2 format
760    * 
761    * @param sequences
762    *          the sequences whose features are to be output
763    * @param visible
764    *          a map whose keys are the type names of visible features
765    * @param outputVisibleOnly
766    * @param includeNonPositionalFeatures
767    * @return
768    */
769   public String printGffFormat(SequenceI[] sequences,
770           Map<String, FeatureColourI> visible, boolean outputVisibleOnly,
771           boolean includeNonPositionalFeatures)
772   {
773     StringBuilder out = new StringBuilder(256);
774     int version = gffVersion == 0 ? 2 : gffVersion;
775     out.append(String.format("%s %d\n", GFF_VERSION, version));
776     String source;
777     boolean isnonpos;
778     for (SequenceI seq : sequences)
779     {
780       SequenceFeature[] features = seq.getSequenceFeatures();
781       if (features != null)
782       {
783         for (SequenceFeature sf : features)
784         {
785           isnonpos = sf.begin == 0 && sf.end == 0;
786           if (!includeNonPositionalFeatures && isnonpos)
787           {
788             /*
789              * ignore non-positional features if not wanted
790              */
791             continue;
792           }
793           // TODO why the test !isnonpos here?
794           // what about not visible non-positional features?
795           if (!isnonpos && outputVisibleOnly
796                   && !visible.containsKey(sf.type))
797           {
798             /*
799              * ignore not visible features if not wanted
800              */
801             continue;
802           }
803
804           source = sf.featureGroup;
805           if (source == null)
806           {
807             source = sf.getDescription();
808           }
809
810           out.append(seq.getName());
811           out.append(TAB);
812           out.append(source);
813           out.append(TAB);
814           out.append(sf.type);
815           out.append(TAB);
816           out.append(sf.begin);
817           out.append(TAB);
818           out.append(sf.end);
819           out.append(TAB);
820           out.append(sf.score);
821           out.append(TAB);
822
823           int strand = sf.getStrand();
824           out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
825           out.append(TAB);
826
827           String phase = sf.getPhase();
828           out.append(phase == null ? "." : phase);
829
830           // miscellaneous key-values (GFF column 9)
831           String attributes = sf.getAttributes();
832           if (attributes != null)
833           {
834             out.append(TAB).append(attributes);
835           }
836
837           out.append(newline);
838         }
839       }
840     }
841
842     return out.toString();
843   }
844
845   /**
846    * Returns a mapping given list of one or more Align descriptors (exonerate
847    * format)
848    * 
849    * @param alignedRegions
850    *          a list of "Align fromStart toStart fromCount"
851    * @param mapIsFromCdna
852    *          if true, 'from' is dna, else 'from' is protein
853    * @param strand
854    *          either 1 (forward) or -1 (reverse)
855    * @return
856    * @throws IOException
857    */
858   protected MapList constructCodonMappingFromAlign(
859           List<String> alignedRegions, boolean mapIsFromCdna, int strand)
860           throws IOException
861   {
862     if (strand == 0)
863     {
864       throw new IOException(
865               "Invalid strand for a codon mapping (cannot be 0)");
866     }
867     int regions = alignedRegions.size();
868     // arrays to hold [start, end] for each aligned region
869     int[] fromRanges = new int[regions * 2]; // from dna
870     int[] toRanges = new int[regions * 2]; // to protein
871     int fromRangesIndex = 0;
872     int toRangesIndex = 0;
873
874     for (String range : alignedRegions)
875     {
876       /* 
877        * Align mapFromStart mapToStart mapFromCount
878        * e.g. if mapIsFromCdna
879        *     Align 11270 143 120
880        * means:
881        *     120 bases from pos 11270 align to pos 143 in peptide
882        * if !mapIsFromCdna this would instead be
883        *     Align 143 11270 40 
884        */
885       String[] tokens = range.split(" ");
886       if (tokens.length != 3)
887       {
888         throw new IOException("Wrong number of fields for Align");
889       }
890       int fromStart = 0;
891       int toStart = 0;
892       int fromCount = 0;
893       try
894       {
895         fromStart = Integer.parseInt(tokens[0]);
896         toStart = Integer.parseInt(tokens[1]);
897         fromCount = Integer.parseInt(tokens[2]);
898       } catch (NumberFormatException nfe)
899       {
900         throw new IOException(
901                 "Invalid number in Align field: " + nfe.getMessage());
902       }
903
904       /*
905        * Jalview always models from dna to protein, so adjust values if the
906        * GFF mapping is from protein to dna
907        */
908       if (!mapIsFromCdna)
909       {
910         fromCount *= 3;
911         int temp = fromStart;
912         fromStart = toStart;
913         toStart = temp;
914       }
915       fromRanges[fromRangesIndex++] = fromStart;
916       fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
917
918       /*
919        * If a codon has an intron gap, there will be contiguous 'toRanges';
920        * this is handled for us by the MapList constructor. 
921        * (It is not clear that exonerate ever generates this case)  
922        */
923       toRanges[toRangesIndex++] = toStart;
924       toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
925     }
926
927     return new MapList(fromRanges, toRanges, 3, 1);
928   }
929
930   /**
931    * Parse a GFF format feature. This may include creating a 'dummy' sequence to
932    * hold the feature, or for its mapped sequence, or both, to be resolved
933    * either later in the GFF file (##FASTA section), or when the user loads
934    * additional sequences.
935    * 
936    * @param gffColumns
937    * @param alignment
938    * @param relaxedIdMatching
939    * @param newseqs
940    * @return
941    */
942   protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
943           boolean relaxedIdMatching, List<SequenceI> newseqs)
944   {
945     /*
946      * GFF: seqid source type start end score strand phase [attributes]
947      */
948     if (gffColumns.length < 5)
949     {
950       System.err.println("Ignoring GFF feature line with too few columns ("
951               + gffColumns.length + ")");
952       return null;
953     }
954
955     /*
956      * locate referenced sequence in alignment _or_ 
957      * as a forward or external reference (SequenceDummy)
958      */
959     String seqId = gffColumns[0];
960     SequenceI seq = findSequence(seqId, alignment, newseqs,
961             relaxedIdMatching);
962
963     SequenceFeature sf = null;
964     GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
965     if (helper != null)
966     {
967       try
968       {
969         sf = helper.processGff(seq, gffColumns, alignment, newseqs,
970                 relaxedIdMatching);
971         if (sf != null)
972         {
973           seq.addSequenceFeature(sf);
974           while ((seq = alignment.findName(seq, seqId, true)) != null)
975           {
976             seq.addSequenceFeature(new SequenceFeature(sf));
977           }
978         }
979       } catch (IOException e)
980       {
981         System.err.println("GFF parsing failed with: " + e.getMessage());
982         return null;
983       }
984     }
985
986     return seq;
987   }
988
989   /**
990    * Process the 'column 9' data of the GFF file. This is less formally defined,
991    * and its interpretation will vary depending on the tool that has generated
992    * it.
993    * 
994    * @param attributes
995    * @param sf
996    */
997   protected void processGffColumnNine(String attributes, SequenceFeature sf)
998   {
999     sf.setAttributes(attributes);
1000
1001     /*
1002      * Parse attributes in column 9 and add them to the sequence feature's 
1003      * 'otherData' table; use Note as a best proxy for description
1004      */
1005     char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1006     // TODO check we don't break GFF2 values which include commas here
1007     Map<String, List<String>> nameValues = GffHelperBase
1008             .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1009     for (Entry<String, List<String>> attr : nameValues.entrySet())
1010     {
1011       String values = StringUtils.listToDelimitedString(attr.getValue(),
1012               "; ");
1013       sf.setValue(attr.getKey(), values);
1014       if (NOTE.equals(attr.getKey()))
1015       {
1016         sf.setDescription(values);
1017       }
1018     }
1019   }
1020
1021   /**
1022    * After encountering ##fasta in a GFF3 file, process the remainder of the
1023    * file as FAST sequence data. Any placeholder sequences created during
1024    * feature parsing are updated with the actual sequences.
1025    * 
1026    * @param align
1027    * @param newseqs
1028    * @throws IOException
1029    */
1030   protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1031           throws IOException
1032   {
1033     try
1034     {
1035       mark();
1036     } catch (IOException q)
1037     {
1038     }
1039     FastaFile parser = new FastaFile(this);
1040     List<SequenceI> includedseqs = parser.getSeqs();
1041
1042     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1043
1044     /*
1045      * iterate over includedseqs, and replacing matching ones with newseqs
1046      * sequences. Generic iterator not used here because we modify
1047      * includedseqs as we go
1048      */
1049     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1050     {
1051       // search for any dummy seqs that this sequence can be used to update
1052       SequenceI includedSeq = includedseqs.get(p);
1053       SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1054       if (dummyseq != null && dummyseq instanceof SequenceDummy)
1055       {
1056         // probably have the pattern wrong
1057         // idea is that a flyweight proxy for a sequence ID can be created for
1058         // 1. stable reference creation
1059         // 2. addition of annotation
1060         // 3. future replacement by a real sequence
1061         // current pattern is to create SequenceDummy objects - a convenience
1062         // constructor for a Sequence.
1063         // problem is that when promoted to a real sequence, all references
1064         // need to be updated somehow. We avoid that by keeping the same object.
1065         ((SequenceDummy) dummyseq).become(includedSeq);
1066         dummyseq.createDatasetSequence();
1067
1068         /*
1069          * Update mappings so they are now to the dataset sequence
1070          */
1071         for (AlignedCodonFrame mapping : align.getCodonFrames())
1072         {
1073           mapping.updateToDataset(dummyseq);
1074         }
1075
1076         /*
1077          * replace parsed sequence with the realised forward reference
1078          */
1079         includedseqs.set(p, dummyseq);
1080
1081         /*
1082          * and remove from the newseqs list
1083          */
1084         newseqs.remove(dummyseq);
1085       }
1086     }
1087
1088     /*
1089      * finally add sequences to the dataset
1090      */
1091     for (SequenceI seq : includedseqs)
1092     {
1093       // experimental: mapping-based 'alignment' to query sequence
1094       AlignmentUtils.alignSequenceAs(seq, align,
1095               String.valueOf(align.getGapCharacter()), false, true);
1096
1097       // rename sequences if GFF handler requested this
1098       // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1099       SequenceFeature[] sfs = seq.getSequenceFeatures();
1100       if (sfs != null)
1101       {
1102         String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1103         if (newName != null)
1104         {
1105           seq.setName(newName);
1106         }
1107       }
1108       align.addSequence(seq);
1109     }
1110   }
1111
1112   /**
1113    * Process a ## directive
1114    * 
1115    * @param line
1116    * @param gffProps
1117    * @param align
1118    * @param newseqs
1119    * @throws IOException
1120    */
1121   protected void processGffPragma(String line, Map<String, String> gffProps,
1122           AlignmentI align, List<SequenceI> newseqs) throws IOException
1123   {
1124     line = line.trim();
1125     if ("###".equals(line))
1126     {
1127       // close off any open 'forward references'
1128       return;
1129     }
1130
1131     String[] tokens = line.substring(2).split(" ");
1132     String pragma = tokens[0];
1133     String value = tokens.length == 1 ? null : tokens[1];
1134
1135     if ("gff-version".equalsIgnoreCase(pragma))
1136     {
1137       if (value != null)
1138       {
1139         try
1140         {
1141           // value may be e.g. "3.1.2"
1142           gffVersion = Integer.parseInt(value.split("\\.")[0]);
1143         } catch (NumberFormatException e)
1144         {
1145           // ignore
1146         }
1147       }
1148     }
1149     else if ("sequence-region".equalsIgnoreCase(pragma))
1150     {
1151       // could capture <seqid start end> if wanted here
1152     }
1153     else if ("feature-ontology".equalsIgnoreCase(pragma))
1154     {
1155       // should resolve against the specified feature ontology URI
1156     }
1157     else if ("attribute-ontology".equalsIgnoreCase(pragma))
1158     {
1159       // URI of attribute ontology - not currently used in GFF3
1160     }
1161     else if ("source-ontology".equalsIgnoreCase(pragma))
1162     {
1163       // URI of source ontology - not currently used in GFF3
1164     }
1165     else if ("species-build".equalsIgnoreCase(pragma))
1166     {
1167       // save URI of specific NCBI taxon version of annotations
1168       gffProps.put("species-build", value);
1169     }
1170     else if ("fasta".equalsIgnoreCase(pragma))
1171     {
1172       // process the rest of the file as a fasta file and replace any dummy
1173       // sequence IDs
1174       processAsFasta(align, newseqs);
1175     }
1176     else
1177     {
1178       System.err.println("Ignoring unknown pragma: " + line);
1179     }
1180   }
1181 }