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 (int j = 0; j < features.length; j++)
847 isnonpos = features[j].begin == 0 && features[j].end == 0;
848 if ((!nonpos && isnonpos)
849 || (!isnonpos && visOnly && !visible
850 .containsKey(features[j].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 && (features[j].featureGroup == null || !features[j].featureGroup
864 if (group == null && features[j].featureGroup != null)
868 // we have features to output
870 if (features[j].description == null
871 || features[j].description.equals(""))
873 out.append(features[j].type).append(TAB);
877 if (features[j].links != null
878 && features[j].getDescription().indexOf("<html>") == -1)
880 out.append("<html>");
883 out.append(features[j].description + " ");
884 if (features[j].links != null)
886 for (int l = 0; l < features[j].links.size(); l++)
888 String label = features[j].links.elementAt(l).toString();
889 String href = label.substring(label.indexOf("|") + 1);
890 label = label.substring(0, label.indexOf("|"));
892 if (features[j].description.indexOf(href) == -1)
894 out.append("<a href=\"" + href + "\">" + label + "</a>");
898 if (features[j].getDescription().indexOf("</html>") == -1)
900 out.append("</html>");
906 out.append(sequences[i].getName());
907 out.append("\t-1\t");
908 out.append(features[j].begin);
910 out.append(features[j].end);
912 out.append(features[j].type);
913 if (!Float.isNaN(features[j].score))
916 out.append(features[j].score);
925 out.append("ENDGROUP").append(TAB);
935 } while (groupIndex < groups.size() + 1);
939 return "No Features Visible";
942 return out.toString();
946 * Parse method that is called when a GFF file is dragged to the desktop
951 AlignViewportI av = getViewport();
954 if (av.getAlignment() != null)
956 dataset = av.getAlignment().getDataset();
960 // working in the applet context ?
961 dataset = av.getAlignment();
966 dataset = new Alignment(new SequenceI[] {});
969 boolean parseResult = parse(dataset, null, false, true);
972 // pass error up somehow
976 // update viewport with the dataset data ?
980 setSeqs(dataset.getSequencesArray());
985 * Implementation of unused abstract method
987 * @return error message
990 public String print()
992 return "Use printGffFormat() or printJalviewFormat()";
996 * Returns features output in GFF2 format, including hidden and non-positional
1000 * the sequences whose features are to be output
1002 * a map whose keys are the type names of visible features
1005 public String printGffFormat(SequenceI[] sequences,
1006 Map<String, Object> visible)
1008 return printGffFormat(sequences, visible, true, true);
1012 * Returns features output in GFF2 format
1015 * the sequences whose features are to be output
1017 * a map whose keys are the type names of visible features
1018 * @param outputVisibleOnly
1019 * @param includeNonPositionalFeatures
1022 public String printGffFormat(SequenceI[] sequences,
1023 Map<String, Object> visible, boolean outputVisibleOnly,
1024 boolean includeNonPositionalFeatures)
1026 StringBuilder out = new StringBuilder(256);
1027 out.append(String.format("%s %d\n", GFF_VERSION, gffVersion));
1030 for (SequenceI seq : sequences)
1032 SequenceFeature[] features = seq.getSequenceFeatures();
1033 if (features != null)
1035 for (SequenceFeature sf : features)
1037 isnonpos = sf.begin == 0 && sf.end == 0;
1038 if (!includeNonPositionalFeatures && isnonpos)
1041 * ignore non-positional features if not wanted
1045 // TODO why the test !isnonpos here?
1046 // what about not visible non-positional features?
1047 if (!isnonpos && outputVisibleOnly
1048 && !visible.containsKey(sf.type))
1051 * ignore not visible features if not wanted
1056 source = sf.featureGroup;
1059 source = sf.getDescription();
1062 out.append(seq.getName());
1066 out.append(sf.type);
1068 out.append(sf.begin);
1072 out.append(sf.score);
1075 int strand = sf.getStrand();
1076 out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1079 String phase = sf.getPhase();
1080 out.append(phase == null ? "." : phase);
1082 // miscellaneous key-values (GFF column 9)
1083 String attributes = sf.getAttributes();
1084 if (attributes != null)
1086 out.append(TAB).append(attributes);
1089 out.append(newline);
1094 return out.toString();
1098 * Returns a mapping given list of one or more Align descriptors (exonerate
1101 * @param alignedRegions
1102 * a list of "Align fromStart toStart fromCount"
1103 * @param mapIsFromCdna
1104 * if true, 'from' is dna, else 'from' is protein
1106 * either 1 (forward) or -1 (reverse)
1108 * @throws IOException
1110 protected MapList constructCodonMappingFromAlign(
1111 List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1116 throw new IOException(
1117 "Invalid strand for a codon mapping (cannot be 0)");
1119 int regions = alignedRegions.size();
1120 // arrays to hold [start, end] for each aligned region
1121 int[] fromRanges = new int[regions * 2]; // from dna
1122 int[] toRanges = new int[regions * 2]; // to protein
1123 int fromRangesIndex = 0;
1124 int toRangesIndex = 0;
1126 for (String range : alignedRegions)
1129 * Align mapFromStart mapToStart mapFromCount
1130 * e.g. if mapIsFromCdna
1131 * Align 11270 143 120
1133 * 120 bases from pos 11270 align to pos 143 in peptide
1134 * if !mapIsFromCdna this would instead be
1135 * Align 143 11270 40
1137 String[] tokens = range.split(" ");
1138 if (tokens.length != 3)
1140 throw new IOException("Wrong number of fields for Align");
1147 fromStart = Integer.parseInt(tokens[0]);
1148 toStart = Integer.parseInt(tokens[1]);
1149 fromCount = Integer.parseInt(tokens[2]);
1150 } catch (NumberFormatException nfe)
1152 throw new IOException("Invalid number in Align field: "
1153 + nfe.getMessage());
1157 * Jalview always models from dna to protein, so adjust values if the
1158 * GFF mapping is from protein to dna
1163 int temp = fromStart;
1164 fromStart = toStart;
1167 fromRanges[fromRangesIndex++] = fromStart;
1168 fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1171 * If a codon has an intron gap, there will be contiguous 'toRanges';
1172 * this is handled for us by the MapList constructor.
1173 * (It is not clear that exonerate ever generates this case)
1175 toRanges[toRangesIndex++] = toStart;
1176 toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1179 return new MapList(fromRanges, toRanges, 3, 1);
1183 * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1184 * hold the feature, or for its mapped sequence, or both, to be resolved
1185 * either later in the GFF file (##FASTA section), or when the user loads
1186 * additional sequences.
1190 * @param relaxedIdMatching
1194 protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1195 boolean relaxedIdMatching, List<SequenceI> newseqs)
1198 * GFF: seqid source type start end score strand phase [attributes]
1200 if (gffColumns.length < 5)
1202 System.err.println("Ignoring GFF feature line with too few columns ("
1203 + gffColumns.length + ")");
1208 * locate referenced sequence in alignment _or_
1209 * as a forward or external reference (SequenceDummy)
1211 String seqId = gffColumns[0];
1212 SequenceI seq = findSequence(seqId, alignment, newseqs,
1215 SequenceFeature sf = null;
1216 GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1221 sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1225 seq.addSequenceFeature(sf);
1226 while ((seq = alignment.findName(seq, seqId, true)) != null)
1228 seq.addSequenceFeature(new SequenceFeature(sf));
1231 } catch (IOException e)
1233 System.err.println("GFF parsing failed with: " + e.getMessage());
1242 * Process the 'column 9' data of the GFF file. This is less formally defined,
1243 * and its interpretation will vary depending on the tool that has generated
1249 protected void processGffColumnNine(String attributes, SequenceFeature sf)
1251 sf.setAttributes(attributes);
1254 * Parse attributes in column 9 and add them to the sequence feature's
1255 * 'otherData' table; use Note as a best proxy for description
1257 char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1258 // TODO check we don't break GFF2 values which include commas here
1259 Map<String, List<String>> nameValues = GffHelperBase
1260 .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1261 for (Entry<String, List<String>> attr : nameValues.entrySet())
1263 String values = StringUtils.listToDelimitedString(attr.getValue(),
1265 sf.setValue(attr.getKey(), values);
1266 if (NOTE.equals(attr.getKey()))
1268 sf.setDescription(values);
1274 * After encountering ##fasta in a GFF3 file, process the remainder of the
1275 * file as FAST sequence data. Any placeholder sequences created during
1276 * feature parsing are updated with the actual sequences.
1280 * @throws IOException
1282 protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1288 } catch (IOException q)
1291 FastaFile parser = new FastaFile(this);
1292 List<SequenceI> includedseqs = parser.getSeqs();
1294 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1297 * iterate over includedseqs, and replacing matching ones with newseqs
1298 * sequences. Generic iterator not used here because we modify
1299 * includedseqs as we go
1301 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1303 // search for any dummy seqs that this sequence can be used to update
1304 SequenceI includedSeq = includedseqs.get(p);
1305 SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1306 if (dummyseq != null && dummyseq instanceof SequenceDummy)
1308 // probably have the pattern wrong
1309 // idea is that a flyweight proxy for a sequence ID can be created for
1310 // 1. stable reference creation
1311 // 2. addition of annotation
1312 // 3. future replacement by a real sequence
1313 // current pattern is to create SequenceDummy objects - a convenience
1314 // constructor for a Sequence.
1315 // problem is that when promoted to a real sequence, all references
1316 // need to be updated somehow. We avoid that by keeping the same object.
1317 ((SequenceDummy) dummyseq).become(includedSeq);
1318 dummyseq.createDatasetSequence();
1321 * Update mappings so they are now to the dataset sequence
1323 for (AlignedCodonFrame mapping : align.getCodonFrames())
1325 mapping.updateToDataset(dummyseq);
1329 * replace parsed sequence with the realised forward reference
1331 includedseqs.set(p, dummyseq);
1334 * and remove from the newseqs list
1336 newseqs.remove(dummyseq);
1341 * finally add sequences to the dataset
1343 for (SequenceI seq : includedseqs)
1345 // experimental: mapping-based 'alignment' to query sequence
1346 AlignmentUtils.alignSequenceAs(seq, align,
1347 String.valueOf(align.getGapCharacter()), false, true);
1349 // rename sequences if GFF handler requested this
1350 // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1351 SequenceFeature[] sfs = seq.getSequenceFeatures();
1354 String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1355 if (newName != null)
1357 seq.setName(newName);
1360 align.addSequence(seq);
1365 * Process a ## directive
1371 * @throws IOException
1373 protected void processGffPragma(String line,
1374 Map<String, String> gffProps, AlignmentI align,
1375 List<SequenceI> newseqs) throws IOException
1378 if ("###".equals(line))
1380 // close off any open 'forward references'
1384 String[] tokens = line.substring(2).split(" ");
1385 String pragma = tokens[0];
1386 String value = tokens.length == 1 ? null : tokens[1];
1388 if ("gff-version".equalsIgnoreCase(pragma))
1394 // value may be e.g. "3.1.2"
1395 gffVersion = Integer.parseInt(value.split("\\.")[0]);
1396 } catch (NumberFormatException e)
1402 else if ("sequence-region".equalsIgnoreCase(pragma))
1404 // could capture <seqid start end> if wanted here
1406 else if ("feature-ontology".equalsIgnoreCase(pragma))
1408 // should resolve against the specified feature ontology URI
1410 else if ("attribute-ontology".equalsIgnoreCase(pragma))
1412 // URI of attribute ontology - not currently used in GFF3
1414 else if ("source-ontology".equalsIgnoreCase(pragma))
1416 // URI of source ontology - not currently used in GFF3
1418 else if ("species-build".equalsIgnoreCase(pragma))
1420 // save URI of specific NCBI taxon version of annotations
1421 gffProps.put("species-build", value);
1423 else if ("fasta".equalsIgnoreCase(pragma))
1425 // process the rest of the file as a fasta file and replace any dummy
1427 processAsFasta(align, newseqs);
1431 System.err.println("Ignoring unknown pragma: " + line);