JAL-2505 use setter not direct access to sf.description
[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)
126           throws IOException
127   {
128     super(parseImmediately, inFile, type);
129   }
130
131   /**
132    * Parse GFF or sequence features file using case-independent matching,
133    * discarding URLs
134    * 
135    * @param align
136    *          - alignment/dataset containing sequences that are to be annotated
137    * @param colours
138    *          - hashtable to store feature colour definitions
139    * @param removeHTML
140    *          - process html strings into plain text
141    * @return true if features were added
142    */
143   public boolean parse(AlignmentI align,
144           Map<String, FeatureColourI> colours, boolean removeHTML)
145   {
146     return parse(align, colours, removeHTML, false);
147   }
148
149   /**
150    * Extends the default addProperties by also adding peptide-to-cDNA mappings
151    * (if any) derived while parsing a GFF file
152    */
153   @Override
154   public void addProperties(AlignmentI al)
155   {
156     super.addProperties(al);
157     if (dataset != null && dataset.getCodonFrames() != null)
158     {
159       AlignmentI ds = (al.getDataset() == null) ? al : al.getDataset();
160       for (AlignedCodonFrame codons : dataset.getCodonFrames())
161       {
162         ds.addCodonFrame(codons);
163       }
164     }
165   }
166
167   /**
168    * Parse GFF or Jalview format sequence features file
169    * 
170    * @param align
171    *          - alignment/dataset containing sequences that are to be annotated
172    * @param colours
173    *          - hashtable to store feature colour definitions
174    * @param removeHTML
175    *          - process html strings into plain text
176    * @param relaxedIdmatching
177    *          - when true, ID matches to compound sequence IDs are allowed
178    * @return true if features were added
179    */
180   public boolean parse(AlignmentI align,
181           Map<String, FeatureColourI> colours, boolean removeHTML,
182           boolean relaxedIdmatching)
183   {
184     Map<String, String> gffProps = new HashMap<String, String>();
185     /*
186      * keep track of any sequences we try to create from the data
187      */
188     List<SequenceI> newseqs = new ArrayList<SequenceI>();
189
190     String line = null;
191     try
192     {
193       String[] gffColumns;
194       String featureGroup = null;
195
196       while ((line = nextLine()) != null)
197       {
198         // skip comments/process pragmas
199         if (line.length() == 0 || line.startsWith("#"))
200         {
201           if (line.toLowerCase().startsWith("##"))
202           {
203             processGffPragma(line, gffProps, align, newseqs);
204           }
205           continue;
206         }
207
208         gffColumns = line.split("\\t"); // tab as regex
209         if (gffColumns.length == 1)
210         {
211           if (line.trim().equalsIgnoreCase("GFF"))
212           {
213             /*
214              * Jalview features file with appended GFF
215              * assume GFF2 (though it may declare ##gff-version 3)
216              */
217             gffVersion = 2;
218             continue;
219           }
220         }
221
222         if (gffColumns.length > 1 && gffColumns.length < 4)
223         {
224           /*
225            * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
226            * a feature type colour specification
227            */
228           String ft = gffColumns[0];
229           if (ft.equalsIgnoreCase("startgroup"))
230           {
231             featureGroup = gffColumns[1];
232           }
233           else if (ft.equalsIgnoreCase("endgroup"))
234           {
235             // We should check whether this is the current group,
236             // but at present there's no way of showing more than 1 group
237             featureGroup = null;
238           }
239           else
240           {
241             String colscheme = gffColumns[1];
242             FeatureColourI colour = FeatureColour
243                     .parseJalviewFeatureColour(colscheme);
244             if (colour != null)
245             {
246               colours.put(ft, colour);
247             }
248           }
249           continue;
250         }
251
252         /*
253          * if not a comment, GFF pragma, startgroup, endgroup or feature
254          * colour specification, that just leaves a feature details line
255          * in either Jalview or GFF format
256          */
257         if (gffVersion == 0)
258         {
259           parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
260                   relaxedIdmatching, featureGroup);
261         }
262         else
263         {
264           parseGff(gffColumns, align, relaxedIdmatching, newseqs);
265         }
266       }
267       resetMatcher();
268     } catch (Exception ex)
269     {
270       // should report somewhere useful for UI if necessary
271       warningMessage = ((warningMessage == null) ? "" : warningMessage)
272               + "Parsing error at\n" + line;
273       System.out.println("Error parsing feature file: " + ex + "\n" + line);
274       ex.printStackTrace(System.err);
275       resetMatcher();
276       return false;
277     }
278
279     /*
280      * experimental - add any dummy sequences with features to the alignment
281      * - we need them for Ensembl feature extraction - though maybe not otherwise
282      */
283     for (SequenceI newseq : newseqs)
284     {
285       if (newseq.getFeatures().hasFeatures())
286       {
287         align.addSequence(newseq);
288       }
289     }
290     return true;
291   }
292
293   /**
294    * Try to parse a Jalview format feature specification and add it as a
295    * sequence feature to any matching sequences in the alignment. Returns true
296    * if successful (a feature was added), or false if not.
297    * 
298    * @param line
299    * @param gffColumns
300    * @param alignment
301    * @param featureColours
302    * @param removeHTML
303    * @param relaxedIdmatching
304    * @param featureGroup
305    */
306   protected boolean parseJalviewFeature(String line, String[] gffColumns,
307           AlignmentI alignment, Map<String, FeatureColourI> featureColours,
308           boolean removeHTML, boolean relaxedIdMatching, 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,
363             endPos, 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     if (removeHTML)
476     {
477       sf.setDescription(parsed.getNonHtmlContent());
478     }
479
480     for (String link : parsed.getLinks())
481     {
482       sf.addLink(link);
483     }
484
485   }
486
487   /**
488    * generate a features file for seqs includes non-pos features by default.
489    * 
490    * @param sequences
491    *          source of sequence features
492    * @param visible
493    *          hash of feature types and colours
494    * @return features file contents
495    */
496   public String printJalviewFormat(SequenceI[] sequences,
497           Map<String, FeatureColourI> visible)
498   {
499     return printJalviewFormat(sequences, visible, true, true);
500   }
501
502   /**
503    * generate a features file for seqs with colours from visible (if any)
504    * 
505    * @param sequences
506    *          source of features
507    * @param visible
508    *          hash of Colours for each feature type
509    * @param visOnly
510    *          when true only feature types in 'visible' will be output
511    * @param nonpos
512    *          indicates if non-positional features should be output (regardless
513    *          of group or type)
514    * @return features file contents
515    */
516   public String printJalviewFormat(SequenceI[] sequences,
517           Map<String, FeatureColourI> visible, boolean visOnly,
518           boolean nonpos)
519   {
520     StringBuilder out = new StringBuilder(256);
521     boolean featuresGen = false;
522     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
523     {
524       // no point continuing.
525       return "No Features Visible";
526     }
527
528     if (visible != null && visOnly)
529     {
530       // write feature colours only if we're given them and we are generating
531       // viewed features
532       // TODO: decide if feature links should also be written here ?
533       Iterator<String> en = visible.keySet().iterator();
534       while (en.hasNext())
535       {
536         String featureType = en.next().toString();
537         FeatureColourI colour = visible.get(featureType);
538         out.append(colour.toJalviewFormat(featureType)).append(newline);
539       }
540     }
541
542     // Work out which groups are both present and visible
543     List<String> groups = new ArrayList<String>();
544     int groupIndex = 0;
545     boolean isnonpos = false;
546
547     SequenceFeature[] features;
548     for (int i = 0; i < sequences.length; i++)
549     {
550       features = sequences[i].getSequenceFeatures();
551       if (features != null)
552       {
553         for (int j = 0; j < features.length; j++)
554         {
555           isnonpos = features[j].begin == 0 && features[j].end == 0;
556           if ((!nonpos && isnonpos)
557                   || (!isnonpos && visOnly && !visible
558                           .containsKey(features[j].type)))
559           {
560             continue;
561           }
562
563           if (features[j].featureGroup != null
564                   && !groups.contains(features[j].featureGroup))
565           {
566             groups.add(features[j].featureGroup);
567           }
568         }
569       }
570     }
571
572     String group = null;
573     do
574     {
575       if (groups.size() > 0 && groupIndex < groups.size())
576       {
577         group = groups.get(groupIndex);
578         out.append(newline);
579         out.append("STARTGROUP").append(TAB);
580         out.append(group);
581         out.append(newline);
582       }
583       else
584       {
585         group = null;
586       }
587
588       for (int i = 0; i < sequences.length; i++)
589       {
590         features = sequences[i].getSequenceFeatures();
591         if (features != null)
592         {
593           for (SequenceFeature sequenceFeature : features)
594           {
595             isnonpos = sequenceFeature.begin == 0
596                     && sequenceFeature.end == 0;
597             if ((!nonpos && isnonpos)
598                     || (!isnonpos && visOnly && !visible
599                             .containsKey(sequenceFeature.type)))
600             {
601               // skip if feature is nonpos and we ignore them or if we only
602               // output visible and it isn't non-pos and it's not visible
603               continue;
604             }
605
606             if (group != null
607                     && (sequenceFeature.featureGroup == null || !sequenceFeature.featureGroup
608                             .equals(group)))
609             {
610               continue;
611             }
612
613             if (group == null && sequenceFeature.featureGroup != null)
614             {
615               continue;
616             }
617             // we have features to output
618             featuresGen = true;
619             if (sequenceFeature.description == null
620                     || sequenceFeature.description.equals(""))
621             {
622               out.append(sequenceFeature.type).append(TAB);
623             }
624             else
625             {
626               if (sequenceFeature.links != null
627                       && sequenceFeature.getDescription().indexOf("<html>") == -1)
628               {
629                 out.append("<html>");
630               }
631
632               out.append(sequenceFeature.description);
633               if (sequenceFeature.links != null)
634               {
635                 for (int l = 0; l < sequenceFeature.links.size(); l++)
636                 {
637                   String label = sequenceFeature.links.elementAt(l);
638                   String href = label.substring(label.indexOf("|") + 1);
639                   label = label.substring(0, label.indexOf("|"));
640
641                   if (sequenceFeature.description.indexOf(href) == -1)
642                   {
643                     out.append(" <a href=\"" + href + "\">" + label
644                             + "</a>");
645                   }
646                 }
647
648                 if (sequenceFeature.getDescription().indexOf("</html>") == -1)
649                 {
650                   out.append("</html>");
651                 }
652               }
653
654               out.append(TAB);
655             }
656             out.append(sequences[i].getName());
657             out.append("\t-1\t");
658             out.append(sequenceFeature.begin);
659             out.append(TAB);
660             out.append(sequenceFeature.end);
661             out.append(TAB);
662             out.append(sequenceFeature.type);
663             if (!Float.isNaN(sequenceFeature.score))
664             {
665               out.append(TAB);
666               out.append(sequenceFeature.score);
667             }
668             out.append(newline);
669           }
670         }
671       }
672
673       if (group != null)
674       {
675         out.append("ENDGROUP").append(TAB);
676         out.append(group);
677         out.append(newline);
678         groupIndex++;
679       }
680       else
681       {
682         break;
683       }
684
685     } while (groupIndex < groups.size() + 1);
686
687     if (!featuresGen)
688     {
689       return "No Features Visible";
690     }
691
692     return out.toString();
693   }
694
695   /**
696    * Parse method that is called when a GFF file is dragged to the desktop
697    */
698   @Override
699   public void parse()
700   {
701     AlignViewportI av = getViewport();
702     if (av != null)
703     {
704       if (av.getAlignment() != null)
705       {
706         dataset = av.getAlignment().getDataset();
707       }
708       if (dataset == null)
709       {
710         // working in the applet context ?
711         dataset = av.getAlignment();
712       }
713     }
714     else
715     {
716       dataset = new Alignment(new SequenceI[] {});
717     }
718
719     Map<String, FeatureColourI> featureColours = new HashMap<String, FeatureColourI>();
720     boolean parseResult = parse(dataset, featureColours, false, true);
721     if (!parseResult)
722     {
723       // pass error up somehow
724     }
725     if (av != null)
726     {
727       // update viewport with the dataset data ?
728     }
729     else
730     {
731       setSeqs(dataset.getSequencesArray());
732     }
733   }
734
735   /**
736    * Implementation of unused abstract method
737    * 
738    * @return error message
739    */
740   @Override
741   public String print(SequenceI[] sqs, boolean jvsuffix)
742   {
743     System.out.println("Use printGffFormat() or printJalviewFormat()");
744     return null;
745   }
746
747   /**
748    * Returns features output in GFF2 format, including hidden and non-positional
749    * features
750    * 
751    * @param sequences
752    *          the sequences whose features are to be output
753    * @param visible
754    *          a map whose keys are the type names of visible features
755    * @return
756    */
757   public String printGffFormat(SequenceI[] sequences,
758           Map<String, FeatureColourI> visible)
759   {
760     return printGffFormat(sequences, visible, true, true);
761   }
762
763   /**
764    * Returns features output in GFF2 format
765    * 
766    * @param sequences
767    *          the sequences whose features are to be output
768    * @param visible
769    *          a map whose keys are the type names of visible features
770    * @param outputVisibleOnly
771    * @param includeNonPositionalFeatures
772    * @return
773    */
774   public String printGffFormat(SequenceI[] sequences,
775           Map<String, FeatureColourI> visible, boolean outputVisibleOnly,
776           boolean includeNonPositionalFeatures)
777   {
778     StringBuilder out = new StringBuilder(256);
779     int version = gffVersion == 0 ? 2 : gffVersion;
780     out.append(String.format("%s %d\n", GFF_VERSION, version));
781     String source;
782     boolean isnonpos;
783     for (SequenceI seq : sequences)
784     {
785       SequenceFeature[] features = seq.getSequenceFeatures();
786       if (features != null)
787       {
788         for (SequenceFeature sf : features)
789         {
790           isnonpos = sf.begin == 0 && sf.end == 0;
791           if (!includeNonPositionalFeatures && isnonpos)
792           {
793             /*
794              * ignore non-positional features if not wanted
795              */
796             continue;
797           }
798           // TODO why the test !isnonpos here?
799           // what about not visible non-positional features?
800           if (!isnonpos && outputVisibleOnly
801                   && !visible.containsKey(sf.type))
802           {
803             /*
804              * ignore not visible features if not wanted
805              */
806             continue;
807           }
808
809           source = sf.featureGroup;
810           if (source == null)
811           {
812             source = sf.getDescription();
813           }
814
815           out.append(seq.getName());
816           out.append(TAB);
817           out.append(source);
818           out.append(TAB);
819           out.append(sf.type);
820           out.append(TAB);
821           out.append(sf.begin);
822           out.append(TAB);
823           out.append(sf.end);
824           out.append(TAB);
825           out.append(sf.score);
826           out.append(TAB);
827
828           int strand = sf.getStrand();
829           out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
830           out.append(TAB);
831
832           String phase = sf.getPhase();
833           out.append(phase == null ? "." : phase);
834
835           // miscellaneous key-values (GFF column 9)
836           String attributes = sf.getAttributes();
837           if (attributes != null)
838           {
839             out.append(TAB).append(attributes);
840           }
841
842           out.append(newline);
843         }
844       }
845     }
846
847     return out.toString();
848   }
849
850   /**
851    * Returns a mapping given list of one or more Align descriptors (exonerate
852    * format)
853    * 
854    * @param alignedRegions
855    *          a list of "Align fromStart toStart fromCount"
856    * @param mapIsFromCdna
857    *          if true, 'from' is dna, else 'from' is protein
858    * @param strand
859    *          either 1 (forward) or -1 (reverse)
860    * @return
861    * @throws IOException
862    */
863   protected MapList constructCodonMappingFromAlign(
864           List<String> alignedRegions, boolean mapIsFromCdna, int strand)
865           throws IOException
866   {
867     if (strand == 0)
868     {
869       throw new IOException(
870               "Invalid strand for a codon mapping (cannot be 0)");
871     }
872     int regions = alignedRegions.size();
873     // arrays to hold [start, end] for each aligned region
874     int[] fromRanges = new int[regions * 2]; // from dna
875     int[] toRanges = new int[regions * 2]; // to protein
876     int fromRangesIndex = 0;
877     int toRangesIndex = 0;
878
879     for (String range : alignedRegions)
880     {
881       /* 
882        * Align mapFromStart mapToStart mapFromCount
883        * e.g. if mapIsFromCdna
884        *     Align 11270 143 120
885        * means:
886        *     120 bases from pos 11270 align to pos 143 in peptide
887        * if !mapIsFromCdna this would instead be
888        *     Align 143 11270 40 
889        */
890       String[] tokens = range.split(" ");
891       if (tokens.length != 3)
892       {
893         throw new IOException("Wrong number of fields for Align");
894       }
895       int fromStart = 0;
896       int toStart = 0;
897       int fromCount = 0;
898       try
899       {
900         fromStart = Integer.parseInt(tokens[0]);
901         toStart = Integer.parseInt(tokens[1]);
902         fromCount = Integer.parseInt(tokens[2]);
903       } catch (NumberFormatException nfe)
904       {
905         throw new IOException("Invalid number in Align field: "
906                 + nfe.getMessage());
907       }
908
909       /*
910        * Jalview always models from dna to protein, so adjust values if the
911        * GFF mapping is from protein to dna
912        */
913       if (!mapIsFromCdna)
914       {
915         fromCount *= 3;
916         int temp = fromStart;
917         fromStart = toStart;
918         toStart = temp;
919       }
920       fromRanges[fromRangesIndex++] = fromStart;
921       fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
922
923       /*
924        * If a codon has an intron gap, there will be contiguous 'toRanges';
925        * this is handled for us by the MapList constructor. 
926        * (It is not clear that exonerate ever generates this case)  
927        */
928       toRanges[toRangesIndex++] = toStart;
929       toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
930     }
931
932     return new MapList(fromRanges, toRanges, 3, 1);
933   }
934
935   /**
936    * Parse a GFF format feature. This may include creating a 'dummy' sequence to
937    * hold the feature, or for its mapped sequence, or both, to be resolved
938    * either later in the GFF file (##FASTA section), or when the user loads
939    * additional sequences.
940    * 
941    * @param gffColumns
942    * @param alignment
943    * @param relaxedIdMatching
944    * @param newseqs
945    * @return
946    */
947   protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
948           boolean relaxedIdMatching, List<SequenceI> newseqs)
949   {
950     /*
951      * GFF: seqid source type start end score strand phase [attributes]
952      */
953     if (gffColumns.length < 5)
954     {
955       System.err.println("Ignoring GFF feature line with too few columns ("
956               + gffColumns.length + ")");
957       return null;
958     }
959
960     /*
961      * locate referenced sequence in alignment _or_ 
962      * as a forward or external reference (SequenceDummy)
963      */
964     String seqId = gffColumns[0];
965     SequenceI seq = findSequence(seqId, alignment, newseqs,
966             relaxedIdMatching);
967
968     SequenceFeature sf = null;
969     GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
970     if (helper != null)
971     {
972       try
973       {
974         sf = helper.processGff(seq, gffColumns, alignment, newseqs,
975                 relaxedIdMatching);
976         if (sf != null)
977         {
978           seq.addSequenceFeature(sf);
979           while ((seq = alignment.findName(seq, seqId, true)) != null)
980           {
981             seq.addSequenceFeature(new SequenceFeature(sf));
982           }
983         }
984       } catch (IOException e)
985       {
986         System.err.println("GFF parsing failed with: " + e.getMessage());
987         return null;
988       }
989     }
990
991     return seq;
992   }
993
994   /**
995    * Process the 'column 9' data of the GFF file. This is less formally defined,
996    * and its interpretation will vary depending on the tool that has generated
997    * it.
998    * 
999    * @param attributes
1000    * @param sf
1001    */
1002   protected void processGffColumnNine(String attributes, SequenceFeature sf)
1003   {
1004     sf.setAttributes(attributes);
1005
1006     /*
1007      * Parse attributes in column 9 and add them to the sequence feature's 
1008      * 'otherData' table; use Note as a best proxy for description
1009      */
1010     char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1011     // TODO check we don't break GFF2 values which include commas here
1012     Map<String, List<String>> nameValues = GffHelperBase
1013             .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1014     for (Entry<String, List<String>> attr : nameValues.entrySet())
1015     {
1016       String values = StringUtils.listToDelimitedString(attr.getValue(),
1017               "; ");
1018       sf.setValue(attr.getKey(), values);
1019       if (NOTE.equals(attr.getKey()))
1020       {
1021         sf.setDescription(values);
1022       }
1023     }
1024   }
1025
1026   /**
1027    * After encountering ##fasta in a GFF3 file, process the remainder of the
1028    * file as FAST sequence data. Any placeholder sequences created during
1029    * feature parsing are updated with the actual sequences.
1030    * 
1031    * @param align
1032    * @param newseqs
1033    * @throws IOException
1034    */
1035   protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1036           throws IOException
1037   {
1038     try
1039     {
1040       mark();
1041     } catch (IOException q)
1042     {
1043     }
1044     FastaFile parser = new FastaFile(this);
1045     List<SequenceI> includedseqs = parser.getSeqs();
1046
1047     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1048
1049     /*
1050      * iterate over includedseqs, and replacing matching ones with newseqs
1051      * sequences. Generic iterator not used here because we modify
1052      * includedseqs as we go
1053      */
1054     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1055     {
1056       // search for any dummy seqs that this sequence can be used to update
1057       SequenceI includedSeq = includedseqs.get(p);
1058       SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1059       if (dummyseq != null && dummyseq instanceof SequenceDummy)
1060       {
1061         // probably have the pattern wrong
1062         // idea is that a flyweight proxy for a sequence ID can be created for
1063         // 1. stable reference creation
1064         // 2. addition of annotation
1065         // 3. future replacement by a real sequence
1066         // current pattern is to create SequenceDummy objects - a convenience
1067         // constructor for a Sequence.
1068         // problem is that when promoted to a real sequence, all references
1069         // need to be updated somehow. We avoid that by keeping the same object.
1070         ((SequenceDummy) dummyseq).become(includedSeq);
1071         dummyseq.createDatasetSequence();
1072
1073         /*
1074          * Update mappings so they are now to the dataset sequence
1075          */
1076         for (AlignedCodonFrame mapping : align.getCodonFrames())
1077         {
1078           mapping.updateToDataset(dummyseq);
1079         }
1080
1081         /*
1082          * replace parsed sequence with the realised forward reference
1083          */
1084         includedseqs.set(p, dummyseq);
1085
1086         /*
1087          * and remove from the newseqs list
1088          */
1089         newseqs.remove(dummyseq);
1090       }
1091     }
1092
1093     /*
1094      * finally add sequences to the dataset
1095      */
1096     for (SequenceI seq : includedseqs)
1097     {
1098       // experimental: mapping-based 'alignment' to query sequence
1099       AlignmentUtils.alignSequenceAs(seq, align,
1100               String.valueOf(align.getGapCharacter()), false, true);
1101
1102       // rename sequences if GFF handler requested this
1103       // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1104       SequenceFeature[] sfs = seq.getSequenceFeatures();
1105       if (sfs != null)
1106       {
1107         String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1108         if (newName != null)
1109         {
1110           seq.setName(newName);
1111         }
1112       }
1113       align.addSequence(seq);
1114     }
1115   }
1116
1117   /**
1118    * Process a ## directive
1119    * 
1120    * @param line
1121    * @param gffProps
1122    * @param align
1123    * @param newseqs
1124    * @throws IOException
1125    */
1126   protected void processGffPragma(String line,
1127           Map<String, String> gffProps, AlignmentI align,
1128           List<SequenceI> newseqs) throws IOException
1129   {
1130     line = line.trim();
1131     if ("###".equals(line))
1132     {
1133       // close off any open 'forward references'
1134       return;
1135     }
1136
1137     String[] tokens = line.substring(2).split(" ");
1138     String pragma = tokens[0];
1139     String value = tokens.length == 1 ? null : tokens[1];
1140
1141     if ("gff-version".equalsIgnoreCase(pragma))
1142     {
1143       if (value != null)
1144       {
1145         try
1146         {
1147           // value may be e.g. "3.1.2"
1148           gffVersion = Integer.parseInt(value.split("\\.")[0]);
1149         } catch (NumberFormatException e)
1150         {
1151           // ignore
1152         }
1153       }
1154     }
1155     else if ("sequence-region".equalsIgnoreCase(pragma))
1156     {
1157       // could capture <seqid start end> if wanted here
1158     }
1159     else if ("feature-ontology".equalsIgnoreCase(pragma))
1160     {
1161       // should resolve against the specified feature ontology URI
1162     }
1163     else if ("attribute-ontology".equalsIgnoreCase(pragma))
1164     {
1165       // URI of attribute ontology - not currently used in GFF3
1166     }
1167     else if ("source-ontology".equalsIgnoreCase(pragma))
1168     {
1169       // URI of source ontology - not currently used in GFF3
1170     }
1171     else if ("species-build".equalsIgnoreCase(pragma))
1172     {
1173       // save URI of specific NCBI taxon version of annotations
1174       gffProps.put("species-build", value);
1175     }
1176     else if ("fasta".equalsIgnoreCase(pragma))
1177     {
1178       // process the rest of the file as a fasta file and replace any dummy
1179       // sequence IDs
1180       processAsFasta(align, newseqs);
1181     }
1182     else
1183     {
1184       System.err.println("Ignoring unknown pragma: " + line);
1185     }
1186   }
1187 }