Merge branch 'develop' into spike/JAL-4047/JAL-4048_columns_in_sequenceID
[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 java.awt.Color;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Locale;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.TreeMap;
35
36 import jalview.analysis.AlignmentUtils;
37 import jalview.analysis.SequenceIdMatcher;
38 import jalview.api.AlignViewportI;
39 import jalview.api.FeatureColourI;
40 import jalview.api.FeatureRenderer;
41 import jalview.api.FeaturesSourceI;
42 import jalview.datamodel.AlignedCodonFrame;
43 import jalview.datamodel.Alignment;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.MappedFeatures;
46 import jalview.datamodel.SequenceDummy;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceI;
49 import jalview.datamodel.features.FeatureMatcherSet;
50 import jalview.datamodel.features.FeatureMatcherSetI;
51 import jalview.gui.Desktop;
52 import jalview.io.gff.GffHelperFactory;
53 import jalview.io.gff.GffHelperI;
54 import jalview.schemes.FeatureColour;
55 import jalview.util.ColorUtils;
56 import jalview.util.MapList;
57 import jalview.util.ParseHtmlBodyAndLinks;
58 import jalview.util.StringUtils;
59
60 /**
61  * Parses and writes features files, which may be in Jalview, GFF2 or GFF3
62  * format. These are tab-delimited formats but with differences in the use of
63  * columns.
64  * 
65  * A Jalview feature file may define feature colours and then declare that the
66  * remainder of the file is in GFF format with the line 'GFF'.
67  * 
68  * GFF3 files may include alignment mappings for features, which Jalview will
69  * attempt to model, and may include sequence data following a ##FASTA line.
70  * 
71  * 
72  * @author AMW
73  * @author jbprocter
74  * @author gmcarstairs
75  */
76 public class FeaturesFile extends AlignFile implements FeaturesSourceI
77 {
78   private static final String EQUALS = "=";
79
80   private static final String TAB_REGEX = "\\t";
81
82   private static final String STARTGROUP = "STARTGROUP";
83
84   private static final String ENDGROUP = "ENDGROUP";
85
86   private static final String STARTFILTERS = "STARTFILTERS";
87
88   private static final String ENDFILTERS = "ENDFILTERS";
89
90   private static final String ID_NOT_SPECIFIED = "ID_NOT_SPECIFIED";
91
92   protected static final String GFF_VERSION = "##gff-version";
93
94   private AlignmentI lastmatchedAl = null;
95
96   private SequenceIdMatcher matcher = null;
97
98   protected AlignmentI dataset;
99
100   protected int gffVersion;
101
102   /**
103    * Creates a new FeaturesFile object.
104    */
105   public FeaturesFile()
106   {
107   }
108
109   /**
110    * Constructor which does not parse the file immediately
111    * 
112    * @param file
113    *          File or String filename
114    * @param paste
115    * @throws IOException
116    */
117   public FeaturesFile(Object file, DataSourceType paste) throws IOException
118   {
119     super(false, file, paste);
120   }
121
122   /**
123    * @param source
124    * @throws IOException
125    */
126   public FeaturesFile(FileParse source) throws IOException
127   {
128     super(source);
129   }
130
131   /**
132    * Constructor that optionally parses the file immediately
133    * 
134    * @param parseImmediately
135    * @param file
136    * @param type
137    * @throws IOException
138    */
139   public FeaturesFile(boolean parseImmediately, Object file,
140           DataSourceType type) throws IOException
141   {
142     super(parseImmediately, file, 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    *          - map 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     return parse(align, colours, null, removeHTML, relaxedIdmatching);
199   }
200
201   /**
202    * Parse GFF or Jalview format sequence features file
203    * 
204    * @param align
205    *          - alignment/dataset containing sequences that are to be annotated
206    * @param colours
207    *          - map to store feature colour definitions
208    * @param filters
209    *          - map to store feature filter definitions
210    * @param removeHTML
211    *          - process html strings into plain text
212    * @param relaxedIdmatching
213    *          - when true, ID matches to compound sequence IDs are allowed
214    * @return true if features were added
215    */
216   public boolean parse(AlignmentI align,
217           Map<String, FeatureColourI> colours,
218           Map<String, FeatureMatcherSetI> filters, boolean removeHTML,
219           boolean relaxedIdmatching)
220   {
221     Map<String, String> gffProps = new HashMap<>();
222     /*
223      * keep track of any sequences we try to create from the data
224      */
225     List<SequenceI> newseqs = new ArrayList<>();
226
227     String line = null;
228     try
229     {
230       String[] gffColumns;
231       String featureGroup = null;
232
233       while ((line = nextLine()) != null)
234       {
235         // skip comments/process pragmas
236         if (line.length() == 0 || line.startsWith("#"))
237         {
238           if (line.toLowerCase(Locale.ROOT).startsWith("##"))
239           {
240             processGffPragma(line, gffProps, align, newseqs);
241           }
242           continue;
243         }
244
245         gffColumns = line.split(TAB_REGEX);
246         if (gffColumns.length == 1)
247         {
248           if (line.trim().equalsIgnoreCase("GFF"))
249           {
250             /*
251              * Jalview features file with appended GFF
252              * assume GFF2 (though it may declare ##gff-version 3)
253              */
254             gffVersion = 2;
255             continue;
256           }
257         }
258
259         if (gffColumns.length > 0 && gffColumns.length < 4)
260         {
261           /*
262            * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
263            * a feature type colour specification
264            */
265           String ft = gffColumns[0];
266           if (ft.equalsIgnoreCase(STARTFILTERS))
267           {
268             parseFilters(filters);
269             continue;
270           }
271           if (ft.equalsIgnoreCase(STARTGROUP))
272           {
273             featureGroup = gffColumns[1];
274           }
275           else if (ft.equalsIgnoreCase(ENDGROUP))
276           {
277             // We should check whether this is the current group,
278             // but at present there's no way of showing more than 1 group
279             featureGroup = null;
280           }
281           else
282           {
283             String colscheme = gffColumns[1];
284             FeatureColourI colour = FeatureColour
285                     .parseJalviewFeatureColour(colscheme);
286             if (colour != null)
287             {
288               colours.put(ft, colour);
289             }
290           }
291           continue;
292         }
293
294         /*
295          * if not a comment, GFF pragma, startgroup, endgroup or feature
296          * colour specification, that just leaves a feature details line
297          * in either Jalview or GFF format
298          */
299         if (gffVersion == 0)
300         {
301           parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
302                   relaxedIdmatching, featureGroup);
303         }
304         else
305         {
306           parseGff(gffColumns, align, relaxedIdmatching, newseqs);
307         }
308       }
309       resetMatcher();
310     } catch (Exception ex)
311     {
312       // should report somewhere useful for UI if necessary
313       warningMessage = ((warningMessage == null) ? "" : warningMessage)
314               + "Parsing error at\n" + line;
315       jalview.bin.Console.outPrintln("Error parsing feature file: " + ex + "\n" + line);
316       ex.printStackTrace(System.err);
317       resetMatcher();
318       return false;
319     }
320
321     /*
322      * experimental - add any dummy sequences with features to the alignment
323      * - we need them for Ensembl feature extraction - though maybe not otherwise
324      */
325     for (SequenceI newseq : newseqs)
326     {
327       if (newseq.getFeatures().hasFeatures())
328       {
329         align.addSequence(newseq);
330       }
331     }
332     return true;
333   }
334
335   /**
336    * Reads input lines from STARTFILTERS to ENDFILTERS and adds a feature type
337    * filter to the map for each line parsed. After exit from this method,
338    * nextLine() should return the line after ENDFILTERS (or we are already at
339    * end of file if ENDFILTERS was missing).
340    * 
341    * @param filters
342    * @throws IOException
343    */
344   protected void parseFilters(Map<String, FeatureMatcherSetI> filters)
345           throws IOException
346   {
347     String line;
348     while ((line = nextLine()) != null)
349     {
350       if (line.toUpperCase(Locale.ROOT).startsWith(ENDFILTERS))
351       {
352         return;
353       }
354       String[] tokens = line.split(TAB_REGEX);
355       if (tokens.length != 2)
356       {
357         jalview.bin.Console.errPrintln(String.format("Invalid token count %d for %d",
358                 tokens.length, line));
359       }
360       else
361       {
362         String featureType = tokens[0];
363         FeatureMatcherSetI fm = FeatureMatcherSet.fromString(tokens[1]);
364         if (fm != null && filters != null)
365         {
366           filters.put(featureType, fm);
367         }
368       }
369     }
370   }
371
372   /**
373    * Try to parse a Jalview format feature specification and add it as a
374    * sequence feature to any matching sequences in the alignment. Returns true
375    * if successful (a feature was added), or false if not.
376    * 
377    * @param line
378    * @param gffColumns
379    * @param alignment
380    * @param featureColours
381    * @param removeHTML
382    * @param relaxedIdmatching
383    * @param featureGroup
384    */
385   protected boolean parseJalviewFeature(String line, String[] gffColumns,
386           AlignmentI alignment, Map<String, FeatureColourI> featureColours,
387           boolean removeHTML, boolean relaxedIdMatching,
388           String featureGroup)
389   {
390     /*
391      * tokens: description seqid seqIndex start end type [score]
392      */
393     if (gffColumns.length < 6)
394     {
395       jalview.bin.Console.errPrintln("Ignoring feature line '" + line
396               + "' with too few columns (" + gffColumns.length + ")");
397       return false;
398     }
399     String desc = gffColumns[0];
400     String seqId = gffColumns[1];
401     SequenceI seq = findSequence(seqId, alignment, null, relaxedIdMatching);
402
403     if (!ID_NOT_SPECIFIED.equals(seqId))
404     {
405       seq = findSequence(seqId, alignment, null, relaxedIdMatching);
406     }
407     else
408     {
409       seqId = null;
410       seq = null;
411       String seqIndex = gffColumns[2];
412       try
413       {
414         int idx = Integer.parseInt(seqIndex);
415         seq = alignment.getSequenceAt(idx);
416       } catch (NumberFormatException ex)
417       {
418         jalview.bin.Console.errPrintln("Invalid sequence index: " + seqIndex);
419       }
420     }
421
422     if (seq == null)
423     {
424       jalview.bin.Console.outPrintln("Sequence not found: " + line);
425       return false;
426     }
427
428     int startPos = Integer.parseInt(gffColumns[3]);
429     int endPos = Integer.parseInt(gffColumns[4]);
430
431     String ft = gffColumns[5];
432
433     if (!featureColours.containsKey(ft))
434     {
435       /* 
436        * Perhaps an old style groups file with no colours -
437        * synthesize a colour from the feature type
438        */
439       Color colour = ColorUtils.createColourFromName(ft);
440       featureColours.put(ft, new FeatureColour(colour));
441     }
442     SequenceFeature sf = null;
443     if (gffColumns.length > 6)
444     {
445       float score = Float.NaN;
446       try
447       {
448         score = Float.valueOf(gffColumns[6]).floatValue();
449       } catch (NumberFormatException ex)
450       {
451         sf = new SequenceFeature(ft, desc, startPos, endPos, featureGroup);
452       }
453       sf = new SequenceFeature(ft, desc, startPos, endPos, score,
454               featureGroup);
455     }
456     else
457     {
458       sf = new SequenceFeature(ft, desc, startPos, endPos, featureGroup);
459     }
460
461     parseDescriptionHTML(sf, removeHTML);
462
463     seq.addSequenceFeature(sf);
464
465     while (seqId != null
466             && (seq = alignment.findName(seq, seqId, false)) != null)
467     {
468       seq.addSequenceFeature(new SequenceFeature(sf));
469     }
470     return true;
471   }
472
473   /**
474    * clear any temporary handles used to speed up ID matching
475    */
476   protected void resetMatcher()
477   {
478     lastmatchedAl = null;
479     matcher = null;
480   }
481
482   /**
483    * Returns a sequence matching the given id, as follows
484    * <ul>
485    * <li>strict matching is on exact sequence name</li>
486    * <li>relaxed matching allows matching on a token within the sequence name,
487    * or a dbxref</li>
488    * <li>first tries to find a match in the alignment sequences</li>
489    * <li>else tries to find a match in the new sequences already generated while
490    * parsing the features file</li>
491    * <li>else creates a new placeholder sequence, adds it to the new sequences
492    * list, and returns it</li>
493    * </ul>
494    * 
495    * @param seqId
496    * @param align
497    * @param newseqs
498    * @param relaxedIdMatching
499    * 
500    * @return
501    */
502   protected SequenceI findSequence(String seqId, AlignmentI align,
503           List<SequenceI> newseqs, boolean relaxedIdMatching)
504   {
505     // TODO encapsulate in SequenceIdMatcher, share the matcher
506     // with the GffHelper (removing code duplication)
507     SequenceI match = null;
508     if (relaxedIdMatching)
509     {
510       if (lastmatchedAl != align)
511       {
512         lastmatchedAl = align;
513         matcher = new SequenceIdMatcher(align.getSequencesArray());
514         if (newseqs != null)
515         {
516           matcher.addAll(newseqs);
517         }
518       }
519       match = matcher.findIdMatch(seqId);
520     }
521     else
522     {
523       match = align.findName(seqId, true);
524       if (match == null && newseqs != null)
525       {
526         for (SequenceI m : newseqs)
527         {
528           if (seqId.equals(m.getName()))
529           {
530             return m;
531           }
532         }
533       }
534
535     }
536     if (match == null && newseqs != null)
537     {
538       match = new SequenceDummy(seqId);
539       if (relaxedIdMatching)
540       {
541         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
542       }
543       // add dummy sequence to the newseqs list
544       newseqs.add(match);
545     }
546     return match;
547   }
548
549   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
550   {
551     if (sf.getDescription() == null)
552     {
553       return;
554     }
555     ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
556             sf.getDescription(), removeHTML, newline);
557
558     if (removeHTML)
559     {
560       sf.setDescription(parsed.getNonHtmlContent());
561     }
562
563     for (String link : parsed.getLinks())
564     {
565       sf.addLink(link);
566     }
567   }
568
569   /**
570    * Returns contents of a Jalview format features file, for visible features,
571    * as filtered by type and group. Features with a null group are displayed if
572    * their feature type is visible. Non-positional features may optionally be
573    * included (with no check on type or group).
574    * 
575    * @param sequences
576    * @param fr
577    * @param includeNonPositional
578    *          if true, include non-positional features (regardless of group or
579    *          type)
580    * @param includeComplement
581    *          if true, include visible complementary (CDS/protein) positional
582    *          features, with locations converted to local sequence coordinates
583    * @return
584    */
585   public String printJalviewFormat(SequenceI[] sequences,
586           FeatureRenderer fr, boolean includeNonPositional,
587           boolean includeComplement)
588   {
589     Map<String, FeatureColourI> visibleColours = fr
590             .getDisplayedFeatureCols();
591     Map<String, FeatureMatcherSetI> featureFilters = fr.getFeatureFilters();
592
593     /*
594      * write out feature colours (if we know them)
595      */
596     // TODO: decide if feature links should also be written here ?
597     StringBuilder out = new StringBuilder(256);
598     if (visibleColours != null)
599     {
600       for (Entry<String, FeatureColourI> featureColour : visibleColours
601               .entrySet())
602       {
603         FeatureColourI colour = featureColour.getValue();
604         out.append(colour.toJalviewFormat(featureColour.getKey()))
605                 .append(newline);
606       }
607     }
608
609     String[] types = visibleColours == null ? new String[0]
610             : visibleColours.keySet()
611                     .toArray(new String[visibleColours.keySet().size()]);
612
613     /*
614      * feature filters if any
615      */
616     outputFeatureFilters(out, visibleColours, featureFilters);
617
618     /*
619      * output features within groups
620      */
621     int count = outputFeaturesByGroup(out, fr, types, sequences,
622             includeNonPositional);
623
624     if (includeComplement)
625     {
626       count += outputComplementFeatures(out, fr, sequences);
627     }
628
629     return count > 0 ? out.toString() : "No Features Visible";
630   }
631
632   /**
633    * Outputs any visible complementary (CDS/peptide) positional features as
634    * Jalview format, within feature group. The coordinates of the linked
635    * features are converted to the corresponding positions of the local
636    * sequences.
637    * 
638    * @param out
639    * @param fr
640    * @param sequences
641    * @return
642    */
643   private int outputComplementFeatures(StringBuilder out,
644           FeatureRenderer fr, SequenceI[] sequences)
645   {
646     AlignViewportI comp = fr.getViewport().getCodingComplement();
647     FeatureRenderer fr2 = Desktop.getAlignFrameFor(comp)
648             .getFeatureRenderer();
649
650     /*
651      * bin features by feature group and sequence
652      */
653     Map<String, Map<String, List<SequenceFeature>>> map = new TreeMap<>(
654             String.CASE_INSENSITIVE_ORDER);
655     int count = 0;
656
657     for (SequenceI seq : sequences)
658     {
659       /*
660        * find complementary features
661        */
662       List<SequenceFeature> complementary = findComplementaryFeatures(seq,
663               fr2);
664       String seqName = seq.getName();
665
666       for (SequenceFeature sf : complementary)
667       {
668         String group = sf.getFeatureGroup();
669         if (!map.containsKey(group))
670         {
671           map.put(group, new LinkedHashMap<>()); // preserves sequence order
672         }
673         Map<String, List<SequenceFeature>> groupFeatures = map.get(group);
674         if (!groupFeatures.containsKey(seqName))
675         {
676           groupFeatures.put(seqName, new ArrayList<>());
677         }
678         List<SequenceFeature> foundFeatures = groupFeatures.get(seqName);
679         foundFeatures.add(sf);
680         count++;
681       }
682     }
683
684     /*
685      * output features by group
686      */
687     for (Entry<String, Map<String, List<SequenceFeature>>> groupFeatures : map
688             .entrySet())
689     {
690       out.append(newline);
691       String group = groupFeatures.getKey();
692       if (!"".equals(group))
693       {
694         out.append(STARTGROUP).append(TAB).append(group).append(newline);
695       }
696       Map<String, List<SequenceFeature>> seqFeaturesMap = groupFeatures
697               .getValue();
698       for (Entry<String, List<SequenceFeature>> seqFeatures : seqFeaturesMap
699               .entrySet())
700       {
701         String sequenceName = seqFeatures.getKey();
702         for (SequenceFeature sf : seqFeatures.getValue())
703         {
704           formatJalviewFeature(out, sequenceName, sf);
705         }
706       }
707       if (!"".equals(group))
708       {
709         out.append(ENDGROUP).append(TAB).append(group).append(newline);
710       }
711     }
712
713     return count;
714   }
715
716   /**
717    * Answers a list of mapped features visible in the (CDS/protein) complement,
718    * with feature positions translated to local sequence coordinates
719    * 
720    * @param seq
721    * @param fr2
722    * @return
723    */
724   protected List<SequenceFeature> findComplementaryFeatures(SequenceI seq,
725           FeatureRenderer fr2)
726   {
727     /*
728      * avoid duplication of features (e.g. peptide feature 
729      * at all 3 mapped codon positions)
730      */
731     List<SequenceFeature> found = new ArrayList<>();
732     List<SequenceFeature> complementary = new ArrayList<>();
733
734     for (int pos = seq.getStart(); pos <= seq.getEnd(); pos++)
735     {
736       MappedFeatures mf = fr2.findComplementFeaturesAtResidue(seq, pos);
737
738       if (mf != null)
739       {
740         for (SequenceFeature sf : mf.features)
741         {
742           /*
743            * make a virtual feature with local coordinates
744            */
745           if (!found.contains(sf))
746           {
747             String group = sf.getFeatureGroup();
748             if (group == null)
749             {
750               group = "";
751             }
752             found.add(sf);
753             int begin = sf.getBegin();
754             int end = sf.getEnd();
755             int[] range = mf.getMappedPositions(begin, end);
756             SequenceFeature sf2 = new SequenceFeature(sf, range[0],
757                     range[1], group, sf.getScore());
758             complementary.add(sf2);
759           }
760         }
761       }
762     }
763
764     return complementary;
765   }
766
767   /**
768    * Outputs any feature filters defined for visible feature types, sandwiched
769    * by STARTFILTERS and ENDFILTERS lines
770    * 
771    * @param out
772    * @param visible
773    * @param featureFilters
774    */
775   void outputFeatureFilters(StringBuilder out,
776           Map<String, FeatureColourI> visible,
777           Map<String, FeatureMatcherSetI> featureFilters)
778   {
779     if (visible == null || featureFilters == null
780             || featureFilters.isEmpty())
781     {
782       return;
783     }
784
785     boolean first = true;
786     for (String featureType : visible.keySet())
787     {
788       FeatureMatcherSetI filter = featureFilters.get(featureType);
789       if (filter != null)
790       {
791         if (first)
792         {
793           first = false;
794           out.append(newline).append(STARTFILTERS).append(newline);
795         }
796         out.append(featureType).append(TAB).append(filter.toStableString())
797                 .append(newline);
798       }
799     }
800     if (!first)
801     {
802       out.append(ENDFILTERS).append(newline);
803     }
804
805   }
806
807   /**
808    * Appends output of visible sequence features within feature groups to the
809    * output buffer. Groups other than the null or empty group are sandwiched by
810    * STARTGROUP and ENDGROUP lines. Answers the number of features written.
811    * 
812    * @param out
813    * @param fr
814    * @param featureTypes
815    * @param sequences
816    * @param includeNonPositional
817    * @return
818    */
819   private int outputFeaturesByGroup(StringBuilder out, FeatureRenderer fr,
820           String[] featureTypes, SequenceI[] sequences,
821           boolean includeNonPositional)
822   {
823     List<String> featureGroups = fr.getFeatureGroups();
824
825     /*
826      * sort groups alphabetically, and ensure that features with a
827      * null or empty group are output after those in named groups
828      */
829     List<String> sortedGroups = new ArrayList<>(featureGroups);
830     sortedGroups.remove(null);
831     sortedGroups.remove("");
832     Collections.sort(sortedGroups);
833     sortedGroups.add(null);
834     sortedGroups.add("");
835
836     int count = 0;
837     List<String> visibleGroups = fr.getDisplayedFeatureGroups();
838
839     /*
840      * loop over all groups (may be visible or not);
841      * non-positional features are output even if group is not visible
842      */
843     for (String group : sortedGroups)
844     {
845       boolean firstInGroup = true;
846       boolean isNullGroup = group == null || "".equals(group);
847
848       for (int i = 0; i < sequences.length; i++)
849       {
850         String sequenceName = sequences[i].getName();
851         List<SequenceFeature> features = new ArrayList<>();
852
853         /*
854          * get any non-positional features in this group, if wanted
855          * (for any feature type, whether visible or not)
856          */
857         if (includeNonPositional)
858         {
859           features.addAll(sequences[i].getFeatures()
860                   .getFeaturesForGroup(false, group));
861         }
862
863         /*
864          * add positional features for visible feature types, but
865          * (for named groups) only if feature group is visible
866          */
867         if (featureTypes.length > 0
868                 && (isNullGroup || visibleGroups.contains(group)))
869         {
870           features.addAll(sequences[i].getFeatures()
871                   .getFeaturesForGroup(true, group, featureTypes));
872         }
873
874         for (SequenceFeature sf : features)
875         {
876           if (sf.isNonPositional() || fr.isVisible(sf))
877           {
878             count++;
879             if (firstInGroup)
880             {
881               out.append(newline);
882               if (!isNullGroup)
883               {
884                 out.append(STARTGROUP).append(TAB).append(group)
885                         .append(newline);
886               }
887             }
888             firstInGroup = false;
889             formatJalviewFeature(out, sequenceName, sf);
890           }
891         }
892       }
893
894       if (!isNullGroup && !firstInGroup)
895       {
896         out.append(ENDGROUP).append(TAB).append(group).append(newline);
897       }
898     }
899     return count;
900   }
901
902   /**
903    * Formats one feature in Jalview format and appends to the string buffer
904    * 
905    * @param out
906    * @param sequenceName
907    * @param sequenceFeature
908    */
909   protected void formatJalviewFeature(StringBuilder out,
910           String sequenceName, SequenceFeature sequenceFeature)
911   {
912     if (sequenceFeature.description == null
913             || sequenceFeature.description.equals(""))
914     {
915       out.append(sequenceFeature.type).append(TAB);
916     }
917     else
918     {
919       if (sequenceFeature.links != null
920               && sequenceFeature.getDescription().indexOf("<html>") == -1)
921       {
922         out.append("<html>");
923       }
924
925       out.append(sequenceFeature.description);
926       if (sequenceFeature.links != null)
927       {
928         for (int l = 0; l < sequenceFeature.links.size(); l++)
929         {
930           String label = sequenceFeature.links.elementAt(l);
931           String href = label.substring(label.indexOf("|") + 1);
932           label = label.substring(0, label.indexOf("|"));
933
934           if (sequenceFeature.description.indexOf(href) == -1)
935           {
936             out.append(" <a href=\"").append(href).append("\">")
937                     .append(label).append("</a>");
938           }
939         }
940
941         if (sequenceFeature.getDescription().indexOf("</html>") == -1)
942         {
943           out.append("</html>");
944         }
945       }
946
947       out.append(TAB);
948     }
949     out.append(sequenceName);
950     out.append("\t-1\t");
951     out.append(sequenceFeature.begin);
952     out.append(TAB);
953     out.append(sequenceFeature.end);
954     out.append(TAB);
955     out.append(sequenceFeature.type);
956     if (!Float.isNaN(sequenceFeature.score))
957     {
958       out.append(TAB);
959       out.append(sequenceFeature.score);
960     }
961     out.append(newline);
962   }
963
964   /**
965    * Parse method that is called when a GFF file is dragged to the desktop
966    */
967   @Override
968   public void parse()
969   {
970     AlignViewportI av = getViewport();
971     if (av != null)
972     {
973       if (av.getAlignment() != null)
974       {
975         dataset = av.getAlignment().getDataset();
976       }
977       if (dataset == null)
978       {
979         // working in the applet context ?
980         dataset = av.getAlignment();
981       }
982     }
983     else
984     {
985       dataset = new Alignment(new SequenceI[] {});
986     }
987
988     Map<String, FeatureColourI> featureColours = new HashMap<>();
989     boolean parseResult = parse(dataset, featureColours, false, true);
990     if (!parseResult)
991     {
992       // pass error up somehow
993     }
994     if (av != null)
995     {
996       // update viewport with the dataset data ?
997     }
998     else
999     {
1000       setSeqs(dataset.getSequencesArray());
1001     }
1002   }
1003
1004   /**
1005    * Implementation of unused abstract method
1006    * 
1007    * @return error message
1008    */
1009   @Override
1010   public String print(SequenceI[] sqs, boolean jvsuffix)
1011   {
1012     jalview.bin.Console.outPrintln("Use printGffFormat() or printJalviewFormat()");
1013     return null;
1014   }
1015
1016   /**
1017    * Returns features output in GFF2 format
1018    * 
1019    * @param sequences
1020    *          the sequences whose features are to be output
1021    * @param visible
1022    *          a map whose keys are the type names of visible features
1023    * @param visibleFeatureGroups
1024    * @param includeNonPositionalFeatures
1025    * @param includeComplement
1026    * @return
1027    */
1028   public String printGffFormat(SequenceI[] sequences, FeatureRenderer fr,
1029           boolean includeNonPositionalFeatures, boolean includeComplement)
1030   {
1031     FeatureRenderer fr2 = null;
1032     if (includeComplement)
1033     {
1034       AlignViewportI comp = fr.getViewport().getCodingComplement();
1035       fr2 = Desktop.getAlignFrameFor(comp).getFeatureRenderer();
1036     }
1037
1038     Map<String, FeatureColourI> visibleColours = fr
1039             .getDisplayedFeatureCols();
1040
1041     StringBuilder out = new StringBuilder(256);
1042
1043     out.append(String.format("%s %d\n", GFF_VERSION,
1044             gffVersion == 0 ? 2 : gffVersion));
1045
1046     String[] types = visibleColours == null ? new String[0]
1047             : visibleColours.keySet()
1048                     .toArray(new String[visibleColours.keySet().size()]);
1049
1050     for (SequenceI seq : sequences)
1051     {
1052       List<SequenceFeature> seqFeatures = new ArrayList<>();
1053       List<SequenceFeature> features = new ArrayList<>();
1054       if (includeNonPositionalFeatures)
1055       {
1056         features.addAll(seq.getFeatures().getNonPositionalFeatures());
1057       }
1058       if (visibleColours != null && !visibleColours.isEmpty())
1059       {
1060         features.addAll(seq.getFeatures().getPositionalFeatures(types));
1061       }
1062       for (SequenceFeature sf : features)
1063       {
1064         if (sf.isNonPositional() || fr.isVisible(sf))
1065         {
1066           /*
1067            * drop features hidden by group visibility, colour threshold,
1068            * or feature filter condition
1069            */
1070           seqFeatures.add(sf);
1071         }
1072       }
1073
1074       if (includeComplement)
1075       {
1076         seqFeatures.addAll(findComplementaryFeatures(seq, fr2));
1077       }
1078
1079       /*
1080        * sort features here if wanted
1081        */
1082       for (SequenceFeature sf : seqFeatures)
1083       {
1084         formatGffFeature(out, seq, sf);
1085         out.append(newline);
1086       }
1087     }
1088
1089     return out.toString();
1090   }
1091
1092   /**
1093    * Formats one feature as GFF and appends to the string buffer
1094    */
1095   private void formatGffFeature(StringBuilder out, SequenceI seq,
1096           SequenceFeature sf)
1097   {
1098     String source = sf.featureGroup;
1099     if (source == null)
1100     {
1101       source = sf.getDescription();
1102     }
1103
1104     out.append(seq.getName());
1105     out.append(TAB);
1106     out.append(source);
1107     out.append(TAB);
1108     out.append(sf.type);
1109     out.append(TAB);
1110     out.append(sf.begin);
1111     out.append(TAB);
1112     out.append(sf.end);
1113     out.append(TAB);
1114     out.append(sf.score);
1115     out.append(TAB);
1116
1117     int strand = sf.getStrand();
1118     out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1119     out.append(TAB);
1120
1121     String phase = sf.getPhase();
1122     out.append(phase == null ? "." : phase);
1123
1124     if (sf.otherDetails != null && !sf.otherDetails.isEmpty())
1125     {
1126       Map<String, Object> map = sf.otherDetails;
1127       formatAttributes(out, map);
1128     }
1129   }
1130
1131   /**
1132    * A helper method that outputs attributes stored in the map as
1133    * semicolon-delimited values e.g.
1134    * 
1135    * <pre>
1136    * AC_Male=0;AF_NFE=0.00000e 00;Hom_FIN=0;GQ_MEDIAN=9
1137    * </pre>
1138    * 
1139    * A map-valued attribute is formatted as a comma-delimited list within
1140    * braces, for example
1141    * 
1142    * <pre>
1143    * jvmap_CSQ={ALLELE_NUM=1,UNIPARC=UPI0002841053,Feature=ENST00000585561}
1144    * </pre>
1145    * 
1146    * The {@code jvmap_} prefix designates a values map and is removed if the
1147    * value is parsed when read in. (The GFF3 specification allows
1148    * 'semi-structured data' to be represented provided the attribute name begins
1149    * with a lower case letter.)
1150    * 
1151    * @param sb
1152    * @param map
1153    * @see http://gmod.org/wiki/GFF3#GFF3_Format
1154    */
1155   void formatAttributes(StringBuilder sb, Map<String, Object> map)
1156   {
1157     sb.append(TAB);
1158     boolean first = true;
1159     for (String key : map.keySet())
1160     {
1161       if (SequenceFeature.STRAND.equals(key)
1162               || SequenceFeature.PHASE.equals(key))
1163       {
1164         /*
1165          * values stashed in map but output to their own columns
1166          */
1167         continue;
1168       }
1169       {
1170         if (!first)
1171         {
1172           sb.append(";");
1173         }
1174       }
1175       first = false;
1176       Object value = map.get(key);
1177       if (value instanceof Map<?, ?>)
1178       {
1179         formatMapAttribute(sb, key, (Map<?, ?>) value);
1180       }
1181       else
1182       {
1183         String formatted = StringUtils.urlEncode(value.toString(),
1184                 GffHelperI.GFF_ENCODABLE);
1185         sb.append(key).append(EQUALS).append(formatted);
1186       }
1187     }
1188   }
1189
1190   /**
1191    * Formats the map entries as
1192    * 
1193    * <pre>
1194    * key=key1=value1,key2=value2,...
1195    * </pre>
1196    * 
1197    * and appends this to the string buffer
1198    * 
1199    * @param sb
1200    * @param key
1201    * @param map
1202    */
1203   private void formatMapAttribute(StringBuilder sb, String key,
1204           Map<?, ?> map)
1205   {
1206     if (map == null || map.isEmpty())
1207     {
1208       return;
1209     }
1210
1211     /*
1212      * AbstractMap.toString would be a shortcut here, but more reliable
1213      * to code the required format in case toString changes in future
1214      */
1215     sb.append(key).append(EQUALS);
1216     boolean first = true;
1217     for (Entry<?, ?> entry : map.entrySet())
1218     {
1219       if (!first)
1220       {
1221         sb.append(",");
1222       }
1223       first = false;
1224       sb.append(entry.getKey().toString()).append(EQUALS);
1225       String formatted = StringUtils.urlEncode(entry.getValue().toString(),
1226               GffHelperI.GFF_ENCODABLE);
1227       sb.append(formatted);
1228     }
1229   }
1230
1231   /**
1232    * Returns a mapping given list of one or more Align descriptors (exonerate
1233    * format)
1234    * 
1235    * @param alignedRegions
1236    *          a list of "Align fromStart toStart fromCount"
1237    * @param mapIsFromCdna
1238    *          if true, 'from' is dna, else 'from' is protein
1239    * @param strand
1240    *          either 1 (forward) or -1 (reverse)
1241    * @return
1242    * @throws IOException
1243    */
1244   protected MapList constructCodonMappingFromAlign(
1245           List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1246           throws IOException
1247   {
1248     if (strand == 0)
1249     {
1250       throw new IOException(
1251               "Invalid strand for a codon mapping (cannot be 0)");
1252     }
1253     int regions = alignedRegions.size();
1254     // arrays to hold [start, end] for each aligned region
1255     int[] fromRanges = new int[regions * 2]; // from dna
1256     int[] toRanges = new int[regions * 2]; // to protein
1257     int fromRangesIndex = 0;
1258     int toRangesIndex = 0;
1259
1260     for (String range : alignedRegions)
1261     {
1262       /* 
1263        * Align mapFromStart mapToStart mapFromCount
1264        * e.g. if mapIsFromCdna
1265        *     Align 11270 143 120
1266        * means:
1267        *     120 bases from pos 11270 align to pos 143 in peptide
1268        * if !mapIsFromCdna this would instead be
1269        *     Align 143 11270 40 
1270        */
1271       String[] tokens = range.split(" ");
1272       if (tokens.length != 3)
1273       {
1274         throw new IOException("Wrong number of fields for Align");
1275       }
1276       int fromStart = 0;
1277       int toStart = 0;
1278       int fromCount = 0;
1279       try
1280       {
1281         fromStart = Integer.parseInt(tokens[0]);
1282         toStart = Integer.parseInt(tokens[1]);
1283         fromCount = Integer.parseInt(tokens[2]);
1284       } catch (NumberFormatException nfe)
1285       {
1286         throw new IOException(
1287                 "Invalid number in Align field: " + nfe.getMessage());
1288       }
1289
1290       /*
1291        * Jalview always models from dna to protein, so adjust values if the
1292        * GFF mapping is from protein to dna
1293        */
1294       if (!mapIsFromCdna)
1295       {
1296         fromCount *= 3;
1297         int temp = fromStart;
1298         fromStart = toStart;
1299         toStart = temp;
1300       }
1301       fromRanges[fromRangesIndex++] = fromStart;
1302       fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1303
1304       /*
1305        * If a codon has an intron gap, there will be contiguous 'toRanges';
1306        * this is handled for us by the MapList constructor. 
1307        * (It is not clear that exonerate ever generates this case)  
1308        */
1309       toRanges[toRangesIndex++] = toStart;
1310       toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1311     }
1312
1313     return new MapList(fromRanges, toRanges, 3, 1);
1314   }
1315
1316   /**
1317    * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1318    * hold the feature, or for its mapped sequence, or both, to be resolved
1319    * either later in the GFF file (##FASTA section), or when the user loads
1320    * additional sequences.
1321    * 
1322    * @param gffColumns
1323    * @param alignment
1324    * @param relaxedIdMatching
1325    * @param newseqs
1326    * @return
1327    */
1328   protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1329           boolean relaxedIdMatching, List<SequenceI> newseqs)
1330   {
1331     /*
1332      * GFF: seqid source type start end score strand phase [attributes]
1333      */
1334     if (gffColumns.length < 5)
1335     {
1336       jalview.bin.Console.errPrintln("Ignoring GFF feature line with too few columns ("
1337               + gffColumns.length + ")");
1338       return null;
1339     }
1340
1341     /*
1342      * locate referenced sequence in alignment _or_ 
1343      * as a forward or external reference (SequenceDummy)
1344      */
1345     String seqId = gffColumns[0];
1346     SequenceI seq = findSequence(seqId, alignment, newseqs,
1347             relaxedIdMatching);
1348
1349     SequenceFeature sf = null;
1350     GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1351     if (helper != null)
1352     {
1353       try
1354       {
1355         sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1356                 relaxedIdMatching);
1357         if (sf != null)
1358         {
1359           seq.addSequenceFeature(sf);
1360           while ((seq = alignment.findName(seq, seqId, true)) != null)
1361           {
1362             seq.addSequenceFeature(new SequenceFeature(sf));
1363           }
1364         }
1365       } catch (IOException e)
1366       {
1367         jalview.bin.Console.errPrintln("GFF parsing failed with: " + e.getMessage());
1368         return null;
1369       }
1370     }
1371
1372     return seq;
1373   }
1374
1375   /**
1376    * After encountering ##fasta in a GFF3 file, process the remainder of the
1377    * file as FAST sequence data. Any placeholder sequences created during
1378    * feature parsing are updated with the actual sequences.
1379    * 
1380    * @param align
1381    * @param newseqs
1382    * @throws IOException
1383    */
1384   protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1385           throws IOException
1386   {
1387     try
1388     {
1389       mark();
1390     } catch (IOException q)
1391     {
1392     }
1393     // Opening a FastaFile object with the remainder of this object's dataIn.
1394     // Tell the constructor to NOT close the dataIn when finished.
1395     FastaFile parser = new FastaFile(this, false);
1396     List<SequenceI> includedseqs = parser.getSeqs();
1397
1398     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1399
1400     /*
1401      * iterate over includedseqs, and replacing matching ones with newseqs
1402      * sequences. Generic iterator not used here because we modify
1403      * includedseqs as we go
1404      */
1405     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1406     {
1407       // search for any dummy seqs that this sequence can be used to update
1408       SequenceI includedSeq = includedseqs.get(p);
1409       SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1410       if (dummyseq != null && dummyseq instanceof SequenceDummy)
1411       {
1412         // probably have the pattern wrong
1413         // idea is that a flyweight proxy for a sequence ID can be created for
1414         // 1. stable reference creation
1415         // 2. addition of annotation
1416         // 3. future replacement by a real sequence
1417         // current pattern is to create SequenceDummy objects - a convenience
1418         // constructor for a Sequence.
1419         // problem is that when promoted to a real sequence, all references
1420         // need to be updated somehow. We avoid that by keeping the same object.
1421         ((SequenceDummy) dummyseq).become(includedSeq);
1422         dummyseq.createDatasetSequence();
1423
1424         /*
1425          * Update mappings so they are now to the dataset sequence
1426          */
1427         for (AlignedCodonFrame mapping : align.getCodonFrames())
1428         {
1429           mapping.updateToDataset(dummyseq);
1430         }
1431
1432         /*
1433          * replace parsed sequence with the realised forward reference
1434          */
1435         includedseqs.set(p, dummyseq);
1436
1437         /*
1438          * and remove from the newseqs list
1439          */
1440         newseqs.remove(dummyseq);
1441       }
1442     }
1443
1444     /*
1445      * finally add sequences to the dataset
1446      */
1447     for (SequenceI seq : includedseqs)
1448     {
1449       // experimental: mapping-based 'alignment' to query sequence
1450       AlignmentUtils.alignSequenceAs(seq, align,
1451               String.valueOf(align.getGapCharacter()), false, true);
1452
1453       // rename sequences if GFF handler requested this
1454       // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1455       List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures();
1456       if (!sfs.isEmpty())
1457       {
1458         String newName = (String) sfs.get(0)
1459                 .getValue(GffHelperI.RENAME_TOKEN);
1460         if (newName != null)
1461         {
1462           seq.setName(newName);
1463         }
1464       }
1465       align.addSequence(seq);
1466     }
1467   }
1468
1469   /**
1470    * Process a ## directive
1471    * 
1472    * @param line
1473    * @param gffProps
1474    * @param align
1475    * @param newseqs
1476    * @throws IOException
1477    */
1478   protected void processGffPragma(String line, Map<String, String> gffProps,
1479           AlignmentI align, List<SequenceI> newseqs) throws IOException
1480   {
1481     line = line.trim();
1482     if ("###".equals(line))
1483     {
1484       // close off any open 'forward references'
1485       return;
1486     }
1487
1488     String[] tokens = line.substring(2).split(" ");
1489     String pragma = tokens[0];
1490     String value = tokens.length == 1 ? null : tokens[1];
1491
1492     if ("gff-version".equalsIgnoreCase(pragma))
1493     {
1494       if (value != null)
1495       {
1496         try
1497         {
1498           // value may be e.g. "3.1.2"
1499           gffVersion = Integer.parseInt(value.split("\\.")[0]);
1500         } catch (NumberFormatException e)
1501         {
1502           // ignore
1503         }
1504       }
1505     }
1506     else if ("sequence-region".equalsIgnoreCase(pragma))
1507     {
1508       // could capture <seqid start end> if wanted here
1509     }
1510     else if ("feature-ontology".equalsIgnoreCase(pragma))
1511     {
1512       // should resolve against the specified feature ontology URI
1513     }
1514     else if ("attribute-ontology".equalsIgnoreCase(pragma))
1515     {
1516       // URI of attribute ontology - not currently used in GFF3
1517     }
1518     else if ("source-ontology".equalsIgnoreCase(pragma))
1519     {
1520       // URI of source ontology - not currently used in GFF3
1521     }
1522     else if ("species-build".equalsIgnoreCase(pragma))
1523     {
1524       // save URI of specific NCBI taxon version of annotations
1525       gffProps.put("species-build", value);
1526     }
1527     else if ("fasta".equalsIgnoreCase(pragma))
1528     {
1529       // process the rest of the file as a fasta file and replace any dummy
1530       // sequence IDs
1531       processAsFasta(align, newseqs);
1532     }
1533     else
1534     {
1535       jalview.bin.Console.errPrintln("Ignoring unknown pragma: " + line);
1536     }
1537   }
1538 }