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, Hashtable colours,
129 return parse(align, colours, null, removeHTML, false);
133 * Parse GFF or sequence features file optionally using case-independent
134 * matching, discarding URLs
137 * - alignment/dataset containing sequences that are to be annotated
139 * - hashtable to store feature colour definitions
141 * - process html strings into plain text
142 * @param relaxedIdmatching
143 * - when true, ID matches to compound sequence IDs are allowed
144 * @return true if features were added
146 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
147 boolean relaxedIdMatching)
149 return parse(align, colours, null, removeHTML, relaxedIdMatching);
153 * Parse GFF or sequence features file optionally using case-independent
157 * - alignment/dataset containing sequences that are to be annotated
159 * - hashtable to store feature colour definitions
161 * - hashtable to store associated URLs
163 * - process html strings into plain text
164 * @return true if features were added
166 public boolean parse(AlignmentI align, Map colours, Map featureLink,
169 return parse(align, colours, featureLink, removeHTML, false);
173 public void addAnnotations(AlignmentI al)
175 // TODO Auto-generated method stub
176 super.addAnnotations(al);
180 public void addProperties(AlignmentI al)
182 // TODO Auto-generated method stub
183 super.addProperties(al);
187 public void addSeqGroups(AlignmentI al)
189 // TODO Auto-generated method stub
190 super.addSeqGroups(al);
194 * Parse GFF or sequence features file
197 * - alignment/dataset containing sequences that are to be annotated
199 * - hashtable to store feature colour definitions
201 * - hashtable to store associated URLs
203 * - process html strings into plain text
204 * @param relaxedIdmatching
205 * - when true, ID matches to compound sequence IDs are allowed
206 * @return true if features were added
208 public boolean parse(AlignmentI align, Map colours, Map featureLink,
209 boolean removeHTML, boolean relaxedIdmatching)
215 SequenceI seq = null;
217 * keep track of any sequences we try to create from the data if it is a GFF3 file
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, List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
837 boolean gFFFile, boolean relaxedIdMatching)
839 String attr = (String) sf.getValue("ATTRIBUTES");
841 if (gFFFile && attr != null)
845 for (String attset : attr.split("\t"))
847 if (attset==null || attset.trim().length()==0)
852 Map<String, List<String>> set = new HashMap<String, List<String>>();
853 // normally, only expect one column - 9 - in this field
854 // the attributes (Gff3) or groups (gff2) field
855 for (String pair : attset.trim().split(";"))
858 if (pair.length() == 0)
863 // expect either space seperated (gff2) or '=' separated (gff3)
864 // key/value pairs here
866 int eqpos = pair.indexOf('='),sppos = pair.indexOf(' ');
867 String key = null, value = null;
869 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
871 key = pair.substring(0, sppos);
872 value = pair.substring(sppos + 1);
874 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
876 key = pair.substring(0, eqpos);
877 value = pair.substring(eqpos + 1);
885 List<String> vals = set.get(key);
888 vals = new ArrayList<String>();
893 vals.add(value.trim());
899 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
900 relaxedIdMatching); // process decides if
901 // feature is actually
903 } catch (InvalidGFF3FieldException ivfe)
905 System.err.println(ivfe);
911 seq.addSequenceFeature(sf);
916 public class InvalidGFF3FieldException extends Exception
920 public InvalidGFF3FieldException(String field,
921 Map<String, List<String>> set, String message)
923 super(message + " (Field was " + field + " and value was "
924 + set.get(field).toString());
926 this.value = set.get(field).toString();
932 * take a set of keys for a feature and interpret them
940 public boolean processGffKey(Map<String, List<String>> set, int nattr,
941 SequenceI seq, SequenceFeature sf, AlignmentI align,
942 List<SequenceI> newseqs, boolean relaxedIdMatching)
943 throws InvalidGFF3FieldException
946 // decide how to interpret according to type
947 if (sf.getType().equals("similarity"))
949 int strand = sf.getStrand();
950 // exonerate cdna/protein map
952 List<SequenceI> querySeq = findNames(align, newseqs,
953 relaxedIdMatching, set.get(attr="Query"));
954 if (querySeq==null || querySeq.size()!=1)
956 throw new InvalidGFF3FieldException( attr, set,
957 "Expecting exactly one sequence in Query field (got "
958 + set.get(attr) + ")");
960 if (set.containsKey(attr="Align"))
962 // process the align maps and create cdna/protein maps
963 // ideally, the query sequences are in the alignment, but maybe not...
965 AlignedCodonFrame alco = new AlignedCodonFrame();
966 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
969 // add codon mapping, and hope!
970 alco.addMap(seq, querySeq.get(0), codonmapping);
971 align.addCodonFrame(alco);
972 // everything that's needed to be done is done
973 // no features to create here !
981 private MapList constructCodonMappingFromAlign(
982 Map<String, List<String>> set,
983 String attr, int strand) throws InvalidGFF3FieldException
987 throw new InvalidGFF3FieldException(attr, set,
988 "Invalid strand for a codon mapping (cannot be 0)");
990 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
991 int lastppos = 0, lastpframe = 0;
992 for (String range : set.get(attr))
994 List<Integer> ints = new ArrayList<Integer>();
995 StringTokenizer st = new StringTokenizer(range, " ");
996 while (st.hasMoreTokens())
998 String num = st.nextToken();
1001 ints.add(new Integer(num));
1002 } catch (NumberFormatException nfe)
1004 throw new InvalidGFF3FieldException(attr, set,
1005 "Invalid number in field " + num);
1008 // Align positionInRef positionInQuery LengthInRef
1009 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1010 // 3652 - . alignment_id 0 ;
1011 // Query DDB_G0269124
1012 // Align 11270 143 120
1013 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1014 // dna in strand direction
1015 // Align 11150 187 282
1016 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1017 // dna in strand direction
1019 // Align 10865 281 888
1020 // Align 9977 578 1068
1021 // Align 8909 935 375
1023 if (ints.size() != 3)
1025 throw new InvalidGFF3FieldException(attr, set,
1026 "Invalid number of fields for this attribute ("
1027 + ints.size() + ")");
1029 fromrange.add(new Integer(ints.get(0).intValue()));
1030 fromrange.add(new Integer(ints.get(0).intValue() + strand
1031 * ints.get(2).intValue()));
1032 // how are intron/exon boundaries that do not align in codons
1034 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1036 // extend existing to map
1037 lastppos += ints.get(2) / 3;
1038 lastpframe = ints.get(2) % 3;
1039 torange.set(torange.size() - 1, new Integer(lastppos));
1044 torange.add(ints.get(1));
1045 lastppos = ints.get(1) + ints.get(2) / 3;
1046 lastpframe = ints.get(2) % 3;
1047 torange.add(new Integer(lastppos));
1050 // from and to ranges must end up being a series of start/end intervals
1051 if (fromrange.size() % 2 == 1)
1053 throw new InvalidGFF3FieldException(attr, set,
1054 "Couldn't parse the DNA alignment range correctly");
1056 if (torange.size() % 2 == 1)
1058 throw new InvalidGFF3FieldException(attr, set,
1059 "Couldn't parse the protein alignment range correctly");
1061 // finally, build the map
1062 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1065 for (Integer ip : fromrange)
1067 frommap[p++] = ip.intValue();
1070 for (Integer ip : torange)
1072 tomap[p++] = ip.intValue();
1075 return new MapList(frommap, tomap, 3, 1);
1078 private List<SequenceI> findNames(AlignmentI align,
1079 List<SequenceI> newseqs, boolean relaxedIdMatching,
1082 List<SequenceI> found = new ArrayList<SequenceI>();
1083 for (String seqId : list)
1085 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1094 private AlignmentI lastmatchedAl = null;
1096 private SequenceIdMatcher matcher = null;
1099 * clear any temporary handles used to speed up ID matching
1101 private void resetMatcher()
1103 lastmatchedAl = null;
1107 private SequenceI findName(AlignmentI align, String seqId,
1108 boolean relaxedIdMatching, List<SequenceI> newseqs)
1110 SequenceI match = null;
1111 if (relaxedIdMatching)
1113 if (lastmatchedAl != align)
1115 matcher = new SequenceIdMatcher(
1116 (lastmatchedAl = align).getSequencesArray());
1117 if (newseqs != null)
1119 matcher.addAll(newseqs);
1122 match = matcher.findIdMatch(seqId);
1126 match = align.findName(seqId, true);
1127 if (match == null && newseqs != null)
1129 for (SequenceI m : newseqs)
1131 if (seqId.equals(m.getName()))
1139 if (match==null && newseqs!=null)
1141 match = new SequenceDummy(seqId);
1142 if (relaxedIdMatching)
1144 matcher.addAll(Arrays.asList(new SequenceI[]
1147 // add dummy sequence to the newseqs list
1152 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1154 if (sf.getDescription() == null)
1158 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1159 sf.getDescription(), removeHTML, newline);
1161 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1163 for (String link : parsed.getLinks())
1171 * generate a features file for seqs includes non-pos features by default.
1174 * source of sequence features
1176 * hash of feature types and colours
1177 * @return features file contents
1179 public String printJalviewFormat(SequenceI[] seqs, Map<String,Object> visible)
1181 return printJalviewFormat(seqs, visible, true, true);
1185 * generate a features file for seqs with colours from visible (if any)
1188 * source of features
1190 * hash of Colours for each feature type
1192 * when true only feature types in 'visible' will be output
1194 * indicates if non-positional features should be output (regardless
1196 * @return features file contents
1198 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1199 boolean visOnly, boolean nonpos)
1201 StringBuffer out = new StringBuffer();
1202 SequenceFeature[] next;
1203 boolean featuresGen = false;
1204 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1206 // no point continuing.
1207 return "No Features Visible";
1210 if (visible != null && visOnly)
1212 // write feature colours only if we're given them and we are generating
1214 // TODO: decide if feature links should also be written here ?
1215 Iterator en = visible.keySet().iterator();
1217 while (en.hasNext())
1219 type = en.next().toString();
1221 if (visible.get(type) instanceof GraduatedColor)
1223 GraduatedColor gc = (GraduatedColor) visible.get(type);
1224 color = (gc.isColourByLabel() ? "label|" : "")
1225 + Format.getHexString(gc.getMinColor()) + "|"
1226 + Format.getHexString(gc.getMaxColor())
1227 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1228 + gc.getMax() + "|";
1229 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1231 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1237 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1239 System.err.println("WARNING: Unsupported threshold type ("
1240 + gc.getThreshType() + ") : Assuming 'above'");
1245 color += "|" + gc.getThresh();
1252 else if (visible.get(type) instanceof java.awt.Color)
1254 color = Format.getHexString((java.awt.Color) visible.get(type));
1258 // legacy support for integer objects containing colour triplet values
1259 color = Format.getHexString(new java.awt.Color(Integer
1260 .parseInt(visible.get(type).toString())));
1265 out.append(newline);
1268 // Work out which groups are both present and visible
1269 Vector groups = new Vector();
1271 boolean isnonpos = false;
1273 for (int i = 0; i < seqs.length; i++)
1275 next = seqs[i].getSequenceFeatures();
1278 for (int j = 0; j < next.length; j++)
1280 isnonpos = next[j].begin == 0 && next[j].end == 0;
1281 if ((!nonpos && isnonpos)
1282 || (!isnonpos && visOnly && !visible
1283 .containsKey(next[j].type)))
1288 if (next[j].featureGroup != null
1289 && !groups.contains(next[j].featureGroup))
1291 groups.addElement(next[j].featureGroup);
1297 String group = null;
1301 if (groups.size() > 0 && groupIndex < groups.size())
1303 group = groups.elementAt(groupIndex).toString();
1304 out.append(newline);
1305 out.append("STARTGROUP\t");
1307 out.append(newline);
1314 for (int i = 0; i < seqs.length; i++)
1316 next = seqs[i].getSequenceFeatures();
1319 for (int j = 0; j < next.length; j++)
1321 isnonpos = next[j].begin == 0 && next[j].end == 0;
1322 if ((!nonpos && isnonpos)
1323 || (!isnonpos && visOnly && !visible
1324 .containsKey(next[j].type)))
1326 // skip if feature is nonpos and we ignore them or if we only
1327 // output visible and it isn't non-pos and it's not visible
1332 && (next[j].featureGroup == null || !next[j].featureGroup
1338 if (group == null && next[j].featureGroup != null)
1342 // we have features to output
1344 if (next[j].description == null
1345 || next[j].description.equals(""))
1347 out.append(next[j].type + "\t");
1351 if (next[j].links != null
1352 && next[j].getDescription().indexOf("<html>") == -1)
1354 out.append("<html>");
1357 out.append(next[j].description + " ");
1358 if (next[j].links != null)
1360 for (int l = 0; l < next[j].links.size(); l++)
1362 String label = next[j].links.elementAt(l).toString();
1363 String href = label.substring(label.indexOf("|") + 1);
1364 label = label.substring(0, label.indexOf("|"));
1366 if (next[j].description.indexOf(href) == -1)
1368 out.append("<a href=\"" + href + "\">" + label + "</a>");
1372 if (next[j].getDescription().indexOf("</html>") == -1)
1374 out.append("</html>");
1380 out.append(seqs[i].getName());
1381 out.append("\t-1\t");
1382 out.append(next[j].begin);
1384 out.append(next[j].end);
1386 out.append(next[j].type);
1387 if (!Float.isNaN(next[j].score))
1390 out.append(next[j].score);
1392 out.append(newline);
1399 out.append("ENDGROUP\t");
1401 out.append(newline);
1409 } while (groupIndex < groups.size() + 1);
1413 return "No Features Visible";
1416 return out.toString();
1420 * generate a gff file for sequence features includes non-pos features by
1427 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible)
1429 return printGFFFormat(seqs, visible, true, true);
1432 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible,
1433 boolean visOnly, boolean nonpos)
1435 StringBuffer out = new StringBuffer();
1436 SequenceFeature[] next;
1439 for (int i = 0; i < seqs.length; i++)
1441 if (seqs[i].getSequenceFeatures() != null)
1443 next = seqs[i].getSequenceFeatures();
1444 for (int j = 0; j < next.length; j++)
1446 isnonpos = next[j].begin == 0 && next[j].end == 0;
1447 if ((!nonpos && isnonpos)
1448 || (!isnonpos && visOnly && !visible
1449 .containsKey(next[j].type)))
1454 source = next[j].featureGroup;
1457 source = next[j].getDescription();
1460 out.append(seqs[i].getName());
1464 out.append(next[j].type);
1466 out.append(next[j].begin);
1468 out.append(next[j].end);
1470 out.append(next[j].score);
1473 if (next[j].getValue("STRAND") != null)
1475 out.append(next[j].getValue("STRAND"));
1483 if (next[j].getValue("FRAME") != null)
1485 out.append(next[j].getValue("FRAME"));
1491 // TODO: verify/check GFF - should there be a /t here before attribute
1494 if (next[j].getValue("ATTRIBUTES") != null)
1496 out.append(next[j].getValue("ATTRIBUTES"));
1499 out.append(newline);
1505 return out.toString();
1509 * this is only for the benefit of object polymorphism - method does nothing.
1517 * this is only for the benefit of object polymorphism - method does nothing.
1519 * @return error message
1521 public String print()
1523 return "USE printGFFFormat() or printJalviewFormat()";