2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
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;
55 import java.util.Map.Entry;
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
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'.
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.
74 public class FeaturesFile extends AlignFile implements FeaturesSourceI
76 private static final String TAB_REGEX = "\\t";
78 private static final String STARTGROUP = "STARTGROUP";
80 private static final String ENDGROUP = "ENDGROUP";
82 private static final String STARTFILTERS = "STARTFILTERS";
84 private static final String ENDFILTERS = "ENDFILTERS";
86 private static final String ID_NOT_SPECIFIED = "ID_NOT_SPECIFIED";
88 private static final String NOTE = "Note";
90 protected static final String GFF_VERSION = "##gff-version";
92 private AlignmentI lastmatchedAl = null;
94 private SequenceIdMatcher matcher = null;
96 protected AlignmentI dataset;
98 protected int gffVersion;
101 * Creates a new FeaturesFile object.
103 public FeaturesFile()
108 * Constructor which does not parse the file immediately
112 * @throws IOException
114 public FeaturesFile(String file, DataSourceType paste)
117 super(false, file, paste);
122 * @throws IOException
124 public FeaturesFile(FileParse source) throws IOException
130 * Constructor that optionally parses the file immediately
132 * @param parseImmediately
135 * @throws IOException
137 public FeaturesFile(boolean parseImmediately, String file,
138 DataSourceType type) throws IOException
140 super(parseImmediately, file, type);
144 * Parse GFF or sequence features file using case-independent matching,
148 * - alignment/dataset containing sequences that are to be annotated
150 * - hashtable to store feature colour definitions
152 * - process html strings into plain text
153 * @return true if features were added
155 public boolean parse(AlignmentI align,
156 Map<String, FeatureColourI> colours, boolean removeHTML)
158 return parse(align, colours, removeHTML, false);
162 * Extends the default addProperties by also adding peptide-to-cDNA mappings
163 * (if any) derived while parsing a GFF file
166 public void addProperties(AlignmentI al)
168 super.addProperties(al);
169 if (dataset != null && dataset.getCodonFrames() != null)
171 AlignmentI ds = (al.getDataset() == null) ? al : al.getDataset();
172 for (AlignedCodonFrame codons : dataset.getCodonFrames())
174 ds.addCodonFrame(codons);
180 * Parse GFF or Jalview format sequence features file
183 * - alignment/dataset containing sequences that are to be annotated
185 * - map to store feature colour definitions
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
192 public boolean parse(AlignmentI align,
193 Map<String, FeatureColourI> colours, boolean removeHTML,
194 boolean relaxedIdmatching)
196 return parse(align, colours, null, removeHTML, relaxedIdmatching);
200 * Parse GFF or Jalview format sequence features file
203 * - alignment/dataset containing sequences that are to be annotated
205 * - map to store feature colour definitions
207 * - map to store feature filter definitions
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
214 public boolean parse(AlignmentI align,
215 Map<String, FeatureColourI> colours,
216 Map<String, FeatureMatcherSetI> filters, boolean removeHTML,
217 boolean relaxedIdmatching)
219 Map<String, String> gffProps = new HashMap<>();
221 * keep track of any sequences we try to create from the data
223 List<SequenceI> newseqs = new ArrayList<>();
229 String featureGroup = null;
231 while ((line = nextLine()) != null)
233 // skip comments/process pragmas
234 if (line.length() == 0 || line.startsWith("#"))
236 if (line.toLowerCase().startsWith("##"))
238 processGffPragma(line, gffProps, align, newseqs);
243 gffColumns = line.split(TAB_REGEX);
244 if (gffColumns.length == 1)
246 if (line.trim().equalsIgnoreCase("GFF"))
249 * Jalview features file with appended GFF
250 * assume GFF2 (though it may declare ##gff-version 3)
257 if (gffColumns.length > 0 && gffColumns.length < 4)
260 * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
261 * a feature type colour specification
263 String ft = gffColumns[0];
264 if (ft.equalsIgnoreCase(STARTFILTERS))
266 parseFilters(filters);
269 if (ft.equalsIgnoreCase(STARTGROUP))
271 featureGroup = gffColumns[1];
273 else if (ft.equalsIgnoreCase(ENDGROUP))
275 // We should check whether this is the current group,
276 // but at present there's no way of showing more than 1 group
281 String colscheme = gffColumns[1];
282 FeatureColourI colour = FeatureColour
283 .parseJalviewFeatureColour(colscheme);
286 colours.put(ft, colour);
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
299 parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
300 relaxedIdmatching, featureGroup);
304 parseGff(gffColumns, align, relaxedIdmatching, newseqs);
308 } catch (Exception ex)
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);
320 * experimental - add any dummy sequences with features to the alignment
321 * - we need them for Ensembl feature extraction - though maybe not otherwise
323 for (SequenceI newseq : newseqs)
325 if (newseq.getFeatures().hasFeatures())
327 align.addSequence(newseq);
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).
340 * @throws IOException
342 protected void parseFilters(Map<String, FeatureMatcherSetI> filters)
346 while ((line = nextLine()) != null)
348 if (line.toUpperCase().startsWith(ENDFILTERS))
352 String[] tokens = line.split(TAB_REGEX);
353 if (tokens.length != 2)
355 System.err.println(String.format("Invalid token count %d for %d",
356 tokens.length, line));
360 String featureType = tokens[0];
361 FeatureMatcherSetI fm = FeatureMatcherSet.fromString(tokens[1]);
362 if (fm != null && filters != null)
364 filters.put(featureType, fm);
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.
378 * @param featureColours
380 * @param relaxedIdmatching
381 * @param featureGroup
383 protected boolean parseJalviewFeature(String line, String[] gffColumns,
384 AlignmentI alignment, Map<String, FeatureColourI> featureColours,
385 boolean removeHTML, boolean relaxedIdMatching,
389 * tokens: description seqid seqIndex start end type [score]
391 if (gffColumns.length < 6)
393 System.err.println("Ignoring feature line '" + line
394 + "' with too few columns (" + gffColumns.length + ")");
397 String desc = gffColumns[0];
398 String seqId = gffColumns[1];
399 SequenceI seq = findSequence(seqId, alignment, null, relaxedIdMatching);
401 if (!ID_NOT_SPECIFIED.equals(seqId))
403 seq = findSequence(seqId, alignment, null, relaxedIdMatching);
409 String seqIndex = gffColumns[2];
412 int idx = Integer.parseInt(seqIndex);
413 seq = alignment.getSequenceAt(idx);
414 } catch (NumberFormatException ex)
416 System.err.println("Invalid sequence index: " + seqIndex);
422 System.out.println("Sequence not found: " + line);
426 int startPos = Integer.parseInt(gffColumns[3]);
427 int endPos = Integer.parseInt(gffColumns[4]);
429 String ft = gffColumns[5];
431 if (!featureColours.containsKey(ft))
434 * Perhaps an old style groups file with no colours -
435 * synthesize a colour from the feature type
437 Color colour = ColorUtils.createColourFromName(ft);
438 featureColours.put(ft, new FeatureColour(colour));
440 SequenceFeature sf = null;
441 if (gffColumns.length > 6)
443 float score = Float.NaN;
446 score = Float.valueOf(gffColumns[6]).floatValue();
447 } catch (NumberFormatException ex)
449 sf = new SequenceFeature(ft, desc, startPos, endPos, featureGroup);
451 sf = new SequenceFeature(ft, desc, startPos, endPos, score,
456 sf = new SequenceFeature(ft, desc, startPos, endPos, featureGroup);
459 parseDescriptionHTML(sf, removeHTML);
461 seq.addSequenceFeature(sf);
464 && (seq = alignment.findName(seq, seqId, false)) != null)
466 seq.addSequenceFeature(new SequenceFeature(sf));
472 * clear any temporary handles used to speed up ID matching
474 protected void resetMatcher()
476 lastmatchedAl = null;
481 * Returns a sequence matching the given id, as follows
483 * <li>strict matching is on exact sequence name</li>
484 * <li>relaxed matching allows matching on a token within the sequence name,
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>
496 * @param relaxedIdMatching
500 protected SequenceI findSequence(String seqId, AlignmentI align,
501 List<SequenceI> newseqs, boolean relaxedIdMatching)
503 // TODO encapsulate in SequenceIdMatcher, share the matcher
504 // with the GffHelper (removing code duplication)
505 SequenceI match = null;
506 if (relaxedIdMatching)
508 if (lastmatchedAl != align)
510 lastmatchedAl = align;
511 matcher = new SequenceIdMatcher(align.getSequencesArray());
514 matcher.addAll(newseqs);
517 match = matcher.findIdMatch(seqId);
521 match = align.findName(seqId, true);
522 if (match == null && newseqs != null)
524 for (SequenceI m : newseqs)
526 if (seqId.equals(m.getName()))
534 if (match == null && newseqs != null)
536 match = new SequenceDummy(seqId);
537 if (relaxedIdMatching)
539 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
541 // add dummy sequence to the newseqs list
547 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
549 if (sf.getDescription() == null)
553 ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
554 sf.getDescription(), removeHTML, newline);
558 sf.setDescription(parsed.getNonHtmlContent());
561 for (String link : parsed.getLinks())
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).
575 * @param includeNonPositional
576 * if true, include non-positional features (regardless of group or
580 public String printJalviewFormat(SequenceI[] sequences,
581 FeatureRenderer fr, boolean includeNonPositional)
583 Map<String, FeatureColourI> visibleColours = fr
584 .getDisplayedFeatureCols();
585 Map<String, FeatureMatcherSetI> featureFilters = fr.getFeatureFilters();
587 if (!includeNonPositional
588 && (visibleColours == null || visibleColours.isEmpty()))
590 // no point continuing.
591 return "No Features Visible";
595 * write out feature colours (if we know them)
597 // TODO: decide if feature links should also be written here ?
598 StringBuilder out = new StringBuilder(256);
599 if (visibleColours != null)
601 for (Entry<String, FeatureColourI> featureColour : visibleColours
604 FeatureColourI colour = featureColour.getValue();
605 out.append(colour.toJalviewFormat(featureColour.getKey())).append(
610 String[] types = visibleColours == null ? new String[0]
611 : visibleColours.keySet()
612 .toArray(new String[visibleColours.keySet().size()]);
615 * feature filters if any
617 outputFeatureFilters(out, visibleColours, featureFilters);
620 * output features within groups
622 int count = outputFeaturesByGroup(out, fr, types, sequences,
623 includeNonPositional);
625 return count > 0 ? out.toString() : "No Features Visible";
629 * Outputs any feature filters defined for visible feature types, sandwiched by
630 * STARTFILTERS and ENDFILTERS lines
634 * @param featureFilters
636 void outputFeatureFilters(StringBuilder out,
637 Map<String, FeatureColourI> visible,
638 Map<String, FeatureMatcherSetI> featureFilters)
640 if (visible == null || featureFilters == null
641 || featureFilters.isEmpty())
646 boolean first = true;
647 for (String featureType : visible.keySet())
649 FeatureMatcherSetI filter = featureFilters.get(featureType);
655 out.append(newline).append(STARTFILTERS).append(newline);
657 out.append(featureType).append(TAB).append(filter.toStableString())
663 out.append(ENDFILTERS).append(newline);
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.
675 * @param featureTypes
677 * @param includeNonPositional
680 private int outputFeaturesByGroup(StringBuilder out,
681 FeatureRenderer fr, String[] featureTypes,
682 SequenceI[] sequences, boolean includeNonPositional)
685 * get all positional feature groups
687 Set<String> featureGroups = new HashSet<>(fr.getFeatureGroups());
690 * add non-positional feature groups, just in case any are not
691 * also positional feature groups
693 for (SequenceI seq : sequences)
695 Set<String> nonPosGroups = seq.getFeatures().getFeatureGroups(false);
696 featureGroups.addAll(nonPosGroups);
700 * sort groups alphabetically, and ensure that features with a
701 * null or empty group are output after those in named groups
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("");
711 List<String> visibleGroups = fr.getDisplayedFeatureGroups();
714 * loop over all groups (may be visible or not);
715 * non-positional features are output even if group is not visible
717 for (String group : sortedGroups)
719 boolean firstInGroup = true;
720 boolean isNullGroup = group == null || "".equals(group);
722 for (int i = 0; i < sequences.length; i++)
724 String sequenceName = sequences[i].getName();
725 List<SequenceFeature> features = new ArrayList<>();
728 * get any non-positional features in this group, if wanted
729 * (for any feature type, whether visible or not)
731 if (includeNonPositional)
733 features.addAll(sequences[i].getFeatures()
734 .getFeaturesForGroup(false, group));
738 * add positional features for visible feature types, but
739 * (for named groups) only if feature group is visible
741 if (featureTypes.length > 0
742 && (isNullGroup || visibleGroups.contains(group)))
744 features.addAll(sequences[i].getFeatures().getFeaturesForGroup(
745 true, group, featureTypes));
748 for (SequenceFeature sf : features)
750 if (sf.isNonPositional() || fr.isVisible(sf))
758 out.append(STARTGROUP).append(TAB).append(group)
762 firstInGroup = false;
763 out.append(formatJalviewFeature(sequenceName, sf));
768 if (!isNullGroup && !firstInGroup)
770 out.append(ENDGROUP).append(TAB).append(group).append(newline);
778 * @param sequenceName
779 * @param sequenceFeature
781 protected String formatJalviewFeature(
782 String sequenceName, SequenceFeature sequenceFeature)
784 StringBuilder out = new StringBuilder(64);
785 if (sequenceFeature.description == null
786 || sequenceFeature.description.equals(""))
788 out.append(sequenceFeature.type).append(TAB);
792 if (sequenceFeature.links != null
793 && sequenceFeature.getDescription().indexOf("<html>") == -1)
795 out.append("<html>");
798 out.append(sequenceFeature.description);
799 if (sequenceFeature.links != null)
801 for (int l = 0; l < sequenceFeature.links.size(); l++)
803 String label = sequenceFeature.links.elementAt(l);
804 String href = label.substring(label.indexOf("|") + 1);
805 label = label.substring(0, label.indexOf("|"));
807 if (sequenceFeature.description.indexOf(href) == -1)
809 out.append(" <a href=\"" + href + "\">" + label + "</a>");
813 if (sequenceFeature.getDescription().indexOf("</html>") == -1)
815 out.append("</html>");
821 out.append(sequenceName);
822 out.append("\t-1\t");
823 out.append(sequenceFeature.begin);
825 out.append(sequenceFeature.end);
827 out.append(sequenceFeature.type);
828 if (!Float.isNaN(sequenceFeature.score))
831 out.append(sequenceFeature.score);
835 return out.toString();
839 * Parse method that is called when a GFF file is dragged to the desktop
844 AlignViewportI av = getViewport();
847 if (av.getAlignment() != null)
849 dataset = av.getAlignment().getDataset();
853 // working in the applet context ?
854 dataset = av.getAlignment();
859 dataset = new Alignment(new SequenceI[] {});
862 Map<String, FeatureColourI> featureColours = new HashMap<>();
863 boolean parseResult = parse(dataset, featureColours, false, true);
866 // pass error up somehow
870 // update viewport with the dataset data ?
874 setSeqs(dataset.getSequencesArray());
879 * Implementation of unused abstract method
881 * @return error message
884 public String print(SequenceI[] sqs, boolean jvsuffix)
886 System.out.println("Use printGffFormat() or printJalviewFormat()");
891 * Returns features output in GFF2 format
894 * the sequences whose features are to be output
896 * a map whose keys are the type names of visible features
897 * @param visibleFeatureGroups
898 * @param includeNonPositionalFeatures
901 public String printGffFormat(SequenceI[] sequences,
902 FeatureRenderer fr, boolean includeNonPositionalFeatures)
904 Map<String, FeatureColourI> visibleColours = fr.getDisplayedFeatureCols();
906 StringBuilder out = new StringBuilder(256);
908 out.append(String.format("%s %d\n", GFF_VERSION, gffVersion == 0 ? 2 : gffVersion));
910 if (!includeNonPositionalFeatures
911 && (visibleColours == null || visibleColours.isEmpty()))
913 return out.toString();
916 String[] types = visibleColours == null ? new String[0]
917 : visibleColours.keySet()
918 .toArray(new String[visibleColours.keySet().size()]);
920 for (SequenceI seq : sequences)
922 List<SequenceFeature> features = new ArrayList<>();
923 if (includeNonPositionalFeatures)
925 features.addAll(seq.getFeatures().getNonPositionalFeatures());
927 if (visibleColours != null && !visibleColours.isEmpty())
929 features.addAll(seq.getFeatures().getPositionalFeatures(types));
932 for (SequenceFeature sf : features)
934 if (!sf.isNonPositional() && !fr.isVisible(sf))
937 * feature hidden by group visibility, colour threshold,
938 * or feature filter condition
943 String source = sf.featureGroup;
946 source = sf.getDescription();
949 out.append(seq.getName());
955 out.append(sf.begin);
959 out.append(sf.score);
962 int strand = sf.getStrand();
963 out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
966 String phase = sf.getPhase();
967 out.append(phase == null ? "." : phase);
969 // miscellaneous key-values (GFF column 9)
970 String attributes = sf.getAttributes();
971 if (attributes != null)
973 out.append(TAB).append(attributes);
980 return out.toString();
984 * Returns a mapping given list of one or more Align descriptors (exonerate
987 * @param alignedRegions
988 * a list of "Align fromStart toStart fromCount"
989 * @param mapIsFromCdna
990 * if true, 'from' is dna, else 'from' is protein
992 * either 1 (forward) or -1 (reverse)
994 * @throws IOException
996 protected MapList constructCodonMappingFromAlign(
997 List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1002 throw new IOException(
1003 "Invalid strand for a codon mapping (cannot be 0)");
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;
1012 for (String range : alignedRegions)
1015 * Align mapFromStart mapToStart mapFromCount
1016 * e.g. if mapIsFromCdna
1017 * Align 11270 143 120
1019 * 120 bases from pos 11270 align to pos 143 in peptide
1020 * if !mapIsFromCdna this would instead be
1021 * Align 143 11270 40
1023 String[] tokens = range.split(" ");
1024 if (tokens.length != 3)
1026 throw new IOException("Wrong number of fields for Align");
1033 fromStart = Integer.parseInt(tokens[0]);
1034 toStart = Integer.parseInt(tokens[1]);
1035 fromCount = Integer.parseInt(tokens[2]);
1036 } catch (NumberFormatException nfe)
1038 throw new IOException(
1039 "Invalid number in Align field: " + nfe.getMessage());
1043 * Jalview always models from dna to protein, so adjust values if the
1044 * GFF mapping is from protein to dna
1049 int temp = fromStart;
1050 fromStart = toStart;
1053 fromRanges[fromRangesIndex++] = fromStart;
1054 fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
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)
1061 toRanges[toRangesIndex++] = toStart;
1062 toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1065 return new MapList(fromRanges, toRanges, 3, 1);
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.
1076 * @param relaxedIdMatching
1080 protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1081 boolean relaxedIdMatching, List<SequenceI> newseqs)
1084 * GFF: seqid source type start end score strand phase [attributes]
1086 if (gffColumns.length < 5)
1088 System.err.println("Ignoring GFF feature line with too few columns ("
1089 + gffColumns.length + ")");
1094 * locate referenced sequence in alignment _or_
1095 * as a forward or external reference (SequenceDummy)
1097 String seqId = gffColumns[0];
1098 SequenceI seq = findSequence(seqId, alignment, newseqs,
1101 SequenceFeature sf = null;
1102 GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1107 sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1111 seq.addSequenceFeature(sf);
1112 while ((seq = alignment.findName(seq, seqId, true)) != null)
1114 seq.addSequenceFeature(new SequenceFeature(sf));
1117 } catch (IOException e)
1119 System.err.println("GFF parsing failed with: " + e.getMessage());
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
1135 protected void processGffColumnNine(String attributes, SequenceFeature sf)
1137 sf.setAttributes(attributes);
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
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())
1149 String values = StringUtils.listToDelimitedString(attr.getValue(),
1151 sf.setValue(attr.getKey(), values);
1152 if (NOTE.equals(attr.getKey()))
1154 sf.setDescription(values);
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.
1166 * @throws IOException
1168 protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1174 } catch (IOException q)
1177 FastaFile parser = new FastaFile(this);
1178 List<SequenceI> includedseqs = parser.getSeqs();
1180 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
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
1187 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
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)
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();
1207 * Update mappings so they are now to the dataset sequence
1209 for (AlignedCodonFrame mapping : align.getCodonFrames())
1211 mapping.updateToDataset(dummyseq);
1215 * replace parsed sequence with the realised forward reference
1217 includedseqs.set(p, dummyseq);
1220 * and remove from the newseqs list
1222 newseqs.remove(dummyseq);
1227 * finally add sequences to the dataset
1229 for (SequenceI seq : includedseqs)
1231 // experimental: mapping-based 'alignment' to query sequence
1232 AlignmentUtils.alignSequenceAs(seq, align,
1233 String.valueOf(align.getGapCharacter()), false, true);
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();
1240 String newName = (String) sfs.get(0).getValue(
1241 GffHelperI.RENAME_TOKEN);
1242 if (newName != null)
1244 seq.setName(newName);
1247 align.addSequence(seq);
1252 * Process a ## directive
1258 * @throws IOException
1260 protected void processGffPragma(String line, Map<String, String> gffProps,
1261 AlignmentI align, List<SequenceI> newseqs) throws IOException
1264 if ("###".equals(line))
1266 // close off any open 'forward references'
1270 String[] tokens = line.substring(2).split(" ");
1271 String pragma = tokens[0];
1272 String value = tokens.length == 1 ? null : tokens[1];
1274 if ("gff-version".equalsIgnoreCase(pragma))
1280 // value may be e.g. "3.1.2"
1281 gffVersion = Integer.parseInt(value.split("\\.")[0]);
1282 } catch (NumberFormatException e)
1288 else if ("sequence-region".equalsIgnoreCase(pragma))
1290 // could capture <seqid start end> if wanted here
1292 else if ("feature-ontology".equalsIgnoreCase(pragma))
1294 // should resolve against the specified feature ontology URI
1296 else if ("attribute-ontology".equalsIgnoreCase(pragma))
1298 // URI of attribute ontology - not currently used in GFF3
1300 else if ("source-ontology".equalsIgnoreCase(pragma))
1302 // URI of source ontology - not currently used in GFF3
1304 else if ("species-build".equalsIgnoreCase(pragma))
1306 // save URI of specific NCBI taxon version of annotations
1307 gffProps.put("species-build", value);
1309 else if ("fasta".equalsIgnoreCase(pragma))
1311 // process the rest of the file as a fasta file and replace any dummy
1313 processAsFasta(align, newseqs);
1317 System.err.println("Ignoring unknown pragma: " + line);