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.FeaturesSourceI;
27 import jalview.datamodel.AlignedCodonFrame;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.SequenceDummy;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.gff.GffHelperBase;
34 import jalview.io.gff.GffHelperFactory;
35 import jalview.io.gff.GffHelperI;
36 import jalview.schemes.AnnotationColourGradient;
37 import jalview.schemes.GraduatedColor;
38 import jalview.schemes.UserColourScheme;
39 import jalview.util.Format;
40 import jalview.util.MapList;
41 import jalview.util.ParseHtmlBodyAndLinks;
42 import jalview.util.StringUtils;
44 import java.awt.Color;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.HashMap;
49 import java.util.Iterator;
50 import java.util.List;
52 import java.util.Map.Entry;
53 import java.util.StringTokenizer;
56 * Parses and writes features files, which may be in Jalview, GFF2 or GFF3
57 * format. These are tab-delimited formats but with differences in the use of
60 * A Jalview feature file may define feature colours and then declare that the
61 * remainder of the file is in GFF format with the line 'GFF'.
63 * GFF3 files may include alignment mappings for features, which Jalview will
64 * attempt to model, and may include sequence data following a ##FASTA line.
71 public class FeaturesFile extends AlignFile implements FeaturesSourceI
73 private static final String ID_NOT_SPECIFIED = "ID_NOT_SPECIFIED";
75 private static final String NOTE = "Note";
77 protected static final String TAB = "\t";
79 protected static final String GFF_VERSION = "##gff-version";
81 private AlignmentI lastmatchedAl = null;
83 private SequenceIdMatcher matcher = null;
85 protected AlignmentI dataset;
87 protected int gffVersion;
90 * Creates a new FeaturesFile object.
97 * Constructor which does not parse the file immediately
101 * @throws IOException
103 public FeaturesFile(String inFile, String type) throws IOException
105 super(false, inFile, type);
110 * @throws IOException
112 public FeaturesFile(FileParse source) throws IOException
118 * Constructor that optionally parses the file immediately
120 * @param parseImmediately
123 * @throws IOException
125 public FeaturesFile(boolean parseImmediately, String inFile, String type)
128 super(parseImmediately, inFile, type);
132 * Parse GFF or sequence features file using case-independent matching,
136 * - alignment/dataset containing sequences that are to be annotated
138 * - hashtable to store feature colour definitions
140 * - process html strings into plain text
141 * @return true if features were added
143 public boolean parse(AlignmentI align, Map<String, Object> colours,
146 return parse(align, colours, removeHTML, false);
150 * Extends the default addProperties by also adding peptide-to-cDNA mappings
151 * (if any) derived while parsing a GFF file
154 public void addProperties(AlignmentI al)
156 super.addProperties(al);
157 if (dataset != null && dataset.getCodonFrames() != null)
159 AlignmentI ds = (al.getDataset() == null) ? al : al.getDataset();
160 for (AlignedCodonFrame codons : dataset.getCodonFrames())
162 ds.addCodonFrame(codons);
168 * Parse GFF or Jalview format sequence features file
171 * - alignment/dataset containing sequences that are to be annotated
173 * - hashtable to store feature colour definitions
175 * - process html strings into plain text
176 * @param relaxedIdmatching
177 * - when true, ID matches to compound sequence IDs are allowed
178 * @return true if features were added
180 public boolean parse(AlignmentI align, Map<String, Object> colours,
181 boolean removeHTML, boolean relaxedIdmatching)
183 Map<String, String> gffProps = new HashMap<String, String>();
185 * keep track of any sequences we try to create from the data
187 List<SequenceI> newseqs = new ArrayList<SequenceI>();
193 String featureGroup = null;
195 while ((line = nextLine()) != null)
197 // skip comments/process pragmas
198 if (line.length() == 0 || line.startsWith("#"))
200 if (line.toLowerCase().startsWith("##"))
202 processGffPragma(line, gffProps, align, newseqs);
207 gffColumns = line.split("\\t"); // tab as regex
208 if (gffColumns.length == 1)
210 if (line.trim().equalsIgnoreCase("GFF"))
213 * Jalview features file with appended GFF
214 * assume GFF2 (though it may declare ##gff-version 3)
221 if (gffColumns.length > 1 && gffColumns.length < 4)
224 * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
225 * a feature type colour specification
227 String ft = gffColumns[0];
228 if (ft.equalsIgnoreCase("startgroup"))
230 featureGroup = gffColumns[1];
232 else if (ft.equalsIgnoreCase("endgroup"))
234 // We should check whether this is the current group,
235 // but at present theres no way of showing more than 1 group
240 parseFeatureColour(line, ft, gffColumns, colours);
246 * if not a comment, GFF pragma, startgroup, endgroup or feature
247 * colour specification, that just leaves a feature details line
248 * in either Jalview or GFF format
252 parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
253 relaxedIdmatching, featureGroup);
257 parseGff(gffColumns, align, relaxedIdmatching, newseqs);
261 } catch (Exception ex)
263 // should report somewhere useful for UI if necessary
264 warningMessage = ((warningMessage == null) ? "" : warningMessage)
265 + "Parsing error at\n" + line;
266 System.out.println("Error parsing feature file: " + ex + "\n" + line);
267 ex.printStackTrace(System.err);
273 * experimental - add any dummy sequences with features to the alignment
274 * - we need them for Ensembl feature extraction - though maybe not otherwise
276 for (SequenceI newseq : newseqs)
278 if (newseq.getSequenceFeatures() != null)
280 align.addSequence(newseq);
287 * Try to parse a Jalview format feature specification and add it as a
288 * sequence feature to any matching sequences in the alignment. Returns true
289 * if successful (a feature was added), or false if not.
294 * @param featureColours
296 * @param relaxedIdmatching
297 * @param featureGroup
299 protected boolean parseJalviewFeature(String line, String[] gffColumns,
300 AlignmentI alignment, Map<String, Object> featureColours,
301 boolean removeHTML, boolean relaxedIdMatching, String featureGroup)
304 * tokens: description seqid seqIndex start end type [score]
306 if (gffColumns.length < 6)
308 System.err.println("Ignoring feature line '" + line
309 + "' with too few columns (" + gffColumns.length + ")");
312 String desc = gffColumns[0];
313 String seqId = gffColumns[1];
314 SequenceI seq = findSequence(seqId, alignment, null, relaxedIdMatching);
316 if (!ID_NOT_SPECIFIED.equals(seqId))
318 seq = findSequence(seqId, alignment, null, relaxedIdMatching);
324 String seqIndex = gffColumns[2];
327 int idx = Integer.parseInt(seqIndex);
328 seq = alignment.getSequenceAt(idx);
329 } catch (NumberFormatException ex)
331 System.err.println("Invalid sequence index: " + seqIndex);
337 System.out.println("Sequence not found: " + line);
341 int startPos = Integer.parseInt(gffColumns[3]);
342 int endPos = Integer.parseInt(gffColumns[4]);
344 String ft = gffColumns[5];
346 if (!featureColours.containsKey(ft))
349 * Perhaps an old style groups file with no colours -
350 * synthesize a colour from the feature type
352 UserColourScheme ucs = new UserColourScheme(ft);
353 featureColours.put(ft, ucs.findColour('A'));
355 SequenceFeature sf = new SequenceFeature(ft, desc, "", startPos,
356 endPos, featureGroup);
357 if (gffColumns.length > 6)
359 float score = Float.NaN;
362 score = new Float(gffColumns[6]).floatValue();
363 // update colourgradient bounds if allowed to
364 } catch (NumberFormatException ex)
371 parseDescriptionHTML(sf, removeHTML);
373 seq.addSequenceFeature(sf);
376 && (seq = alignment.findName(seq, seqId, false)) != null)
378 seq.addSequenceFeature(new SequenceFeature(sf));
384 * Process a feature type colour specification
387 * the current input line (for error messages only)
389 * the first token on the line
391 * holds tokens on the line
393 * map to which to add derived colour specification
395 protected void parseFeatureColour(String line, String featureType,
396 String[] gffColumns, Map<String, Object> colours)
398 Object colour = null;
399 String colscheme = gffColumns[1];
400 if (colscheme.indexOf("|") > -1
401 || colscheme.trim().equalsIgnoreCase("label"))
403 colour = parseGraduatedColourScheme(line, colscheme);
407 UserColourScheme ucs = new UserColourScheme(colscheme);
408 colour = ucs.findColour('A');
412 colours.put(featureType, colour);
417 * Parse a Jalview graduated colour descriptor
420 * @param colourDescriptor
423 protected GraduatedColor parseGraduatedColourScheme(String line,
424 String colourDescriptor)
426 // Parse '|' separated graduated colourscheme fields:
427 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
428 // can either provide 'label' only, first is optional, next two
429 // colors are required (but may be
430 // left blank), next is optional, nxt two min/max are required.
431 // first is either 'label'
432 // first/second and third are both hexadecimal or word equivalent
434 // next two are values parsed as floats.
435 // fifth is either 'above','below', or 'none'.
436 // sixth is a float value and only required when fifth is either
437 // 'above' or 'below'.
438 StringTokenizer gcol = new StringTokenizer(colourDescriptor, "|", true);
440 float min = Float.MIN_VALUE, max = Float.MAX_VALUE;
441 boolean labelCol = false;
443 String mincol = gcol.nextToken();
447 .println("Expected either 'label' or a colour specification in the line: "
451 String maxcol = null;
452 if (mincol.toLowerCase().indexOf("label") == 0)
455 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip '|'
456 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
458 String abso = null, minval, maxval;
461 // at least four more tokens
462 if (mincol.equals("|"))
468 gcol.nextToken(); // skip next '|'
470 // continue parsing rest of line
471 maxcol = gcol.nextToken();
472 if (maxcol.equals("|"))
478 gcol.nextToken(); // skip next '|'
480 abso = gcol.nextToken();
481 gcol.nextToken(); // skip next '|'
482 if (abso.toLowerCase().indexOf("abso") != 0)
489 minval = gcol.nextToken();
490 gcol.nextToken(); // skip next '|'
492 maxval = gcol.nextToken();
493 if (gcol.hasMoreTokens())
495 gcol.nextToken(); // skip next '|'
499 if (minval.length() > 0)
501 min = Float.valueOf(minval);
503 } catch (Exception e)
506 .println("Couldn't parse the minimum value for graduated colour for type ("
508 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
513 if (maxval.length() > 0)
515 max = Float.valueOf(maxval);
517 } catch (Exception e)
520 .println("Couldn't parse the maximum value for graduated colour for type ("
521 + colourDescriptor + ")");
527 // add in some dummy min/max colours for the label-only
533 GraduatedColor colour = null;
536 colour = new GraduatedColor(
537 new UserColourScheme(mincol).findColour('A'),
538 new UserColourScheme(maxcol).findColour('A'), min, max);
539 } catch (Exception e)
541 System.err.println("Couldn't parse the graduated colour scheme ("
542 + colourDescriptor + ")");
547 colour.setColourByLabel(labelCol);
548 colour.setAutoScaled(abso == null);
549 // add in any additional parameters
550 String ttype = null, tval = null;
551 if (gcol.hasMoreTokens())
553 // threshold type and possibly a threshold value
554 ttype = gcol.nextToken();
555 if (ttype.toLowerCase().startsWith("below"))
557 colour.setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
559 else if (ttype.toLowerCase().startsWith("above"))
561 colour.setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
565 colour.setThreshType(AnnotationColourGradient.NO_THRESHOLD);
566 if (!ttype.toLowerCase().startsWith("no"))
568 System.err.println("Ignoring unrecognised threshold type : "
573 if (colour.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
578 tval = gcol.nextToken();
579 colour.setThresh(new Float(tval).floatValue());
580 } catch (Exception e)
582 System.err.println("Couldn't parse threshold value as a float: ("
587 // parse the thresh-is-min token ?
588 if (gcol.hasMoreTokens())
591 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
592 while (gcol.hasMoreTokens())
594 System.err.println("|" + gcol.nextToken());
596 System.err.println("\n");
603 * clear any temporary handles used to speed up ID matching
605 protected void resetMatcher()
607 lastmatchedAl = null;
612 * Returns a sequence matching the given id, as follows
614 * <li>strict matching is on exact sequence name</li>
615 * <li>relaxed matching allows matching on a token within the sequence name,
617 * <li>first tries to find a match in the alignment sequences</li>
618 * <li>else tries to find a match in the new sequences already generated while
619 * parsing the features file</li>
620 * <li>else creates a new placeholder sequence, adds it to the new sequences
621 * list, and returns it</li>
627 * @param relaxedIdMatching
631 protected SequenceI findSequence(String seqId, AlignmentI align,
632 List<SequenceI> newseqs, boolean relaxedIdMatching)
634 // TODO encapsulate in SequenceIdMatcher, share the matcher
635 // with the GffHelper (removing code duplication)
636 SequenceI match = null;
637 if (relaxedIdMatching)
639 if (lastmatchedAl != align)
641 lastmatchedAl = align;
642 matcher = new SequenceIdMatcher(align.getSequencesArray());
645 matcher.addAll(newseqs);
648 match = matcher.findIdMatch(seqId);
652 match = align.findName(seqId, true);
653 if (match == null && newseqs != null)
655 for (SequenceI m : newseqs)
657 if (seqId.equals(m.getName()))
665 if (match == null && newseqs != null)
667 match = new SequenceDummy(seqId);
668 if (relaxedIdMatching)
670 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
672 // add dummy sequence to the newseqs list
678 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
680 if (sf.getDescription() == null)
684 ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
685 sf.getDescription(), removeHTML, newline);
687 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
689 for (String link : parsed.getLinks())
697 * generate a features file for seqs includes non-pos features by default.
700 * source of sequence features
702 * hash of feature types and colours
703 * @return features file contents
705 public String printJalviewFormat(SequenceI[] sequences,
706 Map<String, Object> visible)
708 return printJalviewFormat(sequences, visible, true, true);
712 * generate a features file for seqs with colours from visible (if any)
717 * hash of Colours for each feature type
719 * when true only feature types in 'visible' will be output
721 * indicates if non-positional features should be output (regardless
723 * @return features file contents
725 public String printJalviewFormat(SequenceI[] sequences,
726 Map<String, Object> visible, boolean visOnly, boolean nonpos)
728 StringBuilder out = new StringBuilder(256);
729 boolean featuresGen = false;
730 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
732 // no point continuing.
733 return "No Features Visible";
736 if (visible != null && visOnly)
738 // write feature colours only if we're given them and we are generating
740 // TODO: decide if feature links should also be written here ?
741 Iterator<String> en = visible.keySet().iterator();
742 String featureType, color;
745 featureType = en.next().toString();
747 if (visible.get(featureType) instanceof GraduatedColor)
749 GraduatedColor gc = (GraduatedColor) visible.get(featureType);
750 color = (gc.isColourByLabel() ? "label|" : "")
751 + Format.getHexString(gc.getMinColor()) + "|"
752 + Format.getHexString(gc.getMaxColor())
753 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
755 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
757 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
763 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
765 System.err.println("WARNING: Unsupported threshold type ("
766 + gc.getThreshType() + ") : Assuming 'above'");
771 color += "|" + gc.getThresh();
778 else if (visible.get(featureType) instanceof Color)
780 color = Format.getHexString((Color) visible.get(featureType));
784 // legacy support for integer objects containing colour triplet values
785 color = Format.getHexString(new Color(Integer.parseInt(visible
786 .get(featureType).toString())));
788 out.append(featureType);
794 // Work out which groups are both present and visible
795 List<String> groups = new ArrayList<String>();
797 boolean isnonpos = false;
799 SequenceFeature[] features;
800 for (int i = 0; i < sequences.length; i++)
802 features = sequences[i].getSequenceFeatures();
803 if (features != null)
805 for (int j = 0; j < features.length; j++)
807 isnonpos = features[j].begin == 0 && features[j].end == 0;
808 if ((!nonpos && isnonpos)
809 || (!isnonpos && visOnly && !visible
810 .containsKey(features[j].type)))
815 if (features[j].featureGroup != null
816 && !groups.contains(features[j].featureGroup))
818 groups.add(features[j].featureGroup);
827 if (groups.size() > 0 && groupIndex < groups.size())
829 group = groups.get(groupIndex);
831 out.append("STARTGROUP").append(TAB);
840 for (int i = 0; i < sequences.length; i++)
842 features = sequences[i].getSequenceFeatures();
843 if (features != null)
845 for (SequenceFeature sequenceFeature : features)
847 isnonpos = sequenceFeature.begin == 0 && sequenceFeature.end == 0;
848 if ((!nonpos && isnonpos)
849 || (!isnonpos && visOnly && !visible
850 .containsKey(sequenceFeature.type)))
852 // skip if feature is nonpos and we ignore them or if we only
853 // output visible and it isn't non-pos and it's not visible
858 && (sequenceFeature.featureGroup == null || !sequenceFeature.featureGroup
864 if (group == null && sequenceFeature.featureGroup != null)
868 // we have features to output
870 if (sequenceFeature.description == null
871 || sequenceFeature.description.equals(""))
873 out.append(sequenceFeature.type).append(TAB);
877 if (sequenceFeature.links != null
878 && sequenceFeature.getDescription().indexOf("<html>") == -1)
880 out.append("<html>");
883 out.append(sequenceFeature.description);
884 if (sequenceFeature.links != null)
886 for (int l = 0; l < sequenceFeature.links.size(); l++)
888 String label = sequenceFeature.links.elementAt(l);
889 String href = label.substring(label.indexOf("|") + 1);
890 label = label.substring(0, label.indexOf("|"));
892 if (sequenceFeature.description.indexOf(href) == -1)
894 out.append(" <a href=\"" + href + "\">" + label
899 if (sequenceFeature.getDescription().indexOf("</html>") == -1)
901 out.append("</html>");
907 out.append(sequences[i].getName());
908 out.append("\t-1\t");
909 out.append(sequenceFeature.begin);
911 out.append(sequenceFeature.end);
913 out.append(sequenceFeature.type);
914 if (!Float.isNaN(sequenceFeature.score))
917 out.append(sequenceFeature.score);
926 out.append("ENDGROUP").append(TAB);
936 } while (groupIndex < groups.size() + 1);
940 return "No Features Visible";
943 return out.toString();
947 * Parse method that is called when a GFF file is dragged to the desktop
952 AlignViewportI av = getViewport();
955 if (av.getAlignment() != null)
957 dataset = av.getAlignment().getDataset();
961 // working in the applet context ?
962 dataset = av.getAlignment();
967 dataset = new Alignment(new SequenceI[] {});
970 boolean parseResult = parse(dataset, null, false, true);
973 // pass error up somehow
977 // update viewport with the dataset data ?
981 setSeqs(dataset.getSequencesArray());
986 * Implementation of unused abstract method
988 * @return error message
991 public String print()
993 return "Use printGffFormat() or printJalviewFormat()";
997 * Returns features output in GFF2 format, including hidden and non-positional
1001 * the sequences whose features are to be output
1003 * a map whose keys are the type names of visible features
1006 public String printGffFormat(SequenceI[] sequences,
1007 Map<String, Object> visible)
1009 return printGffFormat(sequences, visible, true, true);
1013 * Returns features output in GFF2 format
1016 * the sequences whose features are to be output
1018 * a map whose keys are the type names of visible features
1019 * @param outputVisibleOnly
1020 * @param includeNonPositionalFeatures
1023 public String printGffFormat(SequenceI[] sequences,
1024 Map<String, Object> visible, boolean outputVisibleOnly,
1025 boolean includeNonPositionalFeatures)
1027 StringBuilder out = new StringBuilder(256);
1028 int version = gffVersion == 0 ? 2 : gffVersion;
1029 out.append(String.format("%s %d\n", GFF_VERSION, version));
1032 for (SequenceI seq : sequences)
1034 SequenceFeature[] features = seq.getSequenceFeatures();
1035 if (features != null)
1037 for (SequenceFeature sf : features)
1039 isnonpos = sf.begin == 0 && sf.end == 0;
1040 if (!includeNonPositionalFeatures && isnonpos)
1043 * ignore non-positional features if not wanted
1047 // TODO why the test !isnonpos here?
1048 // what about not visible non-positional features?
1049 if (!isnonpos && outputVisibleOnly
1050 && !visible.containsKey(sf.type))
1053 * ignore not visible features if not wanted
1058 source = sf.featureGroup;
1061 source = sf.getDescription();
1064 out.append(seq.getName());
1068 out.append(sf.type);
1070 out.append(sf.begin);
1074 out.append(sf.score);
1077 int strand = sf.getStrand();
1078 out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1081 String phase = sf.getPhase();
1082 out.append(phase == null ? "." : phase);
1084 // miscellaneous key-values (GFF column 9)
1085 String attributes = sf.getAttributes();
1086 if (attributes != null)
1088 out.append(TAB).append(attributes);
1091 out.append(newline);
1096 return out.toString();
1100 * Returns a mapping given list of one or more Align descriptors (exonerate
1103 * @param alignedRegions
1104 * a list of "Align fromStart toStart fromCount"
1105 * @param mapIsFromCdna
1106 * if true, 'from' is dna, else 'from' is protein
1108 * either 1 (forward) or -1 (reverse)
1110 * @throws IOException
1112 protected MapList constructCodonMappingFromAlign(
1113 List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1118 throw new IOException(
1119 "Invalid strand for a codon mapping (cannot be 0)");
1121 int regions = alignedRegions.size();
1122 // arrays to hold [start, end] for each aligned region
1123 int[] fromRanges = new int[regions * 2]; // from dna
1124 int[] toRanges = new int[regions * 2]; // to protein
1125 int fromRangesIndex = 0;
1126 int toRangesIndex = 0;
1128 for (String range : alignedRegions)
1131 * Align mapFromStart mapToStart mapFromCount
1132 * e.g. if mapIsFromCdna
1133 * Align 11270 143 120
1135 * 120 bases from pos 11270 align to pos 143 in peptide
1136 * if !mapIsFromCdna this would instead be
1137 * Align 143 11270 40
1139 String[] tokens = range.split(" ");
1140 if (tokens.length != 3)
1142 throw new IOException("Wrong number of fields for Align");
1149 fromStart = Integer.parseInt(tokens[0]);
1150 toStart = Integer.parseInt(tokens[1]);
1151 fromCount = Integer.parseInt(tokens[2]);
1152 } catch (NumberFormatException nfe)
1154 throw new IOException("Invalid number in Align field: "
1155 + nfe.getMessage());
1159 * Jalview always models from dna to protein, so adjust values if the
1160 * GFF mapping is from protein to dna
1165 int temp = fromStart;
1166 fromStart = toStart;
1169 fromRanges[fromRangesIndex++] = fromStart;
1170 fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1173 * If a codon has an intron gap, there will be contiguous 'toRanges';
1174 * this is handled for us by the MapList constructor.
1175 * (It is not clear that exonerate ever generates this case)
1177 toRanges[toRangesIndex++] = toStart;
1178 toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1181 return new MapList(fromRanges, toRanges, 3, 1);
1185 * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1186 * hold the feature, or for its mapped sequence, or both, to be resolved
1187 * either later in the GFF file (##FASTA section), or when the user loads
1188 * additional sequences.
1192 * @param relaxedIdMatching
1196 protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1197 boolean relaxedIdMatching, List<SequenceI> newseqs)
1200 * GFF: seqid source type start end score strand phase [attributes]
1202 if (gffColumns.length < 5)
1204 System.err.println("Ignoring GFF feature line with too few columns ("
1205 + gffColumns.length + ")");
1210 * locate referenced sequence in alignment _or_
1211 * as a forward or external reference (SequenceDummy)
1213 String seqId = gffColumns[0];
1214 SequenceI seq = findSequence(seqId, alignment, newseqs,
1217 SequenceFeature sf = null;
1218 GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1223 sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1227 seq.addSequenceFeature(sf);
1228 while ((seq = alignment.findName(seq, seqId, true)) != null)
1230 seq.addSequenceFeature(new SequenceFeature(sf));
1233 } catch (IOException e)
1235 System.err.println("GFF parsing failed with: " + e.getMessage());
1244 * Process the 'column 9' data of the GFF file. This is less formally defined,
1245 * and its interpretation will vary depending on the tool that has generated
1251 protected void processGffColumnNine(String attributes, SequenceFeature sf)
1253 sf.setAttributes(attributes);
1256 * Parse attributes in column 9 and add them to the sequence feature's
1257 * 'otherData' table; use Note as a best proxy for description
1259 char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1260 // TODO check we don't break GFF2 values which include commas here
1261 Map<String, List<String>> nameValues = GffHelperBase
1262 .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1263 for (Entry<String, List<String>> attr : nameValues.entrySet())
1265 String values = StringUtils.listToDelimitedString(attr.getValue(),
1267 sf.setValue(attr.getKey(), values);
1268 if (NOTE.equals(attr.getKey()))
1270 sf.setDescription(values);
1276 * After encountering ##fasta in a GFF3 file, process the remainder of the
1277 * file as FAST sequence data. Any placeholder sequences created during
1278 * feature parsing are updated with the actual sequences.
1282 * @throws IOException
1284 protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1290 } catch (IOException q)
1293 FastaFile parser = new FastaFile(this);
1294 List<SequenceI> includedseqs = parser.getSeqs();
1296 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1299 * iterate over includedseqs, and replacing matching ones with newseqs
1300 * sequences. Generic iterator not used here because we modify
1301 * includedseqs as we go
1303 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1305 // search for any dummy seqs that this sequence can be used to update
1306 SequenceI includedSeq = includedseqs.get(p);
1307 SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1308 if (dummyseq != null && dummyseq instanceof SequenceDummy)
1310 // probably have the pattern wrong
1311 // idea is that a flyweight proxy for a sequence ID can be created for
1312 // 1. stable reference creation
1313 // 2. addition of annotation
1314 // 3. future replacement by a real sequence
1315 // current pattern is to create SequenceDummy objects - a convenience
1316 // constructor for a Sequence.
1317 // problem is that when promoted to a real sequence, all references
1318 // need to be updated somehow. We avoid that by keeping the same object.
1319 ((SequenceDummy) dummyseq).become(includedSeq);
1320 dummyseq.createDatasetSequence();
1323 * Update mappings so they are now to the dataset sequence
1325 for (AlignedCodonFrame mapping : align.getCodonFrames())
1327 mapping.updateToDataset(dummyseq);
1331 * replace parsed sequence with the realised forward reference
1333 includedseqs.set(p, dummyseq);
1336 * and remove from the newseqs list
1338 newseqs.remove(dummyseq);
1343 * finally add sequences to the dataset
1345 for (SequenceI seq : includedseqs)
1347 // experimental: mapping-based 'alignment' to query sequence
1348 AlignmentUtils.alignSequenceAs(seq, align,
1349 String.valueOf(align.getGapCharacter()), false, true);
1351 // rename sequences if GFF handler requested this
1352 // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1353 SequenceFeature[] sfs = seq.getSequenceFeatures();
1356 String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1357 if (newName != null)
1359 seq.setName(newName);
1362 align.addSequence(seq);
1367 * Process a ## directive
1373 * @throws IOException
1375 protected void processGffPragma(String line,
1376 Map<String, String> gffProps, AlignmentI align,
1377 List<SequenceI> newseqs) throws IOException
1380 if ("###".equals(line))
1382 // close off any open 'forward references'
1386 String[] tokens = line.substring(2).split(" ");
1387 String pragma = tokens[0];
1388 String value = tokens.length == 1 ? null : tokens[1];
1390 if ("gff-version".equalsIgnoreCase(pragma))
1396 // value may be e.g. "3.1.2"
1397 gffVersion = Integer.parseInt(value.split("\\.")[0]);
1398 } catch (NumberFormatException e)
1404 else if ("sequence-region".equalsIgnoreCase(pragma))
1406 // could capture <seqid start end> if wanted here
1408 else if ("feature-ontology".equalsIgnoreCase(pragma))
1410 // should resolve against the specified feature ontology URI
1412 else if ("attribute-ontology".equalsIgnoreCase(pragma))
1414 // URI of attribute ontology - not currently used in GFF3
1416 else if ("source-ontology".equalsIgnoreCase(pragma))
1418 // URI of source ontology - not currently used in GFF3
1420 else if ("species-build".equalsIgnoreCase(pragma))
1422 // save URI of specific NCBI taxon version of annotations
1423 gffProps.put("species-build", value);
1425 else if ("fasta".equalsIgnoreCase(pragma))
1427 // process the rest of the file as a fasta file and replace any dummy
1429 processAsFasta(align, newseqs);
1433 System.err.println("Ignoring unknown pragma: " + line);