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