2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
\r
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
\r
5 * This file is part of Jalview.
\r
7 * Jalview is free software: you can redistribute it and/or
\r
8 * modify it under the terms of the GNU General Public License
\r
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
\r
11 * Jalview is distributed in the hope that it will be useful, but
\r
12 * WITHOUT ANY WARRANTY; without even the implied warranty
\r
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
\r
14 * PURPOSE. See the GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
\r
23 import jalview.analysis.SequenceIdMatcher;
\r
24 import jalview.datamodel.*;
\r
25 import jalview.schemes.*;
\r
26 import jalview.util.Format;
\r
29 * Parse and create Jalview Features files Detects GFF format features files and
\r
30 * parses. Does not implement standard print() - call specific printFeatures or
\r
31 * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
\r
32 * for the features annotation - this normally works on an exact match.
\r
35 * @version $Revision$
\r
37 public class FeaturesFile extends AlignFile
\r
40 * work around for GFF interpretation bug where source string becomes
\r
41 * description rather than a group
\r
43 private boolean doGffSource = true;
\r
46 * Creates a new FeaturesFile object.
\r
48 public FeaturesFile()
\r
53 * Creates a new FeaturesFile object.
\r
60 * @throws IOException
\r
63 public FeaturesFile(String inFile, String type) throws IOException
\r
65 super(inFile, type);
\r
68 public FeaturesFile(FileParse source) throws IOException
\r
74 * Parse GFF or sequence features file using case-independent matching,
\r
78 * - alignment/dataset containing sequences that are to be annotated
\r
80 * - hashtable to store feature colour definitions
\r
82 * - process html strings into plain text
\r
83 * @return true if features were added
\r
85 public boolean parse(AlignmentI align, Hashtable colours,
\r
88 return parse(align, colours, null, removeHTML, false);
\r
92 * Parse GFF or sequence features file optionally using case-independent
\r
93 * matching, discarding URLs
\r
96 * - alignment/dataset containing sequences that are to be annotated
\r
98 * - hashtable to store feature colour definitions
\r
100 * - process html strings into plain text
\r
101 * @param relaxedIdmatching
\r
102 * - when true, ID matches to compound sequence IDs are allowed
\r
103 * @return true if features were added
\r
105 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
\r
106 boolean relaxedIdMatching)
\r
108 return parse(align, colours, null, removeHTML, relaxedIdMatching);
\r
112 * Parse GFF or sequence features file optionally using case-independent
\r
116 * - alignment/dataset containing sequences that are to be annotated
\r
118 * - hashtable to store feature colour definitions
\r
119 * @param featureLink
\r
120 * - hashtable to store associated URLs
\r
121 * @param removeHTML
\r
122 * - process html strings into plain text
\r
123 * @return true if features were added
\r
125 public boolean parse(AlignmentI align, Map colours, Map featureLink,
\r
126 boolean removeHTML)
\r
128 return parse(align, colours, featureLink, removeHTML, false);
\r
132 * /** Parse GFF or sequence features file
\r
135 * - alignment/dataset containing sequences that are to be annotated
\r
137 * - hashtable to store feature colour definitions
\r
138 * @param featureLink
\r
139 * - hashtable to store associated URLs
\r
140 * @param removeHTML
\r
141 * - process html strings into plain text
\r
142 * @param relaxedIdmatching
\r
143 * - when true, ID matches to compound sequence IDs are allowed
\r
144 * @return true if features were added
\r
146 public boolean parse(AlignmentI align, Map colours, Map featureLink,
\r
147 boolean removeHTML, boolean relaxedIdmatching)
\r
150 String line = null;
\r
153 SequenceI seq = null;
\r
154 String type, desc, token = null;
\r
156 int index, start, end;
\r
158 StringTokenizer st;
\r
159 SequenceFeature sf;
\r
160 String featureGroup = null, groupLink = null;
\r
161 Map typeLink = new Hashtable();
\r
163 * when true, assume GFF style features rather than Jalview style.
\r
165 boolean GFFFile = true;
\r
166 while ((line = nextLine()) != null)
\r
168 if (line.startsWith("#"))
\r
173 st = new StringTokenizer(line, "\t");
\r
174 if (st.countTokens() == 1)
\r
176 if (line.trim().equalsIgnoreCase("GFF"))
\r
178 // Start parsing file as if it might be GFF again.
\r
183 if (st.countTokens() > 1 && st.countTokens() < 4)
\r
186 type = st.nextToken();
\r
187 if (type.equalsIgnoreCase("startgroup"))
\r
189 featureGroup = st.nextToken();
\r
190 if (st.hasMoreElements())
\r
192 groupLink = st.nextToken();
\r
193 featureLink.put(featureGroup, groupLink);
\r
196 else if (type.equalsIgnoreCase("endgroup"))
\r
198 // We should check whether this is the current group,
\r
199 // but at present theres no way of showing more than 1 group
\r
201 featureGroup = null;
\r
206 Object colour = null;
\r
207 String colscheme = st.nextToken();
\r
208 if (colscheme.indexOf("|") > -1
\r
209 || colscheme.trim().equalsIgnoreCase("label"))
\r
211 // Parse '|' separated graduated colourscheme fields:
\r
212 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
\r
213 // can either provide 'label' only, first is optional, next two
\r
214 // colors are required (but may be
\r
215 // left blank), next is optional, nxt two min/max are required.
\r
216 // first is either 'label'
\r
217 // first/second and third are both hexadecimal or word equivalent
\r
219 // next two are values parsed as floats.
\r
220 // fifth is either 'above','below', or 'none'.
\r
221 // sixth is a float value and only required when fifth is either
\r
222 // 'above' or 'below'.
\r
223 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
\r
226 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
\r
227 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
\r
228 boolean labelCol = false;
\r
230 String mincol = gcol.nextToken();
\r
234 .println("Expected either 'label' or a colour specification in the line: "
\r
238 String maxcol = null;
\r
239 if (mincol.toLowerCase().indexOf("label") == 0)
\r
242 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
\r
244 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
\r
246 String abso = null, minval, maxval;
\r
247 if (mincol != null)
\r
249 // at least four more tokens
\r
250 if (mincol.equals("|"))
\r
256 gcol.nextToken(); // skip next '|'
\r
258 // continue parsing rest of line
\r
259 maxcol = gcol.nextToken();
\r
260 if (maxcol.equals("|"))
\r
266 gcol.nextToken(); // skip next '|'
\r
268 abso = gcol.nextToken();
\r
269 gcol.nextToken(); // skip next '|'
\r
270 if (abso.toLowerCase().indexOf("abso") != 0)
\r
277 minval = gcol.nextToken();
\r
278 gcol.nextToken(); // skip next '|'
\r
280 maxval = gcol.nextToken();
\r
281 if (gcol.hasMoreTokens())
\r
283 gcol.nextToken(); // skip next '|'
\r
287 if (minval.length() > 0)
\r
289 min = new Float(minval).floatValue();
\r
291 } catch (Exception e)
\r
294 .println("Couldn't parse the minimum value for graduated colour for type ("
\r
296 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
\r
297 e.printStackTrace();
\r
301 if (maxval.length() > 0)
\r
303 max = new Float(maxval).floatValue();
\r
305 } catch (Exception e)
\r
308 .println("Couldn't parse the maximum value for graduated colour for type ("
\r
309 + colscheme + ")");
\r
310 e.printStackTrace();
\r
315 // add in some dummy min/max colours for the label-only
\r
322 colour = new jalview.schemes.GraduatedColor(
\r
323 new UserColourScheme(mincol).findColour('A'),
\r
324 new UserColourScheme(maxcol).findColour('A'), min,
\r
326 } catch (Exception e)
\r
329 .println("Couldn't parse the graduated colour scheme ("
\r
330 + colscheme + ")");
\r
331 e.printStackTrace();
\r
333 if (colour != null)
\r
335 ((jalview.schemes.GraduatedColor) colour)
\r
336 .setColourByLabel(labelCol);
\r
337 ((jalview.schemes.GraduatedColor) colour)
\r
338 .setAutoScaled(abso == null);
\r
339 // add in any additional parameters
\r
340 String ttype = null, tval = null;
\r
341 if (gcol.hasMoreTokens())
\r
343 // threshold type and possibly a threshold value
\r
344 ttype = gcol.nextToken();
\r
345 if (ttype.toLowerCase().startsWith("below"))
\r
347 ((jalview.schemes.GraduatedColor) colour)
\r
348 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
\r
350 else if (ttype.toLowerCase().startsWith("above"))
\r
352 ((jalview.schemes.GraduatedColor) colour)
\r
353 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
\r
357 ((jalview.schemes.GraduatedColor) colour)
\r
358 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
\r
359 if (!ttype.toLowerCase().startsWith("no"))
\r
362 .println("Ignoring unrecognised threshold type : "
\r
367 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
\r
372 tval = gcol.nextToken();
\r
373 ((jalview.schemes.GraduatedColor) colour)
\r
374 .setThresh(new Float(tval).floatValue());
\r
375 } catch (Exception e)
\r
378 .println("Couldn't parse threshold value as a float: ("
\r
380 e.printStackTrace();
\r
383 // parse the thresh-is-min token ?
\r
384 if (gcol.hasMoreTokens())
\r
387 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
\r
388 while (gcol.hasMoreTokens())
\r
390 System.err.println("|" + gcol.nextToken());
\r
392 System.err.println("\n");
\r
398 UserColourScheme ucs = new UserColourScheme(colscheme);
\r
399 colour = ucs.findColour('A');
\r
401 if (colour != null)
\r
403 colours.put(type, colour);
\r
405 if (st.hasMoreElements())
\r
407 String link = st.nextToken();
\r
408 typeLink.put(type, link);
\r
409 if (featureLink == null)
\r
411 featureLink = new Hashtable();
\r
413 featureLink.put(type, link);
\r
419 while (st.hasMoreElements())
\r
424 // Still possible this is an old Jalview file,
\r
425 // which does not have type colours at the beginning
\r
426 seqId = token = st.nextToken();
\r
427 seq = findName(align, seqId, relaxedIdmatching);
\r
430 desc = st.nextToken();
\r
431 String group = null;
\r
432 if (doGffSource && desc.indexOf(' ') == -1)
\r
434 // could also be a source term rather than description line
\r
435 group = new String(desc);
\r
437 type = st.nextToken();
\r
440 String stt = st.nextToken();
\r
441 if (stt.length() == 0 || stt.equals("-"))
\r
447 start = Integer.parseInt(stt);
\r
449 } catch (NumberFormatException ex)
\r
455 String stt = st.nextToken();
\r
456 if (stt.length() == 0 || stt.equals("-"))
\r
462 end = Integer.parseInt(stt);
\r
464 } catch (NumberFormatException ex)
\r
468 // TODO: decide if non positional feature assertion for input data
\r
469 // where end==0 is generally valid
\r
472 // treat as non-positional feature, regardless.
\r
477 score = new Float(st.nextToken()).floatValue();
\r
478 } catch (NumberFormatException ex)
\r
483 sf = new SequenceFeature(type, desc, start, end, score, group);
\r
487 sf.setValue("STRAND", st.nextToken());
\r
488 sf.setValue("FRAME", st.nextToken());
\r
489 } catch (Exception ex)
\r
493 if (st.hasMoreTokens())
\r
495 StringBuffer attributes = new StringBuffer();
\r
496 while (st.hasMoreTokens())
\r
498 attributes.append("\t" + st.nextElement());
\r
500 // TODO validate and split GFF2 attributes field ? parse out
\r
501 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
\r
502 // sf.setValue(attrib, val);
\r
503 sf.setValue("ATTRIBUTES", attributes.toString());
\r
506 seq.addSequenceFeature(sf);
\r
507 while ((seq = align.findName(seq, seqId, true)) != null)
\r
509 seq.addSequenceFeature(new SequenceFeature(sf));
\r
515 if (GFFFile && seq == null)
\r
521 desc = st.nextToken();
\r
523 if (!st.hasMoreTokens())
\r
526 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
\r
527 // in all probability, this isn't a file we understand, so bail
\r
532 token = st.nextToken();
\r
534 if (!token.equals("ID_NOT_SPECIFIED"))
\r
536 seq = findName(align, seqId = token, relaxedIdmatching);
\r
544 index = Integer.parseInt(st.nextToken());
\r
545 seq = align.getSequenceAt(index);
\r
546 } catch (NumberFormatException ex)
\r
554 System.out.println("Sequence not found: " + line);
\r
558 start = Integer.parseInt(st.nextToken());
\r
559 end = Integer.parseInt(st.nextToken());
\r
561 type = st.nextToken();
\r
563 if (!colours.containsKey(type))
\r
565 // Probably the old style groups file
\r
566 UserColourScheme ucs = new UserColourScheme(type);
\r
567 colours.put(type, ucs.findColour('A'));
\r
569 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
\r
570 if (st.hasMoreTokens())
\r
574 score = new Float(st.nextToken()).floatValue();
\r
575 // update colourgradient bounds if allowed to
\r
576 } catch (NumberFormatException ex)
\r
580 sf.setScore(score);
\r
582 if (groupLink != null && removeHTML)
\r
584 sf.addLink(groupLink);
\r
585 sf.description += "%LINK%";
\r
587 if (typeLink.containsKey(type) && removeHTML)
\r
589 sf.addLink(typeLink.get(type).toString());
\r
590 sf.description += "%LINK%";
\r
593 parseDescriptionHTML(sf, removeHTML);
\r
595 seq.addSequenceFeature(sf);
\r
597 while (seqId != null
\r
598 && (seq = align.findName(seq, seqId, false)) != null)
\r
600 seq.addSequenceFeature(new SequenceFeature(sf));
\r
602 // If we got here, its not a GFFFile
\r
607 } catch (Exception ex)
\r
609 System.out.println(line);
\r
610 System.out.println("Error parsing feature file: " + ex + "\n" + line);
\r
611 ex.printStackTrace(System.err);
\r
619 private AlignmentI lastmatchedAl = null;
\r
621 private SequenceIdMatcher matcher = null;
\r
624 * clear any temporary handles used to speed up ID matching
\r
626 private void resetMatcher()
\r
628 lastmatchedAl = null;
\r
632 private SequenceI findName(AlignmentI align, String seqId,
\r
633 boolean relaxedIdMatching)
\r
635 SequenceI match = null;
\r
636 if (relaxedIdMatching)
\r
638 if (lastmatchedAl != align)
\r
640 matcher = new SequenceIdMatcher(
\r
641 (lastmatchedAl = align).getSequencesArray());
\r
643 match = matcher.findIdMatch(seqId);
\r
647 match = align.findName(seqId, true);
\r
652 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
\r
654 if (sf.getDescription() == null)
\r
658 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
\r
659 sf.getDescription(), removeHTML, newline);
\r
661 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
\r
663 for (String link : parsed.getLinks())
\r
671 * generate a features file for seqs includes non-pos features by default.
\r
674 * source of sequence features
\r
676 * hash of feature types and colours
\r
677 * @return features file contents
\r
679 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
\r
681 return printJalviewFormat(seqs, visible, true, true);
\r
685 * generate a features file for seqs with colours from visible (if any)
\r
688 * source of features
\r
690 * hash of Colours for each feature type
\r
692 * when true only feature types in 'visible' will be output
\r
694 * indicates if non-positional features should be output (regardless
\r
695 * of group or type)
\r
696 * @return features file contents
\r
698 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
\r
699 boolean visOnly, boolean nonpos)
\r
701 StringBuffer out = new StringBuffer();
\r
702 SequenceFeature[] next;
\r
703 boolean featuresGen = false;
\r
704 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
\r
706 // no point continuing.
\r
707 return "No Features Visible";
\r
710 if (visible != null && visOnly)
\r
712 // write feature colours only if we're given them and we are generating
\r
714 // TODO: decide if feature links should also be written here ?
\r
715 Enumeration en = visible.keys();
\r
716 String type, color;
\r
717 while (en.hasMoreElements())
\r
719 type = en.nextElement().toString();
\r
721 if (visible.get(type) instanceof GraduatedColor)
\r
723 GraduatedColor gc = (GraduatedColor) visible.get(type);
\r
724 color = (gc.isColourByLabel() ? "label|" : "")
\r
725 + Format.getHexString(gc.getMinColor()) + "|"
\r
726 + Format.getHexString(gc.getMaxColor())
\r
727 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
\r
728 + gc.getMax() + "|";
\r
729 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
\r
731 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
\r
737 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
\r
739 System.err.println("WARNING: Unsupported threshold type ("
\r
740 + gc.getThreshType() + ") : Assuming 'above'");
\r
745 color += "|" + gc.getThresh();
\r
752 else if (visible.get(type) instanceof java.awt.Color)
\r
754 color = Format.getHexString((java.awt.Color) visible.get(type));
\r
758 // legacy support for integer objects containing colour triplet values
\r
759 color = Format.getHexString(new java.awt.Color(Integer
\r
760 .parseInt(visible.get(type).toString())));
\r
765 out.append(newline);
\r
768 // Work out which groups are both present and visible
\r
769 Vector groups = new Vector();
\r
770 int groupIndex = 0;
\r
771 boolean isnonpos = false;
\r
773 for (int i = 0; i < seqs.length; i++)
\r
775 next = seqs[i].getSequenceFeatures();
\r
778 for (int j = 0; j < next.length; j++)
\r
780 isnonpos = next[j].begin == 0 && next[j].end == 0;
\r
781 if ((!nonpos && isnonpos)
\r
782 || (!isnonpos && visOnly && !visible
\r
783 .containsKey(next[j].type)))
\r
788 if (next[j].featureGroup != null
\r
789 && !groups.contains(next[j].featureGroup))
\r
791 groups.addElement(next[j].featureGroup);
\r
797 String group = null;
\r
801 if (groups.size() > 0 && groupIndex < groups.size())
\r
803 group = groups.elementAt(groupIndex).toString();
\r
804 out.append(newline);
\r
805 out.append("STARTGROUP\t");
\r
807 out.append(newline);
\r
814 for (int i = 0; i < seqs.length; i++)
\r
816 next = seqs[i].getSequenceFeatures();
\r
819 for (int j = 0; j < next.length; j++)
\r
821 isnonpos = next[j].begin == 0 && next[j].end == 0;
\r
822 if ((!nonpos && isnonpos)
\r
823 || (!isnonpos && visOnly && !visible
\r
824 .containsKey(next[j].type)))
\r
826 // skip if feature is nonpos and we ignore them or if we only
\r
827 // output visible and it isn't non-pos and it's not visible
\r
832 && (next[j].featureGroup == null || !next[j].featureGroup
\r
838 if (group == null && next[j].featureGroup != null)
\r
842 // we have features to output
\r
843 featuresGen = true;
\r
844 if (next[j].description == null
\r
845 || next[j].description.equals(""))
\r
847 out.append(next[j].type + "\t");
\r
851 if (next[j].links != null
\r
852 && next[j].getDescription().indexOf("<html>") == -1)
\r
854 out.append("<html>");
\r
857 out.append(next[j].description + " ");
\r
858 if (next[j].links != null)
\r
860 for (int l = 0; l < next[j].links.size(); l++)
\r
862 String label = next[j].links.elementAt(l).toString();
\r
863 String href = label.substring(label.indexOf("|") + 1);
\r
864 label = label.substring(0, label.indexOf("|"));
\r
866 if (next[j].description.indexOf(href) == -1)
\r
868 out.append("<a href=\"" + href + "\">" + label + "</a>");
\r
872 if (next[j].getDescription().indexOf("</html>") == -1)
\r
874 out.append("</html>");
\r
880 out.append(seqs[i].getName());
\r
881 out.append("\t-1\t");
\r
882 out.append(next[j].begin);
\r
884 out.append(next[j].end);
\r
886 out.append(next[j].type);
\r
887 if (next[j].score != Float.NaN)
\r
890 out.append(next[j].score);
\r
892 out.append(newline);
\r
899 out.append("ENDGROUP\t");
\r
901 out.append(newline);
\r
909 } while (groupIndex < groups.size() + 1);
\r
913 return "No Features Visible";
\r
916 return out.toString();
\r
920 * generate a gff file for sequence features includes non-pos features by
\r
927 public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
\r
929 return printGFFFormat(seqs, visible, true, true);
\r
932 public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
\r
933 boolean visOnly, boolean nonpos)
\r
935 StringBuffer out = new StringBuffer();
\r
936 SequenceFeature[] next;
\r
939 for (int i = 0; i < seqs.length; i++)
\r
941 if (seqs[i].getSequenceFeatures() != null)
\r
943 next = seqs[i].getSequenceFeatures();
\r
944 for (int j = 0; j < next.length; j++)
\r
946 isnonpos = next[j].begin == 0 && next[j].end == 0;
\r
947 if ((!nonpos && isnonpos)
\r
948 || (!isnonpos && visOnly && !visible
\r
949 .containsKey(next[j].type)))
\r
954 source = next[j].featureGroup;
\r
955 if (source == null)
\r
957 source = next[j].getDescription();
\r
960 out.append(seqs[i].getName());
\r
962 out.append(source);
\r
964 out.append(next[j].type);
\r
966 out.append(next[j].begin);
\r
968 out.append(next[j].end);
\r
970 out.append(next[j].score);
\r
973 if (next[j].getValue("STRAND") != null)
\r
975 out.append(next[j].getValue("STRAND"));
\r
983 if (next[j].getValue("FRAME") != null)
\r
985 out.append(next[j].getValue("FRAME"));
\r
991 // TODO: verify/check GFF - should there be a /t here before attribute
\r
994 if (next[j].getValue("ATTRIBUTES") != null)
\r
996 out.append(next[j].getValue("ATTRIBUTES"));
\r
999 out.append(newline);
\r
1005 return out.toString();
\r
1009 * this is only for the benefit of object polymorphism - method does nothing.
\r
1011 public void parse()
\r
1017 * this is only for the benefit of object polymorphism - method does nothing.
\r
1019 * @return error message
\r
1021 public String print()
\r
1023 return "USE printGFFFormat() or printJalviewFormat()";
\r