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
220 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
221 String type, desc, token = null;
223 int index, start, end;
227 String featureGroup = null, groupLink = null;
228 Map typeLink = new Hashtable();
230 * when true, assume GFF style features rather than Jalview style.
232 boolean GFFFile = true;
233 Map<String, String> gffProps = new HashMap<String, String>();
234 while ((line = nextLine()) != null)
236 // skip comments/process pragmas
237 if (line.startsWith("#"))
239 if (line.startsWith("##"))
241 // possibly GFF2/3 version and metadata header
242 processGffPragma(line, gffProps, align, newseqs);
248 st = new StringTokenizer(line, "\t");
249 if (st.countTokens() == 1)
251 if (line.trim().equalsIgnoreCase("GFF"))
253 // Start parsing file as if it might be GFF again.
258 if (st.countTokens() > 1 && st.countTokens() < 4)
261 type = st.nextToken();
262 if (type.equalsIgnoreCase("startgroup"))
264 featureGroup = st.nextToken();
265 if (st.hasMoreElements())
267 groupLink = st.nextToken();
268 featureLink.put(featureGroup, groupLink);
271 else if (type.equalsIgnoreCase("endgroup"))
273 // We should check whether this is the current group,
274 // but at present theres no way of showing more than 1 group
281 Object colour = null;
282 String colscheme = st.nextToken();
283 if (colscheme.indexOf("|") > -1
284 || colscheme.trim().equalsIgnoreCase("label"))
286 // Parse '|' separated graduated colourscheme fields:
287 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
288 // can either provide 'label' only, first is optional, next two
289 // colors are required (but may be
290 // left blank), next is optional, nxt two min/max are required.
291 // first is either 'label'
292 // first/second and third are both hexadecimal or word equivalent
294 // next two are values parsed as floats.
295 // fifth is either 'above','below', or 'none'.
296 // sixth is a float value and only required when fifth is either
297 // 'above' or 'below'.
298 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
301 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
302 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
303 boolean labelCol = false;
305 String mincol = gcol.nextToken();
309 .println("Expected either 'label' or a colour specification in the line: "
313 String maxcol = null;
314 if (mincol.toLowerCase().indexOf("label") == 0)
317 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
319 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
321 String abso = null, minval, maxval;
324 // at least four more tokens
325 if (mincol.equals("|"))
331 gcol.nextToken(); // skip next '|'
333 // continue parsing rest of line
334 maxcol = gcol.nextToken();
335 if (maxcol.equals("|"))
341 gcol.nextToken(); // skip next '|'
343 abso = gcol.nextToken();
344 gcol.nextToken(); // skip next '|'
345 if (abso.toLowerCase().indexOf("abso") != 0)
352 minval = gcol.nextToken();
353 gcol.nextToken(); // skip next '|'
355 maxval = gcol.nextToken();
356 if (gcol.hasMoreTokens())
358 gcol.nextToken(); // skip next '|'
362 if (minval.length() > 0)
364 min = new Float(minval).floatValue();
366 } catch (Exception e)
369 .println("Couldn't parse the minimum value for graduated colour for type ("
371 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
376 if (maxval.length() > 0)
378 max = new Float(maxval).floatValue();
380 } catch (Exception e)
383 .println("Couldn't parse the maximum value for graduated colour for type ("
390 // add in some dummy min/max colours for the label-only
397 colour = new jalview.schemes.GraduatedColor(
398 new UserColourScheme(mincol).findColour('A'),
399 new UserColourScheme(maxcol).findColour('A'), min,
401 } catch (Exception e)
404 .println("Couldn't parse the graduated colour scheme ("
410 ((jalview.schemes.GraduatedColor) colour)
411 .setColourByLabel(labelCol);
412 ((jalview.schemes.GraduatedColor) colour)
413 .setAutoScaled(abso == null);
414 // add in any additional parameters
415 String ttype = null, tval = null;
416 if (gcol.hasMoreTokens())
418 // threshold type and possibly a threshold value
419 ttype = gcol.nextToken();
420 if (ttype.toLowerCase().startsWith("below"))
422 ((jalview.schemes.GraduatedColor) colour)
423 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
425 else if (ttype.toLowerCase().startsWith("above"))
427 ((jalview.schemes.GraduatedColor) colour)
428 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
432 ((jalview.schemes.GraduatedColor) colour)
433 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
434 if (!ttype.toLowerCase().startsWith("no"))
437 .println("Ignoring unrecognised threshold type : "
442 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
447 tval = gcol.nextToken();
448 ((jalview.schemes.GraduatedColor) colour)
449 .setThresh(new Float(tval).floatValue());
450 } catch (Exception e)
453 .println("Couldn't parse threshold value as a float: ("
458 // parse the thresh-is-min token ?
459 if (gcol.hasMoreTokens())
462 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
463 while (gcol.hasMoreTokens())
465 System.err.println("|" + gcol.nextToken());
467 System.err.println("\n");
473 UserColourScheme ucs = new UserColourScheme(colscheme);
474 colour = ucs.findColour('A');
478 colours.put(type, colour);
480 if (st.hasMoreElements())
482 String link = st.nextToken();
483 typeLink.put(type, link);
484 if (featureLink == null)
486 featureLink = new Hashtable();
488 featureLink.put(type, link);
494 while (st.hasMoreElements())
499 // Still possible this is an old Jalview file,
500 // which does not have type colours at the beginning
501 seqId = token = st.nextToken();
502 seq = findName(align, seqId, relaxedIdmatching, newseqs);
505 desc = st.nextToken();
507 if (doGffSource && desc.indexOf(' ') == -1)
509 // could also be a source term rather than description line
510 group = new String(desc);
512 type = st.nextToken();
515 String stt = st.nextToken();
516 if (stt.length() == 0 || stt.equals("-"))
522 start = Integer.parseInt(stt);
524 } catch (NumberFormatException ex)
530 String stt = st.nextToken();
531 if (stt.length() == 0 || stt.equals("-"))
537 end = Integer.parseInt(stt);
539 } catch (NumberFormatException ex)
543 // TODO: decide if non positional feature assertion for input data
544 // where end==0 is generally valid
547 // treat as non-positional feature, regardless.
552 score = new Float(st.nextToken()).floatValue();
553 } catch (NumberFormatException ex)
558 sf = new SequenceFeature(type, desc, start, end, score, group);
562 sf.setValue("STRAND", st.nextToken());
563 sf.setValue("FRAME", st.nextToken());
564 } catch (Exception ex)
568 if (st.hasMoreTokens())
570 StringBuffer attributes = new StringBuffer();
572 while (st.hasMoreTokens())
574 attributes.append((sep ? "\t" : "") + st.nextElement());
577 // TODO validate and split GFF2 attributes field ? parse out
578 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
579 // sf.setValue(attrib, val);
580 sf.setValue("ATTRIBUTES", attributes.toString());
583 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
586 // check whether we should add the sequence feature to any other
587 // sequences in the alignment with the same or similar
588 while ((seq = align.findName(seq, seqId, true)) != null)
590 seq.addSequenceFeature(new SequenceFeature(sf));
597 if (GFFFile && seq == null)
603 desc = st.nextToken();
605 if (!st.hasMoreTokens())
608 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
609 // in all probability, this isn't a file we understand, so bail
614 token = st.nextToken();
616 if (!token.equals("ID_NOT_SPECIFIED"))
618 seq = findName(align, seqId = token, relaxedIdmatching, null);
626 index = Integer.parseInt(st.nextToken());
627 seq = align.getSequenceAt(index);
628 } catch (NumberFormatException ex)
636 System.out.println("Sequence not found: " + line);
640 start = Integer.parseInt(st.nextToken());
641 end = Integer.parseInt(st.nextToken());
643 type = st.nextToken();
645 if (!colours.containsKey(type))
647 // Probably the old style groups file
648 UserColourScheme ucs = new UserColourScheme(type);
649 colours.put(type, ucs.findColour('A'));
651 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
652 if (st.hasMoreTokens())
656 score = new Float(st.nextToken()).floatValue();
657 // update colourgradient bounds if allowed to
658 } catch (NumberFormatException ex)
664 if (groupLink != null && removeHTML)
666 sf.addLink(groupLink);
667 sf.description += "%LINK%";
669 if (typeLink.containsKey(type) && removeHTML)
671 sf.addLink(typeLink.get(type).toString());
672 sf.description += "%LINK%";
675 parseDescriptionHTML(sf, removeHTML);
677 seq.addSequenceFeature(sf);
680 && (seq = align.findName(seq, seqId, false)) != null)
682 seq.addSequenceFeature(new SequenceFeature(sf));
684 // If we got here, its not a GFFFile
689 } catch (Exception ex)
691 // should report somewhere useful for UI if necessary
692 warningMessage = ((warningMessage == null) ? "" : warningMessage)
693 + "Parsing error at\n" + line;
694 System.out.println("Error parsing feature file: " + ex + "\n" + line);
695 ex.printStackTrace(System.err);
703 private enum GffPragmas
705 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
708 private static Map<String, GffPragmas> GFFPRAGMA;
711 GFFPRAGMA = new HashMap<String, GffPragmas>();
712 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
713 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
714 GFFPRAGMA.put("#", GffPragmas.hash);
715 GFFPRAGMA.put("fasta", GffPragmas.fasta);
716 GFFPRAGMA.put("species-build", GffPragmas.species_build);
717 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
718 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
721 private void processGffPragma(String line, Map<String, String> gffProps,
722 AlignmentI align, ArrayList<SequenceI> newseqs)
725 // line starts with ##
726 int spacepos = line.indexOf(' ');
727 String pragma = spacepos == -1 ? line.substring(2).trim() : line
728 .substring(2, spacepos);
729 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
730 if (gffpragma == null)
739 gffversion = Integer.parseInt(line.substring(spacepos + 1));
745 case feature_ontology:
746 // resolve against specific feature ontology
748 case attribute_ontology:
749 // resolve against specific attribute ontology
751 case source_ontology:
752 // resolve against specific source ontology
755 // resolve against specific NCBI taxon version
758 // close off any open feature hierarchies
761 // process the rest of the file as a fasta file and replace any dummy
763 process_as_fasta(align, newseqs);
767 System.err.println("Ignoring unknown pragma:\n" + line);
771 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
777 } catch (IOException q)
780 FastaFile parser = new FastaFile(this);
781 List<SequenceI> includedseqs = parser.getSeqs();
782 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
783 // iterate over includedseqs, and replacing matching ones with newseqs
784 // sequences. Generic iterator not used here because we modify includedseqs
786 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
788 // search for any dummy seqs that this sequence can be used to update
789 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
790 if (dummyseq != null)
792 // dummyseq was created so it could be annotated and referred to in
793 // alignments/codon mappings
795 SequenceI mseq = includedseqs.get(p);
796 // mseq is the 'template' imported from the FASTA file which we'll use
797 // to coomplete dummyseq
798 if (dummyseq instanceof SequenceDummy)
800 // probably have the pattern wrong
801 // idea is that a flyweight proxy for a sequence ID can be created for
802 // 1. stable reference creation
803 // 2. addition of annotation
804 // 3. future replacement by a real sequence
805 // current pattern is to create SequenceDummy objects - a convenience
806 // constructor for a Sequence.
807 // problem is that when promoted to a real sequence, all references
809 // to be updated somehow.
810 ((SequenceDummy) dummyseq).become(mseq);
811 includedseqs.set(p, dummyseq); // template is no longer needed
815 // finally add sequences to the dataset
816 for (SequenceI seq : includedseqs)
818 align.addSequence(seq);
823 * take a sequence feature and examine its attributes to decide how it should
824 * be added to a sequence
827 * - the destination sequence constructed or discovered in the
830 * - the base feature with ATTRIBUTES property containing any
831 * additional attributes
833 * - true if we are processing a GFF annotation file
834 * @return true if sf was actually added to the sequence, false if it was
835 * processed in another way
837 public boolean processOrAddSeqFeature(AlignmentI align,
838 List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
839 boolean gFFFile, boolean relaxedIdMatching)
841 String attr = (String) sf.getValue("ATTRIBUTES");
843 if (gFFFile && attr != null)
847 for (String attset : attr.split("\t"))
849 if (attset == null || attset.trim().length() == 0)
854 Map<String, List<String>> set = new HashMap<String, List<String>>();
855 // normally, only expect one column - 9 - in this field
856 // the attributes (Gff3) or groups (gff2) field
857 for (String pair : attset.trim().split(";"))
860 if (pair.length() == 0)
865 // expect either space seperated (gff2) or '=' separated (gff3)
866 // key/value pairs here
868 int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
869 String key = null, value = null;
871 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
873 key = pair.substring(0, sppos);
874 value = pair.substring(sppos + 1);
878 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
880 key = pair.substring(0, eqpos);
881 value = pair.substring(eqpos + 1);
890 List<String> vals = set.get(key);
893 vals = new ArrayList<String>();
898 vals.add(value.trim());
904 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
905 relaxedIdMatching); // process decides if
906 // feature is actually
908 } catch (InvalidGFF3FieldException ivfe)
910 System.err.println(ivfe);
916 seq.addSequenceFeature(sf);
921 public class InvalidGFF3FieldException extends Exception
925 public InvalidGFF3FieldException(String field,
926 Map<String, List<String>> set, String message)
928 super(message + " (Field was " + field + " and value was "
929 + set.get(field).toString());
931 this.value = set.get(field).toString();
937 * take a set of keys for a feature and interpret them
945 public boolean processGffKey(Map<String, List<String>> set, int nattr,
946 SequenceI seq, SequenceFeature sf, AlignmentI align,
947 List<SequenceI> newseqs, boolean relaxedIdMatching)
948 throws InvalidGFF3FieldException
951 // decide how to interpret according to type
952 if (sf.getType().equals("similarity"))
954 int strand = sf.getStrand();
955 // exonerate cdna/protein map
957 List<SequenceI> querySeq = findNames(align, newseqs,
958 relaxedIdMatching, set.get(attr = "Query"));
959 if (querySeq == null || querySeq.size() != 1)
961 throw new InvalidGFF3FieldException(attr, set,
962 "Expecting exactly one sequence in Query field (got "
963 + set.get(attr) + ")");
965 if (set.containsKey(attr = "Align"))
967 // process the align maps and create cdna/protein maps
968 // ideally, the query sequences are in the alignment, but maybe not...
970 AlignedCodonFrame alco = new AlignedCodonFrame();
971 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
974 // add codon mapping, and hope!
975 alco.addMap(seq, querySeq.get(0), codonmapping);
976 align.addCodonFrame(alco);
977 // everything that's needed to be done is done
978 // no features to create here !
986 private MapList constructCodonMappingFromAlign(
987 Map<String, List<String>> set, String attr, int strand)
988 throws InvalidGFF3FieldException
992 throw new InvalidGFF3FieldException(attr, set,
993 "Invalid strand for a codon mapping (cannot be 0)");
995 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
996 int lastppos = 0, lastpframe = 0;
997 for (String range : set.get(attr))
999 List<Integer> ints = new ArrayList<Integer>();
1000 StringTokenizer st = new StringTokenizer(range, " ");
1001 while (st.hasMoreTokens())
1003 String num = st.nextToken();
1006 ints.add(new Integer(num));
1007 } catch (NumberFormatException nfe)
1009 throw new InvalidGFF3FieldException(attr, set,
1010 "Invalid number in field " + num);
1013 // Align positionInRef positionInQuery LengthInRef
1014 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1015 // 3652 - . alignment_id 0 ;
1016 // Query DDB_G0269124
1017 // Align 11270 143 120
1018 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1019 // dna in strand direction
1020 // Align 11150 187 282
1021 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1022 // dna in strand direction
1024 // Align 10865 281 888
1025 // Align 9977 578 1068
1026 // Align 8909 935 375
1028 if (ints.size() != 3)
1030 throw new InvalidGFF3FieldException(attr, set,
1031 "Invalid number of fields for this attribute ("
1032 + ints.size() + ")");
1034 fromrange.add(new Integer(ints.get(0).intValue()));
1035 fromrange.add(new Integer(ints.get(0).intValue() + strand
1036 * ints.get(2).intValue()));
1037 // how are intron/exon boundaries that do not align in codons
1039 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1041 // extend existing to map
1042 lastppos += ints.get(2) / 3;
1043 lastpframe = ints.get(2) % 3;
1044 torange.set(torange.size() - 1, new Integer(lastppos));
1049 torange.add(ints.get(1));
1050 lastppos = ints.get(1) + ints.get(2) / 3;
1051 lastpframe = ints.get(2) % 3;
1052 torange.add(new Integer(lastppos));
1055 // from and to ranges must end up being a series of start/end intervals
1056 if (fromrange.size() % 2 == 1)
1058 throw new InvalidGFF3FieldException(attr, set,
1059 "Couldn't parse the DNA alignment range correctly");
1061 if (torange.size() % 2 == 1)
1063 throw new InvalidGFF3FieldException(attr, set,
1064 "Couldn't parse the protein alignment range correctly");
1066 // finally, build the map
1067 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1070 for (Integer ip : fromrange)
1072 frommap[p++] = ip.intValue();
1075 for (Integer ip : torange)
1077 tomap[p++] = ip.intValue();
1080 return new MapList(frommap, tomap, 3, 1);
1083 private List<SequenceI> findNames(AlignmentI align,
1084 List<SequenceI> newseqs, boolean relaxedIdMatching,
1087 List<SequenceI> found = new ArrayList<SequenceI>();
1088 for (String seqId : list)
1090 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1099 private AlignmentI lastmatchedAl = null;
1101 private SequenceIdMatcher matcher = null;
1104 * clear any temporary handles used to speed up ID matching
1106 private void resetMatcher()
1108 lastmatchedAl = null;
1112 private SequenceI findName(AlignmentI align, String seqId,
1113 boolean relaxedIdMatching, List<SequenceI> newseqs)
1115 SequenceI match = null;
1116 if (relaxedIdMatching)
1118 if (lastmatchedAl != align)
1120 matcher = new SequenceIdMatcher(
1121 (lastmatchedAl = align).getSequencesArray());
1122 if (newseqs != null)
1124 matcher.addAll(newseqs);
1127 match = matcher.findIdMatch(seqId);
1131 match = align.findName(seqId, true);
1132 if (match == null && newseqs != null)
1134 for (SequenceI m : newseqs)
1136 if (seqId.equals(m.getName()))
1144 if (match == null && newseqs != null)
1146 match = new SequenceDummy(seqId);
1147 if (relaxedIdMatching)
1149 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1151 // add dummy sequence to the newseqs list
1157 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1159 if (sf.getDescription() == null)
1163 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1164 sf.getDescription(), removeHTML, newline);
1166 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1168 for (String link : parsed.getLinks())
1176 * generate a features file for seqs includes non-pos features by default.
1179 * source of sequence features
1181 * hash of feature types and colours
1182 * @return features file contents
1184 public String printJalviewFormat(SequenceI[] seqs,
1185 Map<String, Object> visible)
1187 return printJalviewFormat(seqs, visible, true, true);
1191 * generate a features file for seqs with colours from visible (if any)
1194 * source of features
1196 * hash of Colours for each feature type
1198 * when true only feature types in 'visible' will be output
1200 * indicates if non-positional features should be output (regardless
1202 * @return features file contents
1204 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1205 boolean visOnly, boolean nonpos)
1207 StringBuffer out = new StringBuffer();
1208 SequenceFeature[] next;
1209 boolean featuresGen = false;
1210 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1212 // no point continuing.
1213 return "No Features Visible";
1216 if (visible != null && visOnly)
1218 // write feature colours only if we're given them and we are generating
1220 // TODO: decide if feature links should also be written here ?
1221 Iterator en = visible.keySet().iterator();
1223 while (en.hasNext())
1225 type = en.next().toString();
1227 if (visible.get(type) instanceof GraduatedColor)
1229 GraduatedColor gc = (GraduatedColor) visible.get(type);
1230 color = (gc.isColourByLabel() ? "label|" : "")
1231 + Format.getHexString(gc.getMinColor()) + "|"
1232 + Format.getHexString(gc.getMaxColor())
1233 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1234 + gc.getMax() + "|";
1235 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1237 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1243 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1245 System.err.println("WARNING: Unsupported threshold type ("
1246 + gc.getThreshType() + ") : Assuming 'above'");
1251 color += "|" + gc.getThresh();
1258 else if (visible.get(type) instanceof java.awt.Color)
1260 color = Format.getHexString((java.awt.Color) visible.get(type));
1264 // legacy support for integer objects containing colour triplet values
1265 color = Format.getHexString(new java.awt.Color(Integer
1266 .parseInt(visible.get(type).toString())));
1271 out.append(newline);
1274 // Work out which groups are both present and visible
1275 Vector groups = new Vector();
1277 boolean isnonpos = false;
1279 for (int i = 0; i < seqs.length; i++)
1281 next = seqs[i].getSequenceFeatures();
1284 for (int j = 0; j < next.length; j++)
1286 isnonpos = next[j].begin == 0 && next[j].end == 0;
1287 if ((!nonpos && isnonpos)
1288 || (!isnonpos && visOnly && !visible
1289 .containsKey(next[j].type)))
1294 if (next[j].featureGroup != null
1295 && !groups.contains(next[j].featureGroup))
1297 groups.addElement(next[j].featureGroup);
1303 String group = null;
1307 if (groups.size() > 0 && groupIndex < groups.size())
1309 group = groups.elementAt(groupIndex).toString();
1310 out.append(newline);
1311 out.append("STARTGROUP\t");
1313 out.append(newline);
1320 for (int i = 0; i < seqs.length; i++)
1322 next = seqs[i].getSequenceFeatures();
1325 for (int j = 0; j < next.length; j++)
1327 isnonpos = next[j].begin == 0 && next[j].end == 0;
1328 if ((!nonpos && isnonpos)
1329 || (!isnonpos && visOnly && !visible
1330 .containsKey(next[j].type)))
1332 // skip if feature is nonpos and we ignore them or if we only
1333 // output visible and it isn't non-pos and it's not visible
1338 && (next[j].featureGroup == null || !next[j].featureGroup
1344 if (group == null && next[j].featureGroup != null)
1348 // we have features to output
1350 if (next[j].description == null
1351 || next[j].description.equals(""))
1353 out.append(next[j].type + "\t");
1357 if (next[j].links != null
1358 && next[j].getDescription().indexOf("<html>") == -1)
1360 out.append("<html>");
1363 out.append(next[j].description + " ");
1364 if (next[j].links != null)
1366 for (int l = 0; l < next[j].links.size(); l++)
1368 String label = next[j].links.elementAt(l).toString();
1369 String href = label.substring(label.indexOf("|") + 1);
1370 label = label.substring(0, label.indexOf("|"));
1372 if (next[j].description.indexOf(href) == -1)
1374 out.append("<a href=\"" + href + "\">" + label + "</a>");
1378 if (next[j].getDescription().indexOf("</html>") == -1)
1380 out.append("</html>");
1386 out.append(seqs[i].getName());
1387 out.append("\t-1\t");
1388 out.append(next[j].begin);
1390 out.append(next[j].end);
1392 out.append(next[j].type);
1393 if (!Float.isNaN(next[j].score))
1396 out.append(next[j].score);
1398 out.append(newline);
1405 out.append("ENDGROUP\t");
1407 out.append(newline);
1415 } while (groupIndex < groups.size() + 1);
1419 return "No Features Visible";
1422 return out.toString();
1426 * generate a gff file for sequence features includes non-pos features by
1433 public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1435 return printGFFFormat(seqs, visible, true, true);
1438 public String printGFFFormat(SequenceI[] seqs,
1439 Map<String, Object> visible, boolean visOnly, boolean nonpos)
1441 StringBuffer out = new StringBuffer();
1442 SequenceFeature[] next;
1445 for (int i = 0; i < seqs.length; i++)
1447 if (seqs[i].getSequenceFeatures() != null)
1449 next = seqs[i].getSequenceFeatures();
1450 for (int j = 0; j < next.length; j++)
1452 isnonpos = next[j].begin == 0 && next[j].end == 0;
1453 if ((!nonpos && isnonpos)
1454 || (!isnonpos && visOnly && !visible
1455 .containsKey(next[j].type)))
1460 source = next[j].featureGroup;
1463 source = next[j].getDescription();
1466 out.append(seqs[i].getName());
1470 out.append(next[j].type);
1472 out.append(next[j].begin);
1474 out.append(next[j].end);
1476 out.append(next[j].score);
1479 if (next[j].getValue("STRAND") != null)
1481 out.append(next[j].getValue("STRAND"));
1489 if (next[j].getValue("FRAME") != null)
1491 out.append(next[j].getValue("FRAME"));
1497 // TODO: verify/check GFF - should there be a /t here before attribute
1500 if (next[j].getValue("ATTRIBUTES") != null)
1502 out.append(next[j].getValue("ATTRIBUTES"));
1505 out.append(newline);
1511 return out.toString();
1515 * this is only for the benefit of object polymorphism - method does nothing.
1523 * this is only for the benefit of object polymorphism - method does nothing.
1525 * @return error message
1527 public String print()
1529 return "USE printGFFFormat() or printJalviewFormat()";