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.SequenceIdMatcher;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceDummy;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.schemes.AnnotationColourGradient;
30 import jalview.schemes.GraduatedColor;
31 import jalview.schemes.UserColourScheme;
32 import jalview.util.Format;
33 import jalview.util.MapList;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.Hashtable;
40 import java.util.Iterator;
41 import java.util.List;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
47 * Parse and create Jalview Features files Detects GFF format features files and
48 * parses. Does not implement standard print() - call specific printFeatures or
49 * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
50 * for the features annotation - this normally works on an exact match.
55 public class FeaturesFile extends AlignFile
58 * work around for GFF interpretation bug where source string becomes
59 * description rather than a group
61 private boolean doGffSource = true;
63 private int gffversion;
66 * Creates a new FeaturesFile object.
77 public FeaturesFile(String inFile, String type) throws IOException
86 public FeaturesFile(FileParse source) throws IOException
92 * @param parseImmediately
96 public FeaturesFile(boolean parseImmediately, FileParse source)
99 super(parseImmediately, source);
103 * @param parseImmediately
106 * @throws IOException
108 public FeaturesFile(boolean parseImmediately, String inFile, String type)
111 super(parseImmediately, inFile, type);
115 * Parse GFF or sequence features file using case-independent matching,
119 * - alignment/dataset containing sequences that are to be annotated
121 * - hashtable to store feature colour definitions
123 * - process html strings into plain text
124 * @return true if features were added
126 public boolean parse(AlignmentI align, Map colours, boolean removeHTML)
128 return parse(align, colours, null, removeHTML, false);
132 * Parse GFF or sequence features file optionally using case-independent
133 * matching, discarding URLs
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 * @param relaxedIdmatching
142 * - when true, ID matches to compound sequence IDs are allowed
143 * @return true if features were added
145 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
146 boolean relaxedIdMatching)
148 return parse(align, colours, null, removeHTML, relaxedIdMatching);
152 * Parse GFF or sequence features file optionally using case-independent
156 * - alignment/dataset containing sequences that are to be annotated
158 * - hashtable to store feature colour definitions
160 * - hashtable to store associated URLs
162 * - process html strings into plain text
163 * @return true if features were added
165 public boolean parse(AlignmentI align, Map colours, Map featureLink,
168 return parse(align, colours, featureLink, removeHTML, false);
172 public void addAnnotations(AlignmentI al)
174 // TODO Auto-generated method stub
175 super.addAnnotations(al);
179 public void addProperties(AlignmentI al)
181 // TODO Auto-generated method stub
182 super.addProperties(al);
186 public void addSeqGroups(AlignmentI al)
188 // TODO Auto-generated method stub
189 super.addSeqGroups(al);
193 * Parse GFF or sequence features file
196 * - alignment/dataset containing sequences that are to be annotated
198 * - hashtable to store feature colour definitions
200 * - hashtable to store associated URLs
202 * - process html strings into plain text
203 * @param relaxedIdmatching
204 * - when true, ID matches to compound sequence IDs are allowed
205 * @return true if features were added
207 public boolean parse(AlignmentI align, Map colours, Map featureLink,
208 boolean removeHTML, boolean relaxedIdmatching)
214 SequenceI seq = null;
216 * keep track of any sequences we try to create from the data if it is a
219 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
220 String type, desc, token = null;
222 int index, start, end;
226 String featureGroup = null, groupLink = null;
227 Map typeLink = new Hashtable();
229 * when true, assume GFF style features rather than Jalview style.
231 boolean GFFFile = true;
232 Map<String, String> gffProps = new HashMap<String, String>();
233 while ((line = nextLine()) != null)
235 // skip comments/process pragmas
236 if (line.startsWith("#"))
238 if (line.startsWith("##"))
240 // possibly GFF2/3 version and metadata header
241 processGffPragma(line, gffProps, align, newseqs);
247 st = new StringTokenizer(line, "\t");
248 if (st.countTokens() == 1)
250 if (line.trim().equalsIgnoreCase("GFF"))
252 // Start parsing file as if it might be GFF again.
257 if (st.countTokens() > 1 && st.countTokens() < 4)
260 type = st.nextToken();
261 if (type.equalsIgnoreCase("startgroup"))
263 featureGroup = st.nextToken();
264 if (st.hasMoreElements())
266 groupLink = st.nextToken();
267 featureLink.put(featureGroup, groupLink);
270 else if (type.equalsIgnoreCase("endgroup"))
272 // We should check whether this is the current group,
273 // but at present theres no way of showing more than 1 group
280 Object colour = null;
281 String colscheme = st.nextToken();
282 if (colscheme.indexOf("|") > -1
283 || colscheme.trim().equalsIgnoreCase("label"))
285 // Parse '|' separated graduated colourscheme fields:
286 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
287 // can either provide 'label' only, first is optional, next two
288 // colors are required (but may be
289 // left blank), next is optional, nxt two min/max are required.
290 // first is either 'label'
291 // first/second and third are both hexadecimal or word equivalent
293 // next two are values parsed as floats.
294 // fifth is either 'above','below', or 'none'.
295 // sixth is a float value and only required when fifth is either
296 // 'above' or 'below'.
297 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
300 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
301 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
302 boolean labelCol = false;
304 String mincol = gcol.nextToken();
308 .println("Expected either 'label' or a colour specification in the line: "
312 String maxcol = null;
313 if (mincol.toLowerCase().indexOf("label") == 0)
316 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
318 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
320 String abso = null, minval, maxval;
323 // at least four more tokens
324 if (mincol.equals("|"))
330 gcol.nextToken(); // skip next '|'
332 // continue parsing rest of line
333 maxcol = gcol.nextToken();
334 if (maxcol.equals("|"))
340 gcol.nextToken(); // skip next '|'
342 abso = gcol.nextToken();
343 gcol.nextToken(); // skip next '|'
344 if (abso.toLowerCase().indexOf("abso") != 0)
351 minval = gcol.nextToken();
352 gcol.nextToken(); // skip next '|'
354 maxval = gcol.nextToken();
355 if (gcol.hasMoreTokens())
357 gcol.nextToken(); // skip next '|'
361 if (minval.length() > 0)
363 min = new Float(minval).floatValue();
365 } catch (Exception e)
368 .println("Couldn't parse the minimum value for graduated colour for type ("
370 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
375 if (maxval.length() > 0)
377 max = new Float(maxval).floatValue();
379 } catch (Exception e)
382 .println("Couldn't parse the maximum value for graduated colour for type ("
389 // add in some dummy min/max colours for the label-only
396 colour = new jalview.schemes.GraduatedColor(
397 new UserColourScheme(mincol).findColour('A'),
398 new UserColourScheme(maxcol).findColour('A'), min,
400 } catch (Exception e)
403 .println("Couldn't parse the graduated colour scheme ("
409 ((jalview.schemes.GraduatedColor) colour)
410 .setColourByLabel(labelCol);
411 ((jalview.schemes.GraduatedColor) colour)
412 .setAutoScaled(abso == null);
413 // add in any additional parameters
414 String ttype = null, tval = null;
415 if (gcol.hasMoreTokens())
417 // threshold type and possibly a threshold value
418 ttype = gcol.nextToken();
419 if (ttype.toLowerCase().startsWith("below"))
421 ((jalview.schemes.GraduatedColor) colour)
422 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
424 else if (ttype.toLowerCase().startsWith("above"))
426 ((jalview.schemes.GraduatedColor) colour)
427 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
431 ((jalview.schemes.GraduatedColor) colour)
432 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
433 if (!ttype.toLowerCase().startsWith("no"))
436 .println("Ignoring unrecognised threshold type : "
441 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
446 tval = gcol.nextToken();
447 ((jalview.schemes.GraduatedColor) colour)
448 .setThresh(new Float(tval).floatValue());
449 } catch (Exception e)
452 .println("Couldn't parse threshold value as a float: ("
457 // parse the thresh-is-min token ?
458 if (gcol.hasMoreTokens())
461 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
462 while (gcol.hasMoreTokens())
464 System.err.println("|" + gcol.nextToken());
466 System.err.println("\n");
472 UserColourScheme ucs = new UserColourScheme(colscheme);
473 colour = ucs.findColour('A');
477 colours.put(type, colour);
479 if (st.hasMoreElements())
481 String link = st.nextToken();
482 typeLink.put(type, link);
483 if (featureLink == null)
485 featureLink = new Hashtable();
487 featureLink.put(type, link);
493 while (st.hasMoreElements())
498 // Still possible this is an old Jalview file,
499 // which does not have type colours at the beginning
500 seqId = token = st.nextToken();
501 seq = findName(align, seqId, relaxedIdmatching, newseqs);
504 desc = st.nextToken();
506 if (doGffSource && desc.indexOf(' ') == -1)
508 // could also be a source term rather than description line
509 group = new String(desc);
511 type = st.nextToken();
514 String stt = st.nextToken();
515 if (stt.length() == 0 || stt.equals("-"))
521 start = Integer.parseInt(stt);
523 } catch (NumberFormatException ex)
529 String stt = st.nextToken();
530 if (stt.length() == 0 || stt.equals("-"))
536 end = Integer.parseInt(stt);
538 } catch (NumberFormatException ex)
542 // TODO: decide if non positional feature assertion for input data
543 // where end==0 is generally valid
546 // treat as non-positional feature, regardless.
551 score = new Float(st.nextToken()).floatValue();
552 } catch (NumberFormatException ex)
557 sf = new SequenceFeature(type, desc, start, end, score, group);
561 sf.setValue("STRAND", st.nextToken());
562 sf.setValue("FRAME", st.nextToken());
563 } catch (Exception ex)
567 if (st.hasMoreTokens())
569 StringBuffer attributes = new StringBuffer();
571 while (st.hasMoreTokens())
573 attributes.append((sep ? "\t" : "") + st.nextElement());
576 // TODO validate and split GFF2 attributes field ? parse out
577 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
578 // sf.setValue(attrib, val);
579 sf.setValue("ATTRIBUTES", attributes.toString());
582 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
585 // check whether we should add the sequence feature to any other
586 // sequences in the alignment with the same or similar
587 while ((seq = align.findName(seq, seqId, true)) != null)
589 seq.addSequenceFeature(new SequenceFeature(sf));
596 if (GFFFile && seq == null)
602 desc = st.nextToken();
604 if (!st.hasMoreTokens())
607 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
608 // in all probability, this isn't a file we understand, so bail
613 token = st.nextToken();
615 if (!token.equals("ID_NOT_SPECIFIED"))
617 seq = findName(align, seqId = token, relaxedIdmatching, null);
625 index = Integer.parseInt(st.nextToken());
626 seq = align.getSequenceAt(index);
627 } catch (NumberFormatException ex)
635 System.out.println("Sequence not found: " + line);
639 start = Integer.parseInt(st.nextToken());
640 end = Integer.parseInt(st.nextToken());
642 type = st.nextToken();
644 if (!colours.containsKey(type))
646 // Probably the old style groups file
647 UserColourScheme ucs = new UserColourScheme(type);
648 colours.put(type, ucs.findColour('A'));
650 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
651 if (st.hasMoreTokens())
655 score = new Float(st.nextToken()).floatValue();
656 // update colourgradient bounds if allowed to
657 } catch (NumberFormatException ex)
663 if (groupLink != null && removeHTML)
665 sf.addLink(groupLink);
666 sf.description += "%LINK%";
668 if (typeLink.containsKey(type) && removeHTML)
670 sf.addLink(typeLink.get(type).toString());
671 sf.description += "%LINK%";
674 parseDescriptionHTML(sf, removeHTML);
676 seq.addSequenceFeature(sf);
679 && (seq = align.findName(seq, seqId, false)) != null)
681 seq.addSequenceFeature(new SequenceFeature(sf));
683 // If we got here, its not a GFFFile
688 } catch (Exception ex)
690 // should report somewhere useful for UI if necessary
691 warningMessage = ((warningMessage == null) ? "" : warningMessage)
692 + "Parsing error at\n" + line;
693 System.out.println("Error parsing feature file: " + ex + "\n" + line);
694 ex.printStackTrace(System.err);
702 private enum GffPragmas
704 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
707 private static Map<String, GffPragmas> GFFPRAGMA;
710 GFFPRAGMA = new HashMap<String, GffPragmas>();
711 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
712 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
713 GFFPRAGMA.put("#", GffPragmas.hash);
714 GFFPRAGMA.put("fasta", GffPragmas.fasta);
715 GFFPRAGMA.put("species-build", GffPragmas.species_build);
716 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
717 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
720 private void processGffPragma(String line, Map<String, String> gffProps,
721 AlignmentI align, ArrayList<SequenceI> newseqs)
724 // line starts with ##
725 int spacepos = line.indexOf(' ');
726 String pragma = spacepos == -1 ? line.substring(2).trim() : line
727 .substring(2, spacepos);
728 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
729 if (gffpragma == null)
738 gffversion = Integer.parseInt(line.substring(spacepos + 1));
744 case feature_ontology:
745 // resolve against specific feature ontology
747 case attribute_ontology:
748 // resolve against specific attribute ontology
750 case source_ontology:
751 // resolve against specific source ontology
754 // resolve against specific NCBI taxon version
757 // close off any open feature hierarchies
760 // process the rest of the file as a fasta file and replace any dummy
762 process_as_fasta(align, newseqs);
766 System.err.println("Ignoring unknown pragma:\n" + line);
770 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
776 } catch (IOException q)
779 FastaFile parser = new FastaFile(this);
780 List<SequenceI> includedseqs = parser.getSeqs();
781 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
782 // iterate over includedseqs, and replacing matching ones with newseqs
783 // sequences. Generic iterator not used here because we modify includedseqs
785 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
787 // search for any dummy seqs that this sequence can be used to update
788 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
789 if (dummyseq != null)
791 // dummyseq was created so it could be annotated and referred to in
792 // alignments/codon mappings
794 SequenceI mseq = includedseqs.get(p);
795 // mseq is the 'template' imported from the FASTA file which we'll use
796 // to coomplete dummyseq
797 if (dummyseq instanceof SequenceDummy)
799 // probably have the pattern wrong
800 // idea is that a flyweight proxy for a sequence ID can be created for
801 // 1. stable reference creation
802 // 2. addition of annotation
803 // 3. future replacement by a real sequence
804 // current pattern is to create SequenceDummy objects - a convenience
805 // constructor for a Sequence.
806 // problem is that when promoted to a real sequence, all references
808 // to be updated somehow.
809 ((SequenceDummy) dummyseq).become(mseq);
810 includedseqs.set(p, dummyseq); // template is no longer needed
814 // finally add sequences to the dataset
815 for (SequenceI seq : includedseqs)
817 align.addSequence(seq);
822 * take a sequence feature and examine its attributes to decide how it should
823 * be added to a sequence
826 * - the destination sequence constructed or discovered in the
829 * - the base feature with ATTRIBUTES property containing any
830 * additional attributes
832 * - true if we are processing a GFF annotation file
833 * @return true if sf was actually added to the sequence, false if it was
834 * processed in another way
836 public boolean processOrAddSeqFeature(AlignmentI align,
837 List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
838 boolean gFFFile, boolean relaxedIdMatching)
840 String attr = (String) sf.getValue("ATTRIBUTES");
842 if (gFFFile && attr != null)
846 for (String attset : attr.split("\t"))
848 if (attset == null || attset.trim().length() == 0)
853 Map<String, List<String>> set = new HashMap<String, List<String>>();
854 // normally, only expect one column - 9 - in this field
855 // the attributes (Gff3) or groups (gff2) field
856 for (String pair : attset.trim().split(";"))
859 if (pair.length() == 0)
864 // expect either space seperated (gff2) or '=' separated (gff3)
865 // key/value pairs here
867 int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
868 String key = null, value = null;
870 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
872 key = pair.substring(0, sppos);
873 value = pair.substring(sppos + 1);
877 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
879 key = pair.substring(0, eqpos);
880 value = pair.substring(eqpos + 1);
889 List<String> vals = set.get(key);
892 vals = new ArrayList<String>();
897 vals.add(value.trim());
903 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
904 relaxedIdMatching); // process decides if
905 // feature is actually
907 } catch (InvalidGFF3FieldException ivfe)
909 System.err.println(ivfe);
915 seq.addSequenceFeature(sf);
920 public class InvalidGFF3FieldException extends Exception
924 public InvalidGFF3FieldException(String field,
925 Map<String, List<String>> set, String message)
927 super(message + " (Field was " + field + " and value was "
928 + set.get(field).toString());
930 this.value = set.get(field).toString();
936 * take a set of keys for a feature and interpret them
944 public boolean processGffKey(Map<String, List<String>> set, int nattr,
945 SequenceI seq, SequenceFeature sf, AlignmentI align,
946 List<SequenceI> newseqs, boolean relaxedIdMatching)
947 throws InvalidGFF3FieldException
950 // decide how to interpret according to type
951 if (sf.getType().equals("similarity"))
953 int strand = sf.getStrand();
954 // exonerate cdna/protein map
956 List<SequenceI> querySeq = findNames(align, newseqs,
957 relaxedIdMatching, set.get(attr = "Query"));
958 if (querySeq == null || querySeq.size() != 1)
960 throw new InvalidGFF3FieldException(attr, set,
961 "Expecting exactly one sequence in Query field (got "
962 + set.get(attr) + ")");
964 if (set.containsKey(attr = "Align"))
966 // process the align maps and create cdna/protein maps
967 // ideally, the query sequences are in the alignment, but maybe not...
969 AlignedCodonFrame alco = new AlignedCodonFrame();
970 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
973 // add codon mapping, and hope!
974 alco.addMap(seq, querySeq.get(0), codonmapping);
975 align.addCodonFrame(alco);
976 // everything that's needed to be done is done
977 // no features to create here !
985 private MapList constructCodonMappingFromAlign(
986 Map<String, List<String>> set, String attr, int strand)
987 throws InvalidGFF3FieldException
991 throw new InvalidGFF3FieldException(attr, set,
992 "Invalid strand for a codon mapping (cannot be 0)");
994 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
995 int lastppos = 0, lastpframe = 0;
996 for (String range : set.get(attr))
998 List<Integer> ints = new ArrayList<Integer>();
999 StringTokenizer st = new StringTokenizer(range, " ");
1000 while (st.hasMoreTokens())
1002 String num = st.nextToken();
1005 ints.add(new Integer(num));
1006 } catch (NumberFormatException nfe)
1008 throw new InvalidGFF3FieldException(attr, set,
1009 "Invalid number in field " + num);
1012 // Align positionInRef positionInQuery LengthInRef
1013 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1014 // 3652 - . alignment_id 0 ;
1015 // Query DDB_G0269124
1016 // Align 11270 143 120
1017 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1018 // dna in strand direction
1019 // Align 11150 187 282
1020 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1021 // dna in strand direction
1023 // Align 10865 281 888
1024 // Align 9977 578 1068
1025 // Align 8909 935 375
1027 if (ints.size() != 3)
1029 throw new InvalidGFF3FieldException(attr, set,
1030 "Invalid number of fields for this attribute ("
1031 + ints.size() + ")");
1033 fromrange.add(new Integer(ints.get(0).intValue()));
1034 fromrange.add(new Integer(ints.get(0).intValue() + strand
1035 * ints.get(2).intValue()));
1036 // how are intron/exon boundaries that do not align in codons
1038 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1040 // extend existing to map
1041 lastppos += ints.get(2) / 3;
1042 lastpframe = ints.get(2) % 3;
1043 torange.set(torange.size() - 1, new Integer(lastppos));
1048 torange.add(ints.get(1));
1049 lastppos = ints.get(1) + ints.get(2) / 3;
1050 lastpframe = ints.get(2) % 3;
1051 torange.add(new Integer(lastppos));
1054 // from and to ranges must end up being a series of start/end intervals
1055 if (fromrange.size() % 2 == 1)
1057 throw new InvalidGFF3FieldException(attr, set,
1058 "Couldn't parse the DNA alignment range correctly");
1060 if (torange.size() % 2 == 1)
1062 throw new InvalidGFF3FieldException(attr, set,
1063 "Couldn't parse the protein alignment range correctly");
1065 // finally, build the map
1066 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1069 for (Integer ip : fromrange)
1071 frommap[p++] = ip.intValue();
1074 for (Integer ip : torange)
1076 tomap[p++] = ip.intValue();
1079 return new MapList(frommap, tomap, 3, 1);
1082 private List<SequenceI> findNames(AlignmentI align,
1083 List<SequenceI> newseqs, boolean relaxedIdMatching,
1086 List<SequenceI> found = new ArrayList<SequenceI>();
1087 for (String seqId : list)
1089 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1098 private AlignmentI lastmatchedAl = null;
1100 private SequenceIdMatcher matcher = null;
1103 * clear any temporary handles used to speed up ID matching
1105 private void resetMatcher()
1107 lastmatchedAl = null;
1111 private SequenceI findName(AlignmentI align, String seqId,
1112 boolean relaxedIdMatching, List<SequenceI> newseqs)
1114 SequenceI match = null;
1115 if (relaxedIdMatching)
1117 if (lastmatchedAl != align)
1119 matcher = new SequenceIdMatcher(
1120 (lastmatchedAl = align).getSequencesArray());
1121 if (newseqs != null)
1123 matcher.addAll(newseqs);
1126 match = matcher.findIdMatch(seqId);
1130 match = align.findName(seqId, true);
1131 if (match == null && newseqs != null)
1133 for (SequenceI m : newseqs)
1135 if (seqId.equals(m.getName()))
1143 if (match == null && newseqs != null)
1145 match = new SequenceDummy(seqId);
1146 if (relaxedIdMatching)
1148 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1150 // add dummy sequence to the newseqs list
1156 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1158 if (sf.getDescription() == null)
1162 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1163 sf.getDescription(), removeHTML, newline);
1165 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1167 for (String link : parsed.getLinks())
1175 * generate a features file for seqs includes non-pos features by default.
1178 * source of sequence features
1180 * hash of feature types and colours
1181 * @return features file contents
1183 public String printJalviewFormat(SequenceI[] seqs,
1184 Map<String, Object> visible)
1186 return printJalviewFormat(seqs, visible, true, true);
1190 * generate a features file for seqs with colours from visible (if any)
1193 * source of features
1195 * hash of Colours for each feature type
1197 * when true only feature types in 'visible' will be output
1199 * indicates if non-positional features should be output (regardless
1201 * @return features file contents
1203 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1204 boolean visOnly, boolean nonpos)
1206 StringBuffer out = new StringBuffer();
1207 SequenceFeature[] next;
1208 boolean featuresGen = false;
1209 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1211 // no point continuing.
1212 return "No Features Visible";
1215 if (visible != null && visOnly)
1217 // write feature colours only if we're given them and we are generating
1219 // TODO: decide if feature links should also be written here ?
1220 Iterator en = visible.keySet().iterator();
1222 while (en.hasNext())
1224 type = en.next().toString();
1226 if (visible.get(type) instanceof GraduatedColor)
1228 GraduatedColor gc = (GraduatedColor) visible.get(type);
1229 color = (gc.isColourByLabel() ? "label|" : "")
1230 + Format.getHexString(gc.getMinColor()) + "|"
1231 + Format.getHexString(gc.getMaxColor())
1232 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1233 + gc.getMax() + "|";
1234 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1236 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1242 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1244 System.err.println("WARNING: Unsupported threshold type ("
1245 + gc.getThreshType() + ") : Assuming 'above'");
1250 color += "|" + gc.getThresh();
1257 else if (visible.get(type) instanceof java.awt.Color)
1259 color = Format.getHexString((java.awt.Color) visible.get(type));
1263 // legacy support for integer objects containing colour triplet values
1264 color = Format.getHexString(new java.awt.Color(Integer
1265 .parseInt(visible.get(type).toString())));
1270 out.append(newline);
1273 // Work out which groups are both present and visible
1274 Vector groups = new Vector();
1276 boolean isnonpos = false;
1278 for (int i = 0; i < seqs.length; i++)
1280 next = seqs[i].getSequenceFeatures();
1283 for (int j = 0; j < next.length; j++)
1285 isnonpos = next[j].begin == 0 && next[j].end == 0;
1286 if ((!nonpos && isnonpos)
1287 || (!isnonpos && visOnly && !visible
1288 .containsKey(next[j].type)))
1293 if (next[j].featureGroup != null
1294 && !groups.contains(next[j].featureGroup))
1296 groups.addElement(next[j].featureGroup);
1302 String group = null;
1306 if (groups.size() > 0 && groupIndex < groups.size())
1308 group = groups.elementAt(groupIndex).toString();
1309 out.append(newline);
1310 out.append("STARTGROUP\t");
1312 out.append(newline);
1319 for (int i = 0; i < seqs.length; i++)
1321 next = seqs[i].getSequenceFeatures();
1324 for (int j = 0; j < next.length; j++)
1326 isnonpos = next[j].begin == 0 && next[j].end == 0;
1327 if ((!nonpos && isnonpos)
1328 || (!isnonpos && visOnly && !visible
1329 .containsKey(next[j].type)))
1331 // skip if feature is nonpos and we ignore them or if we only
1332 // output visible and it isn't non-pos and it's not visible
1337 && (next[j].featureGroup == null || !next[j].featureGroup
1343 if (group == null && next[j].featureGroup != null)
1347 // we have features to output
1349 if (next[j].description == null
1350 || next[j].description.equals(""))
1352 out.append(next[j].type + "\t");
1356 if (next[j].links != null
1357 && next[j].getDescription().indexOf("<html>") == -1)
1359 out.append("<html>");
1362 out.append(next[j].description + " ");
1363 if (next[j].links != null)
1365 for (int l = 0; l < next[j].links.size(); l++)
1367 String label = next[j].links.elementAt(l).toString();
1368 String href = label.substring(label.indexOf("|") + 1);
1369 label = label.substring(0, label.indexOf("|"));
1371 if (next[j].description.indexOf(href) == -1)
1373 out.append("<a href=\"" + href + "\">" + label + "</a>");
1377 if (next[j].getDescription().indexOf("</html>") == -1)
1379 out.append("</html>");
1385 out.append(seqs[i].getName());
1386 out.append("\t-1\t");
1387 out.append(next[j].begin);
1389 out.append(next[j].end);
1391 out.append(next[j].type);
1392 if (!Float.isNaN(next[j].score))
1395 out.append(next[j].score);
1397 out.append(newline);
1404 out.append("ENDGROUP\t");
1406 out.append(newline);
1414 } while (groupIndex < groups.size() + 1);
1418 return "No Features Visible";
1421 return out.toString();
1425 * generate a gff file for sequence features includes non-pos features by
1432 public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1434 return printGFFFormat(seqs, visible, true, true);
1437 public String printGFFFormat(SequenceI[] seqs,
1438 Map<String, Object> visible, boolean visOnly, boolean nonpos)
1440 StringBuffer out = new StringBuffer();
1441 SequenceFeature[] next;
1444 for (int i = 0; i < seqs.length; i++)
1446 if (seqs[i].getSequenceFeatures() != null)
1448 next = seqs[i].getSequenceFeatures();
1449 for (int j = 0; j < next.length; j++)
1451 isnonpos = next[j].begin == 0 && next[j].end == 0;
1452 if ((!nonpos && isnonpos)
1453 || (!isnonpos && visOnly && !visible
1454 .containsKey(next[j].type)))
1459 source = next[j].featureGroup;
1462 source = next[j].getDescription();
1465 out.append(seqs[i].getName());
1469 out.append(next[j].type);
1471 out.append(next[j].begin);
1473 out.append(next[j].end);
1475 out.append(next[j].score);
1478 if (next[j].getValue("STRAND") != null)
1480 out.append(next[j].getValue("STRAND"));
1488 if (next[j].getValue("FRAME") != null)
1490 out.append(next[j].getValue("FRAME"));
1496 // TODO: verify/check GFF - should there be a /t here before attribute
1499 if (next[j].getValue("ATTRIBUTES") != null)
1501 out.append(next[j].getValue("ATTRIBUTES"));
1504 out.append(newline);
1510 return out.toString();
1514 * this is only for the benefit of object polymorphism - method does nothing.
1522 * this is only for the benefit of object polymorphism - method does nothing.
1524 * @return error message
1526 public String print()
1528 return "USE printGFFFormat() or printJalviewFormat()";