2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import jalview.analysis.SequenceIdMatcher;
25 import jalview.datamodel.*;
26 import jalview.schemes.*;
27 import jalview.util.Format;
30 * Parse and create Jalview Features files Detects GFF format features files and
31 * parses. Does not implement standard print() - call specific printFeatures or
32 * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
33 * for the features annotation - this normally works on an exact match.
38 public class FeaturesFile extends AlignFile
41 * work around for GFF interpretation bug where source string becomes
42 * description rather than a group
44 private boolean doGffSource = true;
47 * Creates a new FeaturesFile object.
54 * Creates a new FeaturesFile object.
64 public FeaturesFile(String inFile, String type) throws IOException
69 public FeaturesFile(FileParse source) throws IOException
75 * Parse GFF or sequence features file using case-independent matching,
79 * - alignment/dataset containing sequences that are to be annotated
81 * - hashtable to store feature colour definitions
83 * - process html strings into plain text
84 * @return true if features were added
86 public boolean parse(AlignmentI align, Hashtable colours,
89 return parse(align, colours, null, removeHTML, false);
93 * Parse GFF or sequence features file optionally using case-independent
94 * matching, discarding URLs
97 * - alignment/dataset containing sequences that are to be annotated
99 * - hashtable to store feature colour definitions
101 * - process html strings into plain text
102 * @param relaxedIdmatching
103 * - when true, ID matches to compound sequence IDs are allowed
104 * @return true if features were added
106 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
107 boolean relaxedIdMatching)
109 return parse(align, colours, null, removeHTML, relaxedIdMatching);
113 * Parse GFF or sequence features file optionally using case-independent
117 * - alignment/dataset containing sequences that are to be annotated
119 * - hashtable to store feature colour definitions
121 * - hashtable to store associated URLs
123 * - process html strings into plain text
124 * @return true if features were added
126 public boolean parse(AlignmentI align, Map colours, Map featureLink,
129 return parse(align, colours, featureLink, removeHTML, false);
133 * Parse GFF or sequence features file
136 * - alignment/dataset containing sequences that are to be annotated
138 * - hashtable to store feature colour definitions
140 * - hashtable to store associated URLs
142 * - process html strings into plain text
143 * @param relaxedIdmatching
144 * - when true, ID matches to compound sequence IDs are allowed
145 * @return true if features were added
147 public boolean parse(AlignmentI align, Map colours, Map featureLink,
148 boolean removeHTML, boolean relaxedIdmatching)
154 SequenceI seq = null;
155 String type, desc, token = null;
157 int index, start, end;
161 String featureGroup = null, groupLink = null;
162 Map typeLink = new Hashtable();
164 * when true, assume GFF style features rather than Jalview style.
166 boolean GFFFile = true;
167 while ((line = nextLine()) != null)
169 if (line.startsWith("#"))
174 st = new StringTokenizer(line, "\t");
175 if (st.countTokens() == 1)
177 if (line.trim().equalsIgnoreCase("GFF"))
179 // Start parsing file as if it might be GFF again.
184 if (st.countTokens() > 1 && st.countTokens() < 4)
187 type = st.nextToken();
188 if (type.equalsIgnoreCase("startgroup"))
190 featureGroup = st.nextToken();
191 if (st.hasMoreElements())
193 groupLink = st.nextToken();
194 featureLink.put(featureGroup, groupLink);
197 else if (type.equalsIgnoreCase("endgroup"))
199 // We should check whether this is the current group,
200 // but at present theres no way of showing more than 1 group
207 Object colour = null;
208 String colscheme = st.nextToken();
209 if (colscheme.indexOf("|") > -1
210 || colscheme.trim().equalsIgnoreCase("label"))
212 // Parse '|' separated graduated colourscheme fields:
213 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
214 // can either provide 'label' only, first is optional, next two
215 // colors are required (but may be
216 // left blank), next is optional, nxt two min/max are required.
217 // first is either 'label'
218 // first/second and third are both hexadecimal or word equivalent
220 // next two are values parsed as floats.
221 // fifth is either 'above','below', or 'none'.
222 // sixth is a float value and only required when fifth is either
223 // 'above' or 'below'.
224 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
227 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
228 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
229 boolean labelCol = false;
231 String mincol = gcol.nextToken();
235 .println("Expected either 'label' or a colour specification in the line: "
239 String maxcol = null;
240 if (mincol.toLowerCase().indexOf("label") == 0)
243 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
245 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
247 String abso = null, minval, maxval;
250 // at least four more tokens
251 if (mincol.equals("|"))
257 gcol.nextToken(); // skip next '|'
259 // continue parsing rest of line
260 maxcol = gcol.nextToken();
261 if (maxcol.equals("|"))
267 gcol.nextToken(); // skip next '|'
269 abso = gcol.nextToken();
270 gcol.nextToken(); // skip next '|'
271 if (abso.toLowerCase().indexOf("abso") != 0)
278 minval = gcol.nextToken();
279 gcol.nextToken(); // skip next '|'
281 maxval = gcol.nextToken();
282 if (gcol.hasMoreTokens())
284 gcol.nextToken(); // skip next '|'
288 if (minval.length() > 0)
290 min = new Float(minval).floatValue();
292 } catch (Exception e)
295 .println("Couldn't parse the minimum value for graduated colour for type ("
297 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
302 if (maxval.length() > 0)
304 max = new Float(maxval).floatValue();
306 } catch (Exception e)
309 .println("Couldn't parse the maximum value for graduated colour for type ("
316 // add in some dummy min/max colours for the label-only
323 colour = new jalview.schemes.GraduatedColor(
324 new UserColourScheme(mincol).findColour('A'),
325 new UserColourScheme(maxcol).findColour('A'), min,
327 } catch (Exception e)
330 .println("Couldn't parse the graduated colour scheme ("
336 ((jalview.schemes.GraduatedColor) colour)
337 .setColourByLabel(labelCol);
338 ((jalview.schemes.GraduatedColor) colour)
339 .setAutoScaled(abso == null);
340 // add in any additional parameters
341 String ttype = null, tval = null;
342 if (gcol.hasMoreTokens())
344 // threshold type and possibly a threshold value
345 ttype = gcol.nextToken();
346 if (ttype.toLowerCase().startsWith("below"))
348 ((jalview.schemes.GraduatedColor) colour)
349 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
351 else if (ttype.toLowerCase().startsWith("above"))
353 ((jalview.schemes.GraduatedColor) colour)
354 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
358 ((jalview.schemes.GraduatedColor) colour)
359 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
360 if (!ttype.toLowerCase().startsWith("no"))
363 .println("Ignoring unrecognised threshold type : "
368 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
373 tval = gcol.nextToken();
374 ((jalview.schemes.GraduatedColor) colour)
375 .setThresh(new Float(tval).floatValue());
376 } catch (Exception e)
379 .println("Couldn't parse threshold value as a float: ("
384 // parse the thresh-is-min token ?
385 if (gcol.hasMoreTokens())
388 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
389 while (gcol.hasMoreTokens())
391 System.err.println("|" + gcol.nextToken());
393 System.err.println("\n");
399 UserColourScheme ucs = new UserColourScheme(colscheme);
400 colour = ucs.findColour('A');
404 colours.put(type, colour);
406 if (st.hasMoreElements())
408 String link = st.nextToken();
409 typeLink.put(type, link);
410 if (featureLink == null)
412 featureLink = new Hashtable();
414 featureLink.put(type, link);
420 while (st.hasMoreElements())
425 // Still possible this is an old Jalview file,
426 // which does not have type colours at the beginning
427 seqId = token = st.nextToken();
428 seq = findName(align, seqId, relaxedIdmatching);
431 desc = st.nextToken();
433 if (doGffSource && desc.indexOf(' ') == -1)
435 // could also be a source term rather than description line
436 group = new String(desc);
438 type = st.nextToken();
441 String stt = st.nextToken();
442 if (stt.length() == 0 || stt.equals("-"))
448 start = Integer.parseInt(stt);
450 } catch (NumberFormatException ex)
456 String stt = st.nextToken();
457 if (stt.length() == 0 || stt.equals("-"))
463 end = Integer.parseInt(stt);
465 } catch (NumberFormatException ex)
469 // TODO: decide if non positional feature assertion for input data
470 // where end==0 is generally valid
473 // treat as non-positional feature, regardless.
478 score = new Float(st.nextToken()).floatValue();
479 } catch (NumberFormatException ex)
484 sf = new SequenceFeature(type, desc, start, end, score, group);
488 sf.setValue("STRAND", st.nextToken());
489 sf.setValue("FRAME", st.nextToken());
490 } catch (Exception ex)
494 if (st.hasMoreTokens())
496 StringBuffer attributes = new StringBuffer();
497 while (st.hasMoreTokens())
499 attributes.append("\t" + st.nextElement());
501 // TODO validate and split GFF2 attributes field ? parse out
502 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
503 // sf.setValue(attrib, val);
504 sf.setValue("ATTRIBUTES", attributes.toString());
507 seq.addSequenceFeature(sf);
508 while ((seq = align.findName(seq, seqId, true)) != null)
510 seq.addSequenceFeature(new SequenceFeature(sf));
516 if (GFFFile && seq == null)
522 desc = st.nextToken();
524 if (!st.hasMoreTokens())
527 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
528 // in all probability, this isn't a file we understand, so bail
533 token = st.nextToken();
535 if (!token.equals("ID_NOT_SPECIFIED"))
537 seq = findName(align, seqId = token, relaxedIdmatching);
545 index = Integer.parseInt(st.nextToken());
546 seq = align.getSequenceAt(index);
547 } catch (NumberFormatException ex)
555 System.out.println("Sequence not found: " + line);
559 start = Integer.parseInt(st.nextToken());
560 end = Integer.parseInt(st.nextToken());
562 type = st.nextToken();
564 if (!colours.containsKey(type))
566 // Probably the old style groups file
567 UserColourScheme ucs = new UserColourScheme(type);
568 colours.put(type, ucs.findColour('A'));
570 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
571 if (st.hasMoreTokens())
575 score = new Float(st.nextToken()).floatValue();
576 // update colourgradient bounds if allowed to
577 } catch (NumberFormatException ex)
583 if (groupLink != null && removeHTML)
585 sf.addLink(groupLink);
586 sf.description += "%LINK%";
588 if (typeLink.containsKey(type) && removeHTML)
590 sf.addLink(typeLink.get(type).toString());
591 sf.description += "%LINK%";
594 parseDescriptionHTML(sf, removeHTML);
596 seq.addSequenceFeature(sf);
599 && (seq = align.findName(seq, seqId, false)) != null)
601 seq.addSequenceFeature(new SequenceFeature(sf));
603 // If we got here, its not a GFFFile
608 } catch (Exception ex)
610 System.out.println("Error parsing feature file: " + ex + "\n" + line);
611 ex.printStackTrace(System.err);
619 private AlignmentI lastmatchedAl = null;
621 private SequenceIdMatcher matcher = null;
624 * clear any temporary handles used to speed up ID matching
626 private void resetMatcher()
628 lastmatchedAl = null;
632 private SequenceI findName(AlignmentI align, String seqId,
633 boolean relaxedIdMatching)
635 SequenceI match = null;
636 if (relaxedIdMatching)
638 if (lastmatchedAl != align)
640 matcher = new SequenceIdMatcher(
641 (lastmatchedAl = align).getSequencesArray());
643 match = matcher.findIdMatch(seqId);
647 match = align.findName(seqId, true);
652 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
654 if (sf.getDescription() == null)
658 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
659 sf.getDescription(), removeHTML, newline);
661 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
663 for (String link : parsed.getLinks())
671 * generate a features file for seqs includes non-pos features by default.
674 * source of sequence features
676 * hash of feature types and colours
677 * @return features file contents
679 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
681 return printJalviewFormat(seqs, visible, true, true);
685 * generate a features file for seqs with colours from visible (if any)
690 * hash of Colours for each feature type
692 * when true only feature types in 'visible' will be output
694 * indicates if non-positional features should be output (regardless
696 * @return features file contents
698 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
699 boolean visOnly, boolean nonpos)
701 StringBuffer out = new StringBuffer();
702 SequenceFeature[] next;
703 boolean featuresGen = false;
704 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
706 // no point continuing.
707 return "No Features Visible";
710 if (visible != null && visOnly)
712 // write feature colours only if we're given them and we are generating
714 // TODO: decide if feature links should also be written here ?
715 Enumeration en = visible.keys();
717 while (en.hasMoreElements())
719 type = en.nextElement().toString();
721 if (visible.get(type) instanceof GraduatedColor)
723 GraduatedColor gc = (GraduatedColor) visible.get(type);
724 color = (gc.isColourByLabel() ? "label|" : "")
725 + Format.getHexString(gc.getMinColor()) + "|"
726 + Format.getHexString(gc.getMaxColor())
727 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
729 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
731 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
737 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
739 System.err.println("WARNING: Unsupported threshold type ("
740 + gc.getThreshType() + ") : Assuming 'above'");
745 color += "|" + gc.getThresh();
752 else if (visible.get(type) instanceof java.awt.Color)
754 color = Format.getHexString((java.awt.Color) visible.get(type));
758 // legacy support for integer objects containing colour triplet values
759 color = Format.getHexString(new java.awt.Color(Integer
760 .parseInt(visible.get(type).toString())));
768 // Work out which groups are both present and visible
769 Vector groups = new Vector();
771 boolean isnonpos = false;
773 for (int i = 0; i < seqs.length; i++)
775 next = seqs[i].getSequenceFeatures();
778 for (int j = 0; j < next.length; j++)
780 isnonpos = next[j].begin == 0 && next[j].end == 0;
781 if ((!nonpos && isnonpos)
782 || (!isnonpos && visOnly && !visible
783 .containsKey(next[j].type)))
788 if (next[j].featureGroup != null
789 && !groups.contains(next[j].featureGroup))
791 groups.addElement(next[j].featureGroup);
801 if (groups.size() > 0 && groupIndex < groups.size())
803 group = groups.elementAt(groupIndex).toString();
805 out.append("STARTGROUP\t");
814 for (int i = 0; i < seqs.length; i++)
816 next = seqs[i].getSequenceFeatures();
819 for (int j = 0; j < next.length; j++)
821 isnonpos = next[j].begin == 0 && next[j].end == 0;
822 if ((!nonpos && isnonpos)
823 || (!isnonpos && visOnly && !visible
824 .containsKey(next[j].type)))
826 // skip if feature is nonpos and we ignore them or if we only
827 // output visible and it isn't non-pos and it's not visible
832 && (next[j].featureGroup == null || !next[j].featureGroup
838 if (group == null && next[j].featureGroup != null)
842 // we have features to output
844 if (next[j].description == null
845 || next[j].description.equals(""))
847 out.append(next[j].type + "\t");
851 if (next[j].links != null
852 && next[j].getDescription().indexOf("<html>") == -1)
854 out.append("<html>");
857 out.append(next[j].description + " ");
858 if (next[j].links != null)
860 for (int l = 0; l < next[j].links.size(); l++)
862 String label = next[j].links.elementAt(l).toString();
863 String href = label.substring(label.indexOf("|") + 1);
864 label = label.substring(0, label.indexOf("|"));
866 if (next[j].description.indexOf(href) == -1)
868 out.append("<a href=\"" + href + "\">" + label + "</a>");
872 if (next[j].getDescription().indexOf("</html>") == -1)
874 out.append("</html>");
880 out.append(seqs[i].getName());
881 out.append("\t-1\t");
882 out.append(next[j].begin);
884 out.append(next[j].end);
886 out.append(next[j].type);
887 if (next[j].score != Float.NaN)
890 out.append(next[j].score);
899 out.append("ENDGROUP\t");
909 } while (groupIndex < groups.size() + 1);
913 return "No Features Visible";
916 return out.toString();
920 * generate a gff file for sequence features includes non-pos features by
927 public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
929 return printGFFFormat(seqs, visible, true, true);
932 public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
933 boolean visOnly, boolean nonpos)
935 StringBuffer out = new StringBuffer();
936 SequenceFeature[] next;
939 for (int i = 0; i < seqs.length; i++)
941 if (seqs[i].getSequenceFeatures() != null)
943 next = seqs[i].getSequenceFeatures();
944 for (int j = 0; j < next.length; j++)
946 isnonpos = next[j].begin == 0 && next[j].end == 0;
947 if ((!nonpos && isnonpos)
948 || (!isnonpos && visOnly && !visible
949 .containsKey(next[j].type)))
954 source = next[j].featureGroup;
957 source = next[j].getDescription();
960 out.append(seqs[i].getName());
964 out.append(next[j].type);
966 out.append(next[j].begin);
968 out.append(next[j].end);
970 out.append(next[j].score);
973 if (next[j].getValue("STRAND") != null)
975 out.append(next[j].getValue("STRAND"));
983 if (next[j].getValue("FRAME") != null)
985 out.append(next[j].getValue("FRAME"));
991 // TODO: verify/check GFF - should there be a /t here before attribute
994 if (next[j].getValue("ATTRIBUTES") != null)
996 out.append(next[j].getValue("ATTRIBUTES"));
1005 return out.toString();
1009 * this is only for the benefit of object polymorphism - method does nothing.
1017 * this is only for the benefit of object polymorphism - method does nothing.
1019 * @return error message
1021 public String print()
1023 return "USE printGFFFormat() or printJalviewFormat()";