2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
\r
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
\r
5 * This program is free software; you can redistribute it and/or
\r
6 * modify it under the terms of the GNU General Public License
\r
7 * as published by the Free Software Foundation; either version 2
\r
8 * of the License, or (at your option) any later version.
\r
10 * This program is distributed in the hope that it will be useful,
\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
13 * GNU General Public License for more details.
\r
15 * You should have received a copy of the GNU General Public License
\r
16 * along with this program; if not, write to the Free Software
\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
\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 * The Application can render HTML, but the applet will remove HTML tags and
\r
75 * replace links with %LINK% Both need to read links in HTML however
\r
77 * @throws IOException
\r
80 public boolean parse(AlignmentI align, Hashtable colours,
\r
83 return parse(align, colours, null, removeHTML);
\r
87 * The Application can render HTML, but the applet will remove HTML tags and
\r
88 * replace links with %LINK% Both need to read links in HTML however
\r
90 * @throws IOException
\r
93 public boolean parse(AlignmentI align, Hashtable colours,
\r
94 Hashtable featureLink, boolean removeHTML)
\r
99 SequenceI seq = null;
\r
100 String type, desc, token = null;
\r
102 int index, start, end;
\r
104 StringTokenizer st;
\r
105 SequenceFeature sf;
\r
106 String featureGroup = null, groupLink = null;
\r
107 Hashtable typeLink = new Hashtable();
\r
109 boolean GFFFile = true;
\r
111 while ((line = nextLine()) != null)
\r
113 if (line.startsWith("#"))
\r
118 st = new StringTokenizer(line, "\t");
\r
119 if (st.countTokens() > 1 && st.countTokens() < 4)
\r
122 type = st.nextToken();
\r
123 if (type.equalsIgnoreCase("startgroup"))
\r
125 featureGroup = st.nextToken();
\r
126 if (st.hasMoreElements())
\r
128 groupLink = st.nextToken();
\r
129 featureLink.put(featureGroup, groupLink);
\r
132 else if (type.equalsIgnoreCase("endgroup"))
\r
134 // We should check whether this is the current group,
\r
135 // but at present theres no way of showing more than 1 group
\r
137 featureGroup = null;
\r
142 Object colour = null;
\r
143 String colscheme = st.nextToken();
\r
144 if (colscheme.indexOf("|") > -1)
\r
146 // Parse '|' separated graduated colourscheme fields:
\r
147 // mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue
\r
148 // first four are required.
\r
149 // first two are hexadecimal or word equivalent colours.
\r
150 // second two are values parsed as floats.
\r
151 // fifth is either 'above','below', or 'none'.
\r
152 // sixth is a float value and only required when fifth is either
\r
153 // 'above' or 'below'.
\r
154 StringTokenizer gcol = new StringTokenizer(colscheme, "|");
\r
155 String mincol = gcol.nextToken(), maxcol = gcol.nextToken();
\r
157 .nextToken(), minval, maxval;
\r
158 if (abso.toLowerCase().indexOf("abso")!=0) {
\r
162 minval = gcol.nextToken();
\r
164 maxval = gcol.nextToken();
\r
166 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
\r
167 float min=Float.MIN_VALUE,max=Float.MAX_VALUE,threshval=Float.NaN;
\r
170 if (minval.length()>0) {
\r
171 min = new Float(minval).floatValue();
\r
173 } catch (Exception e)
\r
176 .println("Couldn't parse the minimum value for graduated colour for type ("
\r
177 + colscheme + ") - did you misspell 'auto' for the optional automatic colour switch ?");
\r
178 e.printStackTrace();
\r
182 if (maxval.length()>0) {
\r
183 max = new Float(maxval).floatValue();
\r
185 } catch (Exception e)
\r
188 .println("Couldn't parse the maximum value for graduated colour for type ("
\r
189 + colscheme + ")");
\r
190 e.printStackTrace();
\r
194 colour = new jalview.schemes.GraduatedColor(
\r
195 new UserColourScheme(mincol).findColour('A'),
\r
196 new UserColourScheme(maxcol).findColour('A'),
\r
198 } catch (Exception e)
\r
201 .println("Couldn't parse the graduated colour scheme ("
\r
202 + colscheme + ")");
\r
203 e.printStackTrace();
\r
205 if (colour != null)
\r
207 ((jalview.schemes.GraduatedColor)colour).setAutoScaled(abso==null);
\r
208 // add in any additional parameters
\r
209 String ttype = null, tval = null;
\r
210 if (gcol.hasMoreTokens())
\r
212 // threshold type and possibly a threshold value
\r
213 ttype = gcol.nextToken();
\r
214 if (ttype.toLowerCase().startsWith("below"))
\r
216 ((jalview.schemes.GraduatedColor) colour)
\r
217 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
\r
219 else if (ttype.toLowerCase().startsWith("above"))
\r
221 ((jalview.schemes.GraduatedColor) colour)
\r
222 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
\r
226 ((jalview.schemes.GraduatedColor) colour)
\r
227 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
\r
228 if (!ttype.toLowerCase().startsWith("no"))
\r
231 .println("Ignoring unrecognised threshold type : "
\r
236 if (((GraduatedColor)colour).getThreshType()!=AnnotationColourGradient.NO_THRESHOLD)
\r
238 tval = gcol.nextToken();
\r
241 ((jalview.schemes.GraduatedColor) colour)
\r
242 .setThresh(new Float(tval).floatValue());
\r
243 } catch (Exception e)
\r
246 .println("Couldn't parse threshold value as a float: ("
\r
248 e.printStackTrace();
\r
251 // parse the thresh-is-min token ?
\r
252 if (gcol.hasMoreTokens())
\r
255 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
\r
256 while (gcol.hasMoreTokens())
\r
258 System.err.println("|" + gcol);
\r
260 System.err.println("\n");
\r
266 UserColourScheme ucs = new UserColourScheme(colscheme);
\r
267 colour = ucs.findColour('A');
\r
269 if (colour != null)
\r
271 colours.put(type, colour);
\r
273 if (st.hasMoreElements())
\r
275 String link = st.nextToken();
\r
276 typeLink.put(type, link);
\r
277 if (featureLink == null)
\r
279 featureLink = new Hashtable();
\r
281 featureLink.put(type, link);
\r
287 while (st.hasMoreElements())
\r
292 // Still possible this is an old Jalview file,
\r
293 // which does not have type colours at the beginning
\r
294 seqId = token = st.nextToken();
\r
295 seq = align.findName(seqId, true);
\r
298 desc = st.nextToken();
\r
299 String group = null;
\r
300 if (doGffSource && desc.indexOf(' ') == -1)
\r
302 // could also be a source term rather than description line
\r
303 group = new String(desc);
\r
305 type = st.nextToken();
\r
308 String stt = st.nextToken();
\r
309 if (stt.length() == 0 || stt.equals("-"))
\r
315 start = Integer.parseInt(stt);
\r
317 } catch (NumberFormatException ex)
\r
323 String stt = st.nextToken();
\r
324 if (stt.length() == 0 || stt.equals("-"))
\r
330 end = Integer.parseInt(stt);
\r
332 } catch (NumberFormatException ex)
\r
336 // TODO: decide if non positional feature assertion for input data
\r
337 // where end==0 is generally valid
\r
340 // treat as non-positional feature, regardless.
\r
345 score = new Float(st.nextToken()).floatValue();
\r
346 } catch (NumberFormatException ex)
\r
351 sf = new SequenceFeature(type, desc, start, end, score, group);
\r
355 sf.setValue("STRAND", st.nextToken());
\r
356 sf.setValue("FRAME", st.nextToken());
\r
357 } catch (Exception ex)
\r
361 if (st.hasMoreTokens())
\r
363 StringBuffer attributes = new StringBuffer();
\r
364 while (st.hasMoreTokens())
\r
366 attributes.append("\t" + st.nextElement());
\r
368 // TODO validate and split GFF2 attributes field ? parse out
\r
369 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
\r
370 // sf.setValue(attrib, val);
\r
371 sf.setValue("ATTRIBUTES", attributes.toString());
\r
374 seq.addSequenceFeature(sf);
\r
375 while ((seq = align.findName(seq, seqId, true)) != null)
\r
377 seq.addSequenceFeature(new SequenceFeature(sf));
\r
383 if (GFFFile && seq == null)
\r
389 desc = st.nextToken();
\r
391 if (!st.hasMoreTokens())
\r
394 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
\r
395 // in all probability, this isn't a file we understand, so bail
\r
400 token = st.nextToken();
\r
402 if (!token.equals("ID_NOT_SPECIFIED"))
\r
404 seq = align.findName(seqId = token, true);
\r
412 index = Integer.parseInt(st.nextToken());
\r
413 seq = align.getSequenceAt(index);
\r
414 } catch (NumberFormatException ex)
\r
422 System.out.println("Sequence not found: " + line);
\r
426 start = Integer.parseInt(st.nextToken());
\r
427 end = Integer.parseInt(st.nextToken());
\r
429 type = st.nextToken();
\r
431 if (!colours.containsKey(type))
\r
433 // Probably the old style groups file
\r
434 UserColourScheme ucs = new UserColourScheme(type);
\r
435 colours.put(type, ucs.findColour('A'));
\r
437 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
\r
438 if (st.hasMoreTokens())
\r
442 score = new Float(st.nextToken()).floatValue();
\r
443 // update colourgradient bounds if allowed to
\r
444 } catch (NumberFormatException ex)
\r
448 sf.setScore(score);
\r
450 if (groupLink != null && removeHTML)
\r
452 sf.addLink(groupLink);
\r
453 sf.description += "%LINK%";
\r
455 if (typeLink.containsKey(type) && removeHTML)
\r
457 sf.addLink(typeLink.get(type).toString());
\r
458 sf.description += "%LINK%";
\r
461 parseDescriptionHTML(sf, removeHTML);
\r
463 seq.addSequenceFeature(sf);
\r
465 while (seqId != null
\r
466 && (seq = align.findName(seq, seqId, false)) != null)
\r
468 seq.addSequenceFeature(new SequenceFeature(sf));
\r
470 // If we got here, its not a GFFFile
\r
474 } catch (Exception ex)
\r
476 System.out.println(line);
\r
477 System.out.println("Error parsing feature file: " + ex + "\n" + line);
\r
478 ex.printStackTrace(System.err);
\r
485 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
\r
487 if (sf.getDescription() == null)
\r
493 && sf.getDescription().toUpperCase().indexOf("<HTML>") == -1)
\r
495 removeHTML = false;
\r
498 StringBuffer sb = new StringBuffer();
\r
499 StringTokenizer st = new StringTokenizer(sf.getDescription(), "<");
\r
500 String token, link;
\r
503 while (st.hasMoreElements())
\r
505 token = st.nextToken("&>");
\r
506 if (token.equalsIgnoreCase("html") || token.startsWith("/"))
\r
512 startTag = token.indexOf("<");
\r
516 tag = token.substring(startTag + 1);
\r
517 token = token.substring(0, startTag);
\r
520 if (tag != null && tag.toUpperCase().startsWith("A HREF="))
\r
522 if (token.length() > 0)
\r
526 link = tag.substring(tag.indexOf("\"") + 1, tag.length() - 1);
\r
527 String label = st.nextToken("<>");
\r
528 sf.addLink(label + "|" + link);
\r
529 sb.append(label + "%LINK%");
\r
531 else if (tag != null && tag.equalsIgnoreCase("br"))
\r
535 else if (token.startsWith("lt;"))
\r
537 sb.append("<" + token.substring(3));
\r
539 else if (token.startsWith("gt;"))
\r
541 sb.append(">" + token.substring(3));
\r
543 else if (token.startsWith("amp;"))
\r
545 sb.append("&" + token.substring(4));
\r
555 sf.description = sb.toString();
\r
561 * generate a features file for seqs
\r
564 * source of sequence features
\r
566 * hash of feature types and colours
\r
567 * @return features file contents
\r
569 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
\r
571 return printJalviewFormat(seqs, visible, true);
\r
575 * generate a features file for seqs with colours from visible (if any)
\r
578 * source of features
\r
580 * hash of Colours for each feature type
\r
582 * when true only feature types in 'visible' will be output
\r
583 * @return features file contents
\r
585 public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
\r
588 StringBuffer out = new StringBuffer();
\r
589 SequenceFeature[] next;
\r
591 if (visOnly && (visible == null || visible.size() < 1))
\r
593 return "No Features Visible";
\r
595 if (visible != null && visOnly)
\r
597 // write feature colours only if we're given them and we are generating
\r
599 // TODO: decide if feature links should also be written here ?
\r
600 Enumeration en = visible.keys();
\r
601 String type, color;
\r
602 while (en.hasMoreElements())
\r
604 type = en.nextElement().toString();
\r
606 if (visible.get(type) instanceof GraduatedColor)
\r
608 GraduatedColor gc = (GraduatedColor) visible.get(type);
\r
609 color = Format.getHexString(gc.getMinColor()) + "|"
\r
610 + Format.getHexString(gc.getMaxColor()) +
\r
611 (gc.isAutoScale() ? "|" : "|abso|")+ gc.getMin() + "|" + gc.getMax() + "|";
\r
612 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
\r
614 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
\r
620 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
\r
622 System.err.println("WARNING: Unsupported threshold type ("
\r
623 + gc.getThreshType() + ") : Assuming 'above'");
\r
628 color += "|" + gc.getThresh();
\r
636 if (visible.get(type) instanceof java.awt.Color) {
\r
637 color = Format.getHexString((java.awt.Color)visible.get(type));
\r
639 // legacy support for integer objects containing colour triplet values
\r
640 color = Format.getHexString(new java.awt.Color(Integer
\r
641 .parseInt(visible.get(type).toString())));
\r
643 out.append(type + "\t" + color + "\n");
\r
646 // Work out which groups are both present and visible
\r
647 Vector groups = new Vector();
\r
648 int groupIndex = 0;
\r
650 for (int i = 0; i < seqs.length; i++)
\r
652 next = seqs[i].getSequenceFeatures();
\r
655 for (int j = 0; j < next.length; j++)
\r
657 if (visOnly && !visible.containsKey(next[j].type))
\r
662 if (next[j].featureGroup != null
\r
663 && !groups.contains(next[j].featureGroup))
\r
665 groups.addElement(next[j].featureGroup);
\r
671 String group = null;
\r
676 if (groups.size() > 0 && groupIndex < groups.size())
\r
678 group = groups.elementAt(groupIndex).toString();
\r
679 out.append("\nSTARTGROUP\t" + group + "\n");
\r
686 for (int i = 0; i < seqs.length; i++)
\r
688 next = seqs[i].getSequenceFeatures();
\r
691 for (int j = 0; j < next.length; j++)
\r
693 if (visOnly && !visible.containsKey(next[j].type))
\r
699 && (next[j].featureGroup == null || !next[j].featureGroup
\r
705 if (group == null && next[j].featureGroup != null)
\r
710 if (next[j].description == null
\r
711 || next[j].description.equals(""))
\r
713 out.append(next[j].type + "\t");
\r
717 if (next[j].links != null
\r
718 && next[j].getDescription().indexOf("<html>") == -1)
\r
720 out.append("<html>");
\r
723 out.append(next[j].description + " ");
\r
724 if (next[j].links != null)
\r
726 for (int l = 0; l < next[j].links.size(); l++)
\r
728 String label = next[j].links.elementAt(l).toString();
\r
729 String href = label.substring(label.indexOf("|") + 1);
\r
730 label = label.substring(0, label.indexOf("|"));
\r
732 if (next[j].description.indexOf(href) == -1)
\r
735 .append("<a href=\"" + href + "\">" + label
\r
740 if (next[j].getDescription().indexOf("</html>") == -1)
\r
742 out.append("</html>");
\r
749 out.append(seqs[i].getName() + "\t-1\t" + next[j].begin + "\t"
\r
750 + next[j].end + "\t" + next[j].type + ((visible.get(next[j].type) instanceof GraduatedColor) ? "\t"+next[j].score+"\n" : "\n"));
\r
757 out.append("ENDGROUP\t" + group + "\n");
\r
765 } while (groupIndex < groups.size() + 1);
\r
767 return out.toString();
\r
770 public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
\r
772 return printGFFFormat(seqs, visible, true);
\r
775 public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
\r
778 StringBuffer out = new StringBuffer();
\r
779 SequenceFeature[] next;
\r
782 for (int i = 0; i < seqs.length; i++)
\r
784 if (seqs[i].getSequenceFeatures() != null)
\r
786 next = seqs[i].getSequenceFeatures();
\r
787 for (int j = 0; j < next.length; j++)
\r
789 if (visOnly && visible != null
\r
790 && !visible.containsKey(next[j].type))
\r
795 source = next[j].featureGroup;
\r
796 if (source == null)
\r
798 source = next[j].getDescription();
\r
801 out.append(seqs[i].getName() + "\t" + source + "\t"
\r
802 + next[j].type + "\t" + next[j].begin + "\t"
\r
803 + next[j].end + "\t" + next[j].score + "\t");
\r
805 if (next[j].getValue("STRAND") != null)
\r
807 out.append(next[j].getValue("STRAND") + "\t");
\r
814 if (next[j].getValue("FRAME") != null)
\r
816 out.append(next[j].getValue("FRAME"));
\r
823 if (next[j].getValue("ATTRIBUTES") != null)
\r
825 out.append(next[j].getValue("ATTRIBUTES"));
\r
834 return out.toString();
\r
838 * this is only for the benefit of object polymorphism - method does nothing.
\r
840 public void parse()
\r
846 * this is only for the benefit of object polymorphism - method does nothing.
\r
848 * @return error message
\r
850 public String print()
\r
852 return "USE printGFFFormat() or printJalviewFormat()";
\r