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 FRAME = "FRAME";
79 protected static final String TAB = "\t";
81 protected static final String GFF_VERSION = "##gff-version";
83 private AlignmentI lastmatchedAl = null;
85 private SequenceIdMatcher matcher = null;
87 protected AlignmentI dataset;
89 protected int gffVersion;
92 * Creates a new FeaturesFile object.
99 * Constructor which does not parse the file immediately
103 * @throws IOException
105 public FeaturesFile(String inFile, String type) throws IOException
107 super(false, inFile, type);
112 * @throws IOException
114 public FeaturesFile(FileParse source) throws IOException
120 * Constructor that optionally parses the file immediately
122 * @param parseImmediately
125 * @throws IOException
127 public FeaturesFile(boolean parseImmediately, String inFile, String type)
130 super(parseImmediately, inFile, type);
134 * Parse GFF or sequence features file using case-independent matching,
138 * - alignment/dataset containing sequences that are to be annotated
140 * - hashtable to store feature colour definitions
142 * - process html strings into plain text
143 * @return true if features were added
145 public boolean parse(AlignmentI align, Map<String, Object> colours,
148 return parse(align, colours, removeHTML, false);
152 * Extends the default addProperties by also adding peptide-to-cDNA mappings
153 * (if any) derived while parsing a GFF file
156 public void addProperties(AlignmentI al)
158 super.addProperties(al);
159 if (dataset != null && dataset.getCodonFrames() != null)
161 AlignmentI ds = (al.getDataset() == null) ? al : al.getDataset();
162 for (AlignedCodonFrame codons : dataset.getCodonFrames())
164 ds.addCodonFrame(codons);
170 * Parse GFF or Jalview format sequence features file
173 * - alignment/dataset containing sequences that are to be annotated
175 * - hashtable to store feature colour definitions
177 * - process html strings into plain text
178 * @param relaxedIdmatching
179 * - when true, ID matches to compound sequence IDs are allowed
180 * @return true if features were added
182 public boolean parse(AlignmentI align, Map<String, Object> colours,
183 boolean removeHTML, boolean relaxedIdmatching)
185 Map<String, String> gffProps = new HashMap<String, String>();
187 * keep track of any sequences we try to create from the data
189 List<SequenceI> newseqs = new ArrayList<SequenceI>();
195 String featureGroup = null;
197 while ((line = nextLine()) != null)
199 // skip comments/process pragmas
200 if (line.length() == 0 || line.startsWith("#"))
202 if (line.toLowerCase().startsWith("##"))
204 processGffPragma(line, gffProps, align, newseqs);
209 gffColumns = line.split("\\t"); // tab as regex
210 if (gffColumns.length == 1)
212 if (line.trim().equalsIgnoreCase("GFF"))
215 * Jalview features file with appended GFF
216 * assume GFF2 (though it may declare ##gff-version 3)
223 if (gffColumns.length > 1 && gffColumns.length < 4)
226 * if 2 or 3 tokens, we anticipate either 'startgroup', 'endgroup' or
227 * a feature type colour specification
229 String ft = gffColumns[0];
230 if (ft.equalsIgnoreCase("startgroup"))
232 featureGroup = gffColumns[1];
234 else if (ft.equalsIgnoreCase("endgroup"))
236 // We should check whether this is the current group,
237 // but at present theres no way of showing more than 1 group
242 parseFeatureColour(line, ft, gffColumns, colours);
248 * if not a comment, GFF pragma, startgroup, endgroup or feature
249 * colour specification, that just leaves a feature details line
250 * in either Jalview or GFF format
254 parseJalviewFeature(line, gffColumns, align, colours, removeHTML,
255 relaxedIdmatching, featureGroup);
259 parseGff(gffColumns, align, relaxedIdmatching, newseqs);
263 } catch (Exception ex)
265 // should report somewhere useful for UI if necessary
266 warningMessage = ((warningMessage == null) ? "" : warningMessage)
267 + "Parsing error at\n" + line;
268 System.out.println("Error parsing feature file: " + ex + "\n" + line);
269 ex.printStackTrace(System.err);
278 * Try to parse a Jalview format feature specification and add it as a
279 * sequence feature to any matching sequences in the alignment. Returns true
280 * if successful (a feature was added), or false if not.
285 * @param featureColours
287 * @param relaxedIdmatching
288 * @param featureGroup
290 protected boolean parseJalviewFeature(String line, String[] gffColumns,
291 AlignmentI alignment, Map<String, Object> featureColours,
292 boolean removeHTML, boolean relaxedIdMatching, String featureGroup)
295 * tokens: description seqid seqIndex start end type [score]
297 if (gffColumns.length < 6)
299 System.err.println("Ignoring feature line '" + line
300 + "' with too few columns (" + gffColumns.length + ")");
303 String desc = gffColumns[0];
304 String seqId = gffColumns[1];
305 SequenceI seq = findSequence(seqId, alignment, null, relaxedIdMatching);
307 if (!ID_NOT_SPECIFIED.equals(seqId))
309 seq = findSequence(seqId, alignment, null, relaxedIdMatching);
315 String seqIndex = gffColumns[2];
318 int idx = Integer.parseInt(seqIndex);
319 seq = alignment.getSequenceAt(idx);
320 } catch (NumberFormatException ex)
322 System.err.println("Invalid sequence index: " + seqIndex);
328 System.out.println("Sequence not found: " + line);
332 int startPos = Integer.parseInt(gffColumns[3]);
333 int endPos = Integer.parseInt(gffColumns[4]);
335 String ft = gffColumns[5];
337 if (!featureColours.containsKey(ft))
340 * Perhaps an old style groups file with no colours -
341 * synthesize a colour from the feature type
343 UserColourScheme ucs = new UserColourScheme(ft);
344 featureColours.put(ft, ucs.findColour('A'));
346 SequenceFeature sf = new SequenceFeature(ft, desc, "", startPos,
347 endPos, featureGroup);
348 if (gffColumns.length > 6)
350 float score = Float.NaN;
353 score = new Float(gffColumns[6]).floatValue();
354 // update colourgradient bounds if allowed to
355 } catch (NumberFormatException ex)
362 parseDescriptionHTML(sf, removeHTML);
364 seq.addSequenceFeature(sf);
367 && (seq = alignment.findName(seq, seqId, false)) != null)
369 seq.addSequenceFeature(new SequenceFeature(sf));
375 * Process a feature type colour specification
378 * the current input line (for error messages only)
380 * the first token on the line
382 * holds tokens on the line
384 * map to which to add derived colour specification
386 protected void parseFeatureColour(String line, String featureType,
387 String[] gffColumns, Map<String, Object> colours)
389 Object colour = null;
390 String colscheme = gffColumns[1];
391 if (colscheme.indexOf("|") > -1
392 || colscheme.trim().equalsIgnoreCase("label"))
394 colour = parseGraduatedColourScheme(line, colscheme);
398 UserColourScheme ucs = new UserColourScheme(colscheme);
399 colour = ucs.findColour('A');
403 colours.put(featureType, colour);
408 * Parse a Jalview graduated colour descriptor
411 * @param colourDescriptor
414 protected GraduatedColor parseGraduatedColourScheme(String line,
415 String colourDescriptor)
417 // Parse '|' separated graduated colourscheme fields:
418 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
419 // can either provide 'label' only, first is optional, next two
420 // colors are required (but may be
421 // left blank), next is optional, nxt two min/max are required.
422 // first is either 'label'
423 // first/second and third are both hexadecimal or word equivalent
425 // next two are values parsed as floats.
426 // fifth is either 'above','below', or 'none'.
427 // sixth is a float value and only required when fifth is either
428 // 'above' or 'below'.
429 StringTokenizer gcol = new StringTokenizer(colourDescriptor, "|", true);
431 float min = Float.MIN_VALUE, max = Float.MAX_VALUE;
432 boolean labelCol = false;
434 String mincol = gcol.nextToken();
438 .println("Expected either 'label' or a colour specification in the line: "
442 String maxcol = null;
443 if (mincol.toLowerCase().indexOf("label") == 0)
446 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip '|'
447 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
449 String abso = null, minval, maxval;
452 // at least four more tokens
453 if (mincol.equals("|"))
459 gcol.nextToken(); // skip next '|'
461 // continue parsing rest of line
462 maxcol = gcol.nextToken();
463 if (maxcol.equals("|"))
469 gcol.nextToken(); // skip next '|'
471 abso = gcol.nextToken();
472 gcol.nextToken(); // skip next '|'
473 if (abso.toLowerCase().indexOf("abso") != 0)
480 minval = gcol.nextToken();
481 gcol.nextToken(); // skip next '|'
483 maxval = gcol.nextToken();
484 if (gcol.hasMoreTokens())
486 gcol.nextToken(); // skip next '|'
490 if (minval.length() > 0)
492 min = Float.valueOf(minval);
494 } catch (Exception e)
497 .println("Couldn't parse the minimum value for graduated colour for type ("
499 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
504 if (maxval.length() > 0)
506 max = Float.valueOf(maxval);
508 } catch (Exception e)
511 .println("Couldn't parse the maximum value for graduated colour for type ("
512 + colourDescriptor + ")");
518 // add in some dummy min/max colours for the label-only
524 GraduatedColor colour = null;
527 colour = new GraduatedColor(
528 new UserColourScheme(mincol).findColour('A'),
529 new UserColourScheme(maxcol).findColour('A'), min, max);
530 } catch (Exception e)
532 System.err.println("Couldn't parse the graduated colour scheme ("
533 + colourDescriptor + ")");
538 colour.setColourByLabel(labelCol);
539 colour.setAutoScaled(abso == null);
540 // add in any additional parameters
541 String ttype = null, tval = null;
542 if (gcol.hasMoreTokens())
544 // threshold type and possibly a threshold value
545 ttype = gcol.nextToken();
546 if (ttype.toLowerCase().startsWith("below"))
548 colour.setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
550 else if (ttype.toLowerCase().startsWith("above"))
552 colour.setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
556 colour.setThreshType(AnnotationColourGradient.NO_THRESHOLD);
557 if (!ttype.toLowerCase().startsWith("no"))
559 System.err.println("Ignoring unrecognised threshold type : "
564 if (colour.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
569 tval = gcol.nextToken();
570 colour.setThresh(new Float(tval).floatValue());
571 } catch (Exception e)
573 System.err.println("Couldn't parse threshold value as a float: ("
578 // parse the thresh-is-min token ?
579 if (gcol.hasMoreTokens())
582 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
583 while (gcol.hasMoreTokens())
585 System.err.println("|" + gcol.nextToken());
587 System.err.println("\n");
594 * clear any temporary handles used to speed up ID matching
596 protected void resetMatcher()
598 lastmatchedAl = null;
603 * Returns a sequence matching the given id, as follows
605 * <li>strict matching is on exact sequence name</li>
606 * <li>relaxed matching allows matching on a token within the sequence name,
608 * <li>first tries to find a match in the alignment sequences</li>
609 * <li>else tries to find a match in the new sequences already generated while
610 * parsing the features file</li>
611 * <li>else creates a new placeholder sequence, adds it to the new sequences
612 * list, and returns it</li>
618 * @param relaxedIdMatching
622 protected SequenceI findSequence(String seqId, AlignmentI align,
623 List<SequenceI> newseqs, boolean relaxedIdMatching)
625 // TODO encapsulate in SequenceIdMatcher, share the matcher
626 // with the GffHelper (removing code duplication)
627 SequenceI match = null;
628 if (relaxedIdMatching)
630 if (lastmatchedAl != align)
632 lastmatchedAl = align;
633 matcher = new SequenceIdMatcher(align.getSequencesArray());
636 matcher.addAll(newseqs);
639 match = matcher.findIdMatch(seqId);
643 match = align.findName(seqId, true);
644 if (match == null && newseqs != null)
646 for (SequenceI m : newseqs)
648 if (seqId.equals(m.getName()))
656 if (match == null && newseqs != null)
658 match = new SequenceDummy(seqId);
659 if (relaxedIdMatching)
661 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
663 // add dummy sequence to the newseqs list
669 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
671 if (sf.getDescription() == null)
675 ParseHtmlBodyAndLinks parsed = new ParseHtmlBodyAndLinks(
676 sf.getDescription(), removeHTML, newline);
678 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
680 for (String link : parsed.getLinks())
688 * generate a features file for seqs includes non-pos features by default.
691 * source of sequence features
693 * hash of feature types and colours
694 * @return features file contents
696 public String printJalviewFormat(SequenceI[] sequences,
697 Map<String, Object> visible)
699 return printJalviewFormat(sequences, visible, true, true);
703 * generate a features file for seqs with colours from visible (if any)
708 * hash of Colours for each feature type
710 * when true only feature types in 'visible' will be output
712 * indicates if non-positional features should be output (regardless
714 * @return features file contents
716 public String printJalviewFormat(SequenceI[] sequences,
717 Map<String, Object> visible, boolean visOnly, boolean nonpos)
719 StringBuilder out = new StringBuilder(256);
720 boolean featuresGen = false;
721 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
723 // no point continuing.
724 return "No Features Visible";
727 if (visible != null && visOnly)
729 // write feature colours only if we're given them and we are generating
731 // TODO: decide if feature links should also be written here ?
732 Iterator<String> en = visible.keySet().iterator();
733 String featureType, color;
736 featureType = en.next().toString();
738 if (visible.get(featureType) instanceof GraduatedColor)
740 GraduatedColor gc = (GraduatedColor) visible.get(featureType);
741 color = (gc.isColourByLabel() ? "label|" : "")
742 + Format.getHexString(gc.getMinColor()) + "|"
743 + Format.getHexString(gc.getMaxColor())
744 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
746 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
748 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
754 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
756 System.err.println("WARNING: Unsupported threshold type ("
757 + gc.getThreshType() + ") : Assuming 'above'");
762 color += "|" + gc.getThresh();
769 else if (visible.get(featureType) instanceof Color)
771 color = Format.getHexString((Color) visible.get(featureType));
775 // legacy support for integer objects containing colour triplet values
776 color = Format.getHexString(new Color(Integer.parseInt(visible
777 .get(featureType).toString())));
779 out.append(featureType);
785 // Work out which groups are both present and visible
786 List<String> groups = new ArrayList<String>();
788 boolean isnonpos = false;
790 SequenceFeature[] features;
791 for (int i = 0; i < sequences.length; i++)
793 features = sequences[i].getSequenceFeatures();
794 if (features != null)
796 for (int j = 0; j < features.length; j++)
798 isnonpos = features[j].begin == 0 && features[j].end == 0;
799 if ((!nonpos && isnonpos)
800 || (!isnonpos && visOnly && !visible
801 .containsKey(features[j].type)))
806 if (features[j].featureGroup != null
807 && !groups.contains(features[j].featureGroup))
809 groups.add(features[j].featureGroup);
818 if (groups.size() > 0 && groupIndex < groups.size())
820 group = groups.get(groupIndex);
822 out.append("STARTGROUP").append(TAB);
831 for (int i = 0; i < sequences.length; i++)
833 features = sequences[i].getSequenceFeatures();
834 if (features != null)
836 for (int j = 0; j < features.length; j++)
838 isnonpos = features[j].begin == 0 && features[j].end == 0;
839 if ((!nonpos && isnonpos)
840 || (!isnonpos && visOnly && !visible
841 .containsKey(features[j].type)))
843 // skip if feature is nonpos and we ignore them or if we only
844 // output visible and it isn't non-pos and it's not visible
849 && (features[j].featureGroup == null || !features[j].featureGroup
855 if (group == null && features[j].featureGroup != null)
859 // we have features to output
861 if (features[j].description == null
862 || features[j].description.equals(""))
864 out.append(features[j].type).append(TAB);
868 if (features[j].links != null
869 && features[j].getDescription().indexOf("<html>") == -1)
871 out.append("<html>");
874 out.append(features[j].description + " ");
875 if (features[j].links != null)
877 for (int l = 0; l < features[j].links.size(); l++)
879 String label = features[j].links.elementAt(l).toString();
880 String href = label.substring(label.indexOf("|") + 1);
881 label = label.substring(0, label.indexOf("|"));
883 if (features[j].description.indexOf(href) == -1)
885 out.append("<a href=\"" + href + "\">" + label + "</a>");
889 if (features[j].getDescription().indexOf("</html>") == -1)
891 out.append("</html>");
897 out.append(sequences[i].getName());
898 out.append("\t-1\t");
899 out.append(features[j].begin);
901 out.append(features[j].end);
903 out.append(features[j].type);
904 if (!Float.isNaN(features[j].score))
907 out.append(features[j].score);
916 out.append("ENDGROUP").append(TAB);
926 } while (groupIndex < groups.size() + 1);
930 return "No Features Visible";
933 return out.toString();
937 * Parse method that is called when a GFF file is dragged to the desktop
942 AlignViewportI av = getViewport();
945 if (av.getAlignment() != null)
947 dataset = av.getAlignment().getDataset();
951 // working in the applet context ?
952 dataset = av.getAlignment();
957 dataset = new Alignment(new SequenceI[] {});
960 boolean parseResult = parse(dataset, null, false, true);
963 // pass error up somehow
967 // update viewport with the dataset data ?
971 setSeqs(dataset.getSequencesArray());
976 * Implementation of unused abstract method
978 * @return error message
981 public String print()
983 return "Use printGffFormat() or printJalviewFormat()";
987 * Returns features output in GFF2 format, including hidden and non-positional
991 * the sequences whose features are to be output
993 * a map whose keys are the type names of visible features
996 public String printGffFormat(SequenceI[] sequences,
997 Map<String, Object> visible)
999 return printGffFormat(sequences, visible, true, true);
1003 * Returns features output in GFF2 format
1006 * the sequences whose features are to be output
1008 * a map whose keys are the type names of visible features
1009 * @param outputVisibleOnly
1010 * @param includeNonPositionalFeatures
1013 public String printGffFormat(SequenceI[] sequences,
1014 Map<String, Object> visible, boolean outputVisibleOnly,
1015 boolean includeNonPositionalFeatures)
1017 StringBuilder out = new StringBuilder(256);
1018 out.append(String.format("%s %d\n", GFF_VERSION, gffVersion));
1021 for (SequenceI seq : sequences)
1023 SequenceFeature[] features = seq.getSequenceFeatures();
1024 if (features != null)
1026 for (SequenceFeature sf : features)
1028 isnonpos = sf.begin == 0 && sf.end == 0;
1029 if (!includeNonPositionalFeatures && isnonpos)
1032 * ignore non-positional features if not wanted
1036 // TODO why the test !isnonpos here?
1037 // what about not visible non-positional features?
1038 if (!isnonpos && outputVisibleOnly
1039 && !visible.containsKey(sf.type))
1042 * ignore not visible features if not wanted
1047 source = sf.featureGroup;
1050 source = sf.getDescription();
1053 out.append(seq.getName());
1057 out.append(sf.type);
1059 out.append(sf.begin);
1063 out.append(sf.score);
1066 int strand = sf.getStrand();
1067 out.append(strand == 1 ? "+" : (strand == -1 ? "-" : "."));
1070 out.append(sf.getValue(FRAME, "."));
1072 // miscellaneous key-values (GFF column 9)
1073 String attributes = sf.getAttributes();
1074 if (attributes != null)
1076 out.append(TAB).append(attributes);
1079 out.append(newline);
1084 return out.toString();
1088 * Returns a mapping given list of one or more Align descriptors (exonerate
1091 * @param alignedRegions
1092 * a list of "Align fromStart toStart fromCount"
1093 * @param mapIsFromCdna
1094 * if true, 'from' is dna, else 'from' is protein
1096 * either 1 (forward) or -1 (reverse)
1098 * @throws IOException
1100 protected MapList constructCodonMappingFromAlign(
1101 List<String> alignedRegions, boolean mapIsFromCdna, int strand)
1106 throw new IOException(
1107 "Invalid strand for a codon mapping (cannot be 0)");
1109 int regions = alignedRegions.size();
1110 // arrays to hold [start, end] for each aligned region
1111 int[] fromRanges = new int[regions * 2]; // from dna
1112 int[] toRanges = new int[regions * 2]; // to protein
1113 int fromRangesIndex = 0;
1114 int toRangesIndex = 0;
1116 for (String range : alignedRegions)
1119 * Align mapFromStart mapToStart mapFromCount
1120 * e.g. if mapIsFromCdna
1121 * Align 11270 143 120
1123 * 120 bases from pos 11270 align to pos 143 in peptide
1124 * if !mapIsFromCdna this would instead be
1125 * Align 143 11270 40
1127 String[] tokens = range.split(" ");
1128 if (tokens.length != 3)
1130 throw new IOException("Wrong number of fields for Align");
1137 fromStart = Integer.parseInt(tokens[0]);
1138 toStart = Integer.parseInt(tokens[1]);
1139 fromCount = Integer.parseInt(tokens[2]);
1140 } catch (NumberFormatException nfe)
1142 throw new IOException("Invalid number in Align field: "
1143 + nfe.getMessage());
1147 * Jalview always models from dna to protein, so adjust values if the
1148 * GFF mapping is from protein to dna
1153 int temp = fromStart;
1154 fromStart = toStart;
1157 fromRanges[fromRangesIndex++] = fromStart;
1158 fromRanges[fromRangesIndex++] = fromStart + strand * (fromCount - 1);
1161 * If a codon has an intron gap, there will be contiguous 'toRanges';
1162 * this is handled for us by the MapList constructor.
1163 * (It is not clear that exonerate ever generates this case)
1165 toRanges[toRangesIndex++] = toStart;
1166 toRanges[toRangesIndex++] = toStart + (fromCount - 1) / 3;
1169 return new MapList(fromRanges, toRanges, 3, 1);
1173 * Parse a GFF format feature. This may include creating a 'dummy' sequence to
1174 * hold the feature, or for its mapped sequence, or both, to be resolved
1175 * either later in the GFF file (##FASTA section), or when the user loads
1176 * additional sequences.
1180 * @param relaxedIdMatching
1184 protected SequenceI parseGff(String[] gffColumns, AlignmentI alignment,
1185 boolean relaxedIdMatching, List<SequenceI> newseqs)
1188 * GFF: seqid source type start end score strand phase [attributes]
1190 if (gffColumns.length < 5)
1192 System.err.println("Ignoring GFF feature line with too few columns ("
1193 + gffColumns.length + ")");
1198 * locate referenced sequence in alignment _or_
1199 * as a forward or external reference (SequenceDummy)
1201 String seqId = gffColumns[0];
1202 SequenceI seq = findSequence(seqId, alignment, newseqs,
1205 SequenceFeature sf = null;
1206 GffHelperI helper = GffHelperFactory.getHelper(gffColumns);
1211 sf = helper.processGff(seq, gffColumns, alignment, newseqs,
1215 seq.addSequenceFeature(sf);
1216 while ((seq = alignment.findName(seq, seqId, true)) != null)
1218 seq.addSequenceFeature(new SequenceFeature(sf));
1221 } catch (IOException e)
1223 System.err.println("GFF parsing failed with: " + e.getMessage());
1232 * Process the 'column 9' data of the GFF file. This is less formally defined,
1233 * and its interpretation will vary depending on the tool that has generated
1239 protected void processGffColumnNine(String attributes, SequenceFeature sf)
1241 sf.setAttributes(attributes);
1244 * Parse attributes in column 9 and add them to the sequence feature's
1245 * 'otherData' table; use Note as a best proxy for description
1247 char nameValueSeparator = gffVersion == 3 ? '=' : ' ';
1248 // TODO check we don't break GFF2 values which include commas here
1249 Map<String, List<String>> nameValues = GffHelperBase
1250 .parseNameValuePairs(attributes, ";", nameValueSeparator, ",");
1251 for (Entry<String, List<String>> attr : nameValues.entrySet())
1253 String values = StringUtils.listToDelimitedString(attr.getValue(),
1255 sf.setValue(attr.getKey(), values);
1256 if (NOTE.equals(attr.getKey()))
1258 sf.setDescription(values);
1264 * After encountering ##fasta in a GFF3 file, process the remainder of the
1265 * file as FAST sequence data. Any placeholder sequences created during
1266 * feature parsing are updated with the actual sequences.
1270 * @throws IOException
1272 protected void processAsFasta(AlignmentI align, List<SequenceI> newseqs)
1278 } catch (IOException q)
1281 FastaFile parser = new FastaFile(this);
1282 List<SequenceI> includedseqs = parser.getSeqs();
1284 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
1287 * iterate over includedseqs, and replacing matching ones with newseqs
1288 * sequences. Generic iterator not used here because we modify
1289 * includedseqs as we go
1291 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
1293 // search for any dummy seqs that this sequence can be used to update
1294 SequenceI includedSeq = includedseqs.get(p);
1295 SequenceI dummyseq = smatcher.findIdMatch(includedSeq);
1296 if (dummyseq != null && dummyseq instanceof SequenceDummy)
1298 // probably have the pattern wrong
1299 // idea is that a flyweight proxy for a sequence ID can be created for
1300 // 1. stable reference creation
1301 // 2. addition of annotation
1302 // 3. future replacement by a real sequence
1303 // current pattern is to create SequenceDummy objects - a convenience
1304 // constructor for a Sequence.
1305 // problem is that when promoted to a real sequence, all references
1306 // need to be updated somehow. We avoid that by keeping the same object.
1307 ((SequenceDummy) dummyseq).become(includedSeq);
1308 dummyseq.createDatasetSequence();
1311 * Update mappings so they are now to the dataset sequence
1313 for (AlignedCodonFrame mapping : align.getCodonFrames())
1315 mapping.updateToDataset(dummyseq);
1319 * replace parsed sequence with the realised forward reference
1321 includedseqs.set(p, dummyseq);
1326 * finally add sequences to the dataset
1328 for (SequenceI seq : includedseqs)
1330 // experimental: mapping-based 'alignment' to query sequence
1331 AlignmentUtils.alignSequenceAs(seq, align,
1332 String.valueOf(align.getGapCharacter()), false, true);
1334 // rename sequences if GFF handler requested this
1335 // TODO a more elegant way e.g. gffHelper.postProcess(newseqs) ?
1336 SequenceFeature[] sfs = seq.getSequenceFeatures();
1339 String newName = (String) sfs[0].getValue(GffHelperI.RENAME_TOKEN);
1340 if (newName != null)
1342 seq.setName(newName);
1345 align.addSequence(seq);
1350 * Process a ## directive
1356 * @throws IOException
1358 protected void processGffPragma(String line,
1359 Map<String, String> gffProps, AlignmentI align,
1360 List<SequenceI> newseqs) throws IOException
1363 if ("###".equals(line))
1365 // close off any open 'forward references'
1369 String[] tokens = line.substring(2).split(" ");
1370 String pragma = tokens[0];
1371 String value = tokens.length == 1 ? null : tokens[1];
1373 if ("gff-version".equalsIgnoreCase(pragma))
1379 // value may be e.g. "3.1.2"
1380 gffVersion = Integer.parseInt(value.split("\\.")[0]);
1381 } catch (NumberFormatException e)
1387 else if ("sequence-region".equalsIgnoreCase(pragma))
1389 // could capture <seqid start end> if wanted here
1391 else if ("feature-ontology".equalsIgnoreCase(pragma))
1393 // should resolve against the specified feature ontology URI
1395 else if ("attribute-ontology".equalsIgnoreCase(pragma))
1397 // URI of attribute ontology - not currently used in GFF3
1399 else if ("source-ontology".equalsIgnoreCase(pragma))
1401 // URI of source ontology - not currently used in GFF3
1403 else if ("species-build".equalsIgnoreCase(pragma))
1405 // save URI of specific NCBI taxon version of annotations
1406 gffProps.put("species-build", value);
1408 else if ("fasta".equalsIgnoreCase(pragma))
1410 // process the rest of the file as a fasta file and replace any dummy
1412 processAsFasta(align, newseqs);
1416 System.err.println("Ignoring unknown pragma: " + line);