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 super.addAnnotations(al);
178 public void addProperties(AlignmentI al)
180 super.addProperties(al);
184 public void addSeqGroups(AlignmentI al)
186 super.addSeqGroups(al);
190 * Parse GFF or sequence features file
193 * - alignment/dataset containing sequences that are to be annotated
195 * - hashtable to store feature colour definitions
197 * - hashtable to store associated URLs
199 * - process html strings into plain text
200 * @param relaxedIdmatching
201 * - when true, ID matches to compound sequence IDs are allowed
202 * @return true if features were added
204 public boolean parse(AlignmentI align, Map colours, Map featureLink,
205 boolean removeHTML, boolean relaxedIdmatching)
211 SequenceI seq = null;
213 * keep track of any sequences we try to create from the data if it is a
216 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
217 String type, desc, token = null;
219 int index, start, end;
223 String featureGroup = null, groupLink = null;
224 Map typeLink = new Hashtable();
226 * when true, assume GFF style features rather than Jalview style.
228 boolean GFFFile = true;
229 Map<String, String> gffProps = new HashMap<String, String>();
230 while ((line = nextLine()) != null)
232 // skip comments/process pragmas
233 if (line.startsWith("#"))
235 if (line.startsWith("##"))
237 // possibly GFF2/3 version and metadata header
238 processGffPragma(line, gffProps, align, newseqs);
244 st = new StringTokenizer(line, "\t");
245 if (st.countTokens() == 1)
247 if (line.trim().equalsIgnoreCase("GFF"))
249 // Start parsing file as if it might be GFF again.
254 if (st.countTokens() > 1 && st.countTokens() < 4)
257 type = st.nextToken();
258 if (type.equalsIgnoreCase("startgroup"))
260 featureGroup = st.nextToken();
261 if (st.hasMoreElements())
263 groupLink = st.nextToken();
264 featureLink.put(featureGroup, groupLink);
267 else if (type.equalsIgnoreCase("endgroup"))
269 // We should check whether this is the current group,
270 // but at present theres no way of showing more than 1 group
277 Object colour = null;
278 String colscheme = st.nextToken();
279 if (colscheme.indexOf("|") > -1
280 || colscheme.trim().equalsIgnoreCase("label"))
282 // Parse '|' separated graduated colourscheme fields:
283 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
284 // can either provide 'label' only, first is optional, next two
285 // colors are required (but may be
286 // left blank), next is optional, nxt two min/max are required.
287 // first is either 'label'
288 // first/second and third are both hexadecimal or word equivalent
290 // next two are values parsed as floats.
291 // fifth is either 'above','below', or 'none'.
292 // sixth is a float value and only required when fifth is either
293 // 'above' or 'below'.
294 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
297 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
298 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
299 boolean labelCol = false;
301 String mincol = gcol.nextToken();
305 .println("Expected either 'label' or a colour specification in the line: "
309 String maxcol = null;
310 if (mincol.toLowerCase().indexOf("label") == 0)
313 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
315 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
317 String abso = null, minval, maxval;
320 // at least four more tokens
321 if (mincol.equals("|"))
327 gcol.nextToken(); // skip next '|'
329 // continue parsing rest of line
330 maxcol = gcol.nextToken();
331 if (maxcol.equals("|"))
337 gcol.nextToken(); // skip next '|'
339 abso = gcol.nextToken();
340 gcol.nextToken(); // skip next '|'
341 if (abso.toLowerCase().indexOf("abso") != 0)
348 minval = gcol.nextToken();
349 gcol.nextToken(); // skip next '|'
351 maxval = gcol.nextToken();
352 if (gcol.hasMoreTokens())
354 gcol.nextToken(); // skip next '|'
358 if (minval.length() > 0)
360 min = new Float(minval).floatValue();
362 } catch (Exception e)
365 .println("Couldn't parse the minimum value for graduated colour for type ("
367 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
372 if (maxval.length() > 0)
374 max = new Float(maxval).floatValue();
376 } catch (Exception e)
379 .println("Couldn't parse the maximum value for graduated colour for type ("
386 // add in some dummy min/max colours for the label-only
393 colour = new jalview.schemes.GraduatedColor(
394 new UserColourScheme(mincol).findColour('A'),
395 new UserColourScheme(maxcol).findColour('A'), min,
397 } catch (Exception e)
400 .println("Couldn't parse the graduated colour scheme ("
406 ((jalview.schemes.GraduatedColor) colour)
407 .setColourByLabel(labelCol);
408 ((jalview.schemes.GraduatedColor) colour)
409 .setAutoScaled(abso == null);
410 // add in any additional parameters
411 String ttype = null, tval = null;
412 if (gcol.hasMoreTokens())
414 // threshold type and possibly a threshold value
415 ttype = gcol.nextToken();
416 if (ttype.toLowerCase().startsWith("below"))
418 ((jalview.schemes.GraduatedColor) colour)
419 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
421 else if (ttype.toLowerCase().startsWith("above"))
423 ((jalview.schemes.GraduatedColor) colour)
424 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
428 ((jalview.schemes.GraduatedColor) colour)
429 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
430 if (!ttype.toLowerCase().startsWith("no"))
433 .println("Ignoring unrecognised threshold type : "
438 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
443 tval = gcol.nextToken();
444 ((jalview.schemes.GraduatedColor) colour)
445 .setThresh(new Float(tval).floatValue());
446 } catch (Exception e)
449 .println("Couldn't parse threshold value as a float: ("
454 // parse the thresh-is-min token ?
455 if (gcol.hasMoreTokens())
458 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
459 while (gcol.hasMoreTokens())
461 System.err.println("|" + gcol.nextToken());
463 System.err.println("\n");
469 UserColourScheme ucs = new UserColourScheme(colscheme);
470 colour = ucs.findColour('A');
474 colours.put(type, colour);
476 if (st.hasMoreElements())
478 String link = st.nextToken();
479 typeLink.put(type, link);
480 if (featureLink == null)
482 featureLink = new Hashtable();
484 featureLink.put(type, link);
490 while (st.hasMoreElements())
495 // Still possible this is an old Jalview file,
496 // which does not have type colours at the beginning
497 seqId = token = st.nextToken();
498 seq = findName(align, seqId, relaxedIdmatching, newseqs);
501 desc = st.nextToken();
503 if (doGffSource && desc.indexOf(' ') == -1)
505 // could also be a source term rather than description line
506 group = new String(desc);
508 type = st.nextToken();
511 String stt = st.nextToken();
512 if (stt.length() == 0 || stt.equals("-"))
518 start = Integer.parseInt(stt);
520 } catch (NumberFormatException ex)
526 String stt = st.nextToken();
527 if (stt.length() == 0 || stt.equals("-"))
533 end = Integer.parseInt(stt);
535 } catch (NumberFormatException ex)
539 // TODO: decide if non positional feature assertion for input data
540 // where end==0 is generally valid
543 // treat as non-positional feature, regardless.
548 score = new Float(st.nextToken()).floatValue();
549 } catch (NumberFormatException ex)
554 sf = new SequenceFeature(type, desc, start, end, score, group);
558 sf.setValue("STRAND", st.nextToken());
559 sf.setValue("FRAME", st.nextToken());
560 } catch (Exception ex)
564 if (st.hasMoreTokens())
566 StringBuffer attributes = new StringBuffer();
568 while (st.hasMoreTokens())
570 attributes.append((sep ? "\t" : "") + st.nextElement());
573 // TODO validate and split GFF2 attributes field ? parse out
574 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
575 // sf.setValue(attrib, val);
576 sf.setValue("ATTRIBUTES", attributes.toString());
579 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
582 // check whether we should add the sequence feature to any other
583 // sequences in the alignment with the same or similar
584 while ((seq = align.findName(seq, seqId, true)) != null)
586 seq.addSequenceFeature(new SequenceFeature(sf));
593 if (GFFFile && seq == null)
599 desc = st.nextToken();
601 if (!st.hasMoreTokens())
604 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
605 // in all probability, this isn't a file we understand, so bail
610 token = st.nextToken();
612 if (!token.equals("ID_NOT_SPECIFIED"))
614 seq = findName(align, seqId = token, relaxedIdmatching, null);
622 index = Integer.parseInt(st.nextToken());
623 seq = align.getSequenceAt(index);
624 } catch (NumberFormatException ex)
632 System.out.println("Sequence not found: " + line);
636 start = Integer.parseInt(st.nextToken());
637 end = Integer.parseInt(st.nextToken());
639 type = st.nextToken();
641 if (!colours.containsKey(type))
643 // Probably the old style groups file
644 UserColourScheme ucs = new UserColourScheme(type);
645 colours.put(type, ucs.findColour('A'));
647 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
648 if (st.hasMoreTokens())
652 score = new Float(st.nextToken()).floatValue();
653 // update colourgradient bounds if allowed to
654 } catch (NumberFormatException ex)
660 if (groupLink != null && removeHTML)
662 sf.addLink(groupLink);
663 sf.description += "%LINK%";
665 if (typeLink.containsKey(type) && removeHTML)
667 sf.addLink(typeLink.get(type).toString());
668 sf.description += "%LINK%";
671 parseDescriptionHTML(sf, removeHTML);
673 seq.addSequenceFeature(sf);
676 && (seq = align.findName(seq, seqId, false)) != null)
678 seq.addSequenceFeature(new SequenceFeature(sf));
680 // If we got here, its not a GFFFile
685 } catch (Exception ex)
687 // should report somewhere useful for UI if necessary
688 warningMessage = ((warningMessage == null) ? "" : warningMessage)
689 + "Parsing error at\n" + line;
690 System.out.println("Error parsing feature file: " + ex + "\n" + line);
691 ex.printStackTrace(System.err);
699 private enum GffPragmas
701 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
704 private static Map<String, GffPragmas> GFFPRAGMA;
707 GFFPRAGMA = new HashMap<String, GffPragmas>();
708 GFFPRAGMA.put("gff-version", GffPragmas.gff_version);
709 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
710 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
711 GFFPRAGMA.put("#", GffPragmas.hash);
712 GFFPRAGMA.put("fasta", GffPragmas.fasta);
713 GFFPRAGMA.put("species-build", GffPragmas.species_build);
714 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
715 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
718 private void processGffPragma(String line, Map<String, String> gffProps,
719 AlignmentI align, ArrayList<SequenceI> newseqs)
722 // line starts with ##
723 int spacepos = line.indexOf(' ');
724 String pragma = spacepos == -1 ? line.substring(2).trim() : line
725 .substring(2, spacepos);
726 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
727 if (gffpragma == null)
736 gffversion = Integer.parseInt(line.substring(spacepos + 1));
742 case feature_ontology:
743 // resolve against specific feature ontology
745 case attribute_ontology:
746 // resolve against specific attribute ontology
748 case source_ontology:
749 // resolve against specific source ontology
752 // resolve against specific NCBI taxon version
755 // close off any open feature hierarchies
758 // process the rest of the file as a fasta file and replace any dummy
760 process_as_fasta(align, newseqs);
764 System.err.println("Ignoring unknown pragma:\n" + line);
768 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
774 } catch (IOException q)
777 FastaFile parser = new FastaFile(this);
778 List<SequenceI> includedseqs = parser.getSeqs();
779 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
780 // iterate over includedseqs, and replacing matching ones with newseqs
781 // sequences. Generic iterator not used here because we modify includedseqs
783 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
785 // search for any dummy seqs that this sequence can be used to update
786 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
787 if (dummyseq != null)
789 // dummyseq was created so it could be annotated and referred to in
790 // alignments/codon mappings
792 SequenceI mseq = includedseqs.get(p);
793 // mseq is the 'template' imported from the FASTA file which we'll use
794 // to coomplete dummyseq
795 if (dummyseq instanceof SequenceDummy)
797 // probably have the pattern wrong
798 // idea is that a flyweight proxy for a sequence ID can be created for
799 // 1. stable reference creation
800 // 2. addition of annotation
801 // 3. future replacement by a real sequence
802 // current pattern is to create SequenceDummy objects - a convenience
803 // constructor for a Sequence.
804 // problem is that when promoted to a real sequence, all references
806 // to be updated somehow.
807 ((SequenceDummy) dummyseq).become(mseq);
808 includedseqs.set(p, dummyseq); // template is no longer needed
812 // finally add sequences to the dataset
813 for (SequenceI seq : includedseqs)
815 align.addSequence(seq);
820 * take a sequence feature and examine its attributes to decide how it should
821 * be added to a sequence
824 * - the destination sequence constructed or discovered in the
827 * - the base feature with ATTRIBUTES property containing any
828 * additional attributes
830 * - true if we are processing a GFF annotation file
831 * @return true if sf was actually added to the sequence, false if it was
832 * processed in another way
834 public boolean processOrAddSeqFeature(AlignmentI align,
835 List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
836 boolean gFFFile, boolean relaxedIdMatching)
838 String attr = (String) sf.getValue("ATTRIBUTES");
840 if (gFFFile && attr != null)
844 for (String attset : attr.split("\t"))
846 if (attset == null || attset.trim().length() == 0)
851 Map<String, List<String>> set = new HashMap<String, List<String>>();
852 // normally, only expect one column - 9 - in this field
853 // the attributes (Gff3) or groups (gff2) field
854 for (String pair : attset.trim().split(";"))
857 if (pair.length() == 0)
862 // expect either space seperated (gff2) or '=' separated (gff3)
863 // key/value pairs here
865 int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
866 String key = null, value = null;
868 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
870 key = pair.substring(0, sppos);
871 value = pair.substring(sppos + 1);
875 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
877 key = pair.substring(0, eqpos);
878 value = pair.substring(eqpos + 1);
887 List<String> vals = set.get(key);
890 vals = new ArrayList<String>();
895 vals.add(value.trim());
901 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
902 relaxedIdMatching); // process decides if
903 // feature is actually
905 } catch (InvalidGFF3FieldException ivfe)
907 System.err.println(ivfe);
913 seq.addSequenceFeature(sf);
918 public class InvalidGFF3FieldException extends Exception
922 public InvalidGFF3FieldException(String field,
923 Map<String, List<String>> set, String message)
925 super(message + " (Field was " + field + " and value was "
926 + set.get(field).toString());
928 this.value = set.get(field).toString();
934 * take a set of keys for a feature and interpret them
942 public boolean processGffKey(Map<String, List<String>> set, int nattr,
943 SequenceI seq, SequenceFeature sf, AlignmentI align,
944 List<SequenceI> newseqs, boolean relaxedIdMatching)
945 throws InvalidGFF3FieldException
948 // decide how to interpret according to type
949 if (sf.getType().equals("similarity"))
951 int strand = sf.getStrand();
952 // exonerate cdna/protein map
954 List<SequenceI> querySeq = findNames(align, newseqs,
955 relaxedIdMatching, set.get(attr = "Query"));
956 if (querySeq == null || querySeq.size() != 1)
958 throw new InvalidGFF3FieldException(attr, set,
959 "Expecting exactly one sequence in Query field (got "
960 + set.get(attr) + ")");
962 if (set.containsKey(attr = "Align"))
964 // process the align maps and create cdna/protein maps
965 // ideally, the query sequences are in the alignment, but maybe not...
967 AlignedCodonFrame alco = new AlignedCodonFrame();
968 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
971 // add codon mapping, and hope!
972 alco.addMap(seq, querySeq.get(0), codonmapping);
973 align.addCodonFrame(alco);
974 // everything that's needed to be done is done
975 // no features to create here !
983 private MapList constructCodonMappingFromAlign(
984 Map<String, List<String>> set, String attr, int strand)
985 throws InvalidGFF3FieldException
989 throw new InvalidGFF3FieldException(attr, set,
990 "Invalid strand for a codon mapping (cannot be 0)");
992 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
993 int lastppos = 0, lastpframe = 0;
994 for (String range : set.get(attr))
996 List<Integer> ints = new ArrayList<Integer>();
997 StringTokenizer st = new StringTokenizer(range, " ");
998 while (st.hasMoreTokens())
1000 String num = st.nextToken();
1003 ints.add(new Integer(num));
1004 } catch (NumberFormatException nfe)
1006 throw new InvalidGFF3FieldException(attr, set,
1007 "Invalid number in field " + num);
1010 // Align positionInRef positionInQuery LengthInRef
1011 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1012 // 3652 - . alignment_id 0 ;
1013 // Query DDB_G0269124
1014 // Align 11270 143 120
1015 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1016 // dna in strand direction
1017 // Align 11150 187 282
1018 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1019 // dna in strand direction
1021 // Align 10865 281 888
1022 // Align 9977 578 1068
1023 // Align 8909 935 375
1025 if (ints.size() != 3)
1027 throw new InvalidGFF3FieldException(attr, set,
1028 "Invalid number of fields for this attribute ("
1029 + ints.size() + ")");
1031 fromrange.add(new Integer(ints.get(0).intValue()));
1032 fromrange.add(new Integer(ints.get(0).intValue() + strand
1033 * ints.get(2).intValue()));
1034 // how are intron/exon boundaries that do not align in codons
1036 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1038 // extend existing to map
1039 lastppos += ints.get(2) / 3;
1040 lastpframe = ints.get(2) % 3;
1041 torange.set(torange.size() - 1, new Integer(lastppos));
1046 torange.add(ints.get(1));
1047 lastppos = ints.get(1) + ints.get(2) / 3;
1048 lastpframe = ints.get(2) % 3;
1049 torange.add(new Integer(lastppos));
1052 // from and to ranges must end up being a series of start/end intervals
1053 if (fromrange.size() % 2 == 1)
1055 throw new InvalidGFF3FieldException(attr, set,
1056 "Couldn't parse the DNA alignment range correctly");
1058 if (torange.size() % 2 == 1)
1060 throw new InvalidGFF3FieldException(attr, set,
1061 "Couldn't parse the protein alignment range correctly");
1063 // finally, build the map
1064 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1067 for (Integer ip : fromrange)
1069 frommap[p++] = ip.intValue();
1072 for (Integer ip : torange)
1074 tomap[p++] = ip.intValue();
1077 return new MapList(frommap, tomap, 3, 1);
1080 private List<SequenceI> findNames(AlignmentI align,
1081 List<SequenceI> newseqs, boolean relaxedIdMatching,
1084 List<SequenceI> found = new ArrayList<SequenceI>();
1085 for (String seqId : list)
1087 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1096 private AlignmentI lastmatchedAl = null;
1098 private SequenceIdMatcher matcher = null;
1101 * clear any temporary handles used to speed up ID matching
1103 private void resetMatcher()
1105 lastmatchedAl = null;
1109 private SequenceI findName(AlignmentI align, String seqId,
1110 boolean relaxedIdMatching, List<SequenceI> newseqs)
1112 SequenceI match = null;
1113 if (relaxedIdMatching)
1115 if (lastmatchedAl != align)
1117 matcher = new SequenceIdMatcher(
1118 (lastmatchedAl = align).getSequencesArray());
1119 if (newseqs != null)
1121 matcher.addAll(newseqs);
1124 match = matcher.findIdMatch(seqId);
1128 match = align.findName(seqId, true);
1129 if (match == null && newseqs != null)
1131 for (SequenceI m : newseqs)
1133 if (seqId.equals(m.getName()))
1141 if (match == null && newseqs != null)
1143 match = new SequenceDummy(seqId);
1144 if (relaxedIdMatching)
1146 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1148 // add dummy sequence to the newseqs list
1154 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1156 if (sf.getDescription() == null)
1160 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1161 sf.getDescription(), removeHTML, newline);
1163 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1165 for (String link : parsed.getLinks())
1173 * generate a features file for seqs includes non-pos features by default.
1176 * source of sequence features
1178 * hash of feature types and colours
1179 * @return features file contents
1181 public String printJalviewFormat(SequenceI[] seqs,
1182 Map<String, Object> visible)
1184 return printJalviewFormat(seqs, visible, true, true);
1188 * generate a features file for seqs with colours from visible (if any)
1191 * source of features
1193 * hash of Colours for each feature type
1195 * when true only feature types in 'visible' will be output
1197 * indicates if non-positional features should be output (regardless
1199 * @return features file contents
1201 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1202 boolean visOnly, boolean nonpos)
1204 StringBuffer out = new StringBuffer();
1205 SequenceFeature[] next;
1206 boolean featuresGen = false;
1207 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1209 // no point continuing.
1210 return "No Features Visible";
1213 if (visible != null && visOnly)
1215 // write feature colours only if we're given them and we are generating
1217 // TODO: decide if feature links should also be written here ?
1218 Iterator en = visible.keySet().iterator();
1220 while (en.hasNext())
1222 type = en.next().toString();
1224 if (visible.get(type) instanceof GraduatedColor)
1226 GraduatedColor gc = (GraduatedColor) visible.get(type);
1227 color = (gc.isColourByLabel() ? "label|" : "")
1228 + Format.getHexString(gc.getMinColor()) + "|"
1229 + Format.getHexString(gc.getMaxColor())
1230 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1231 + gc.getMax() + "|";
1232 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1234 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1240 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1242 System.err.println("WARNING: Unsupported threshold type ("
1243 + gc.getThreshType() + ") : Assuming 'above'");
1248 color += "|" + gc.getThresh();
1255 else if (visible.get(type) instanceof java.awt.Color)
1257 color = Format.getHexString((java.awt.Color) visible.get(type));
1261 // legacy support for integer objects containing colour triplet values
1262 color = Format.getHexString(new java.awt.Color(Integer
1263 .parseInt(visible.get(type).toString())));
1268 out.append(newline);
1271 // Work out which groups are both present and visible
1272 Vector groups = new Vector();
1274 boolean isnonpos = false;
1276 for (int i = 0; i < seqs.length; i++)
1278 next = seqs[i].getSequenceFeatures();
1281 for (int j = 0; j < next.length; j++)
1283 isnonpos = next[j].begin == 0 && next[j].end == 0;
1284 if ((!nonpos && isnonpos)
1285 || (!isnonpos && visOnly && !visible
1286 .containsKey(next[j].type)))
1291 if (next[j].featureGroup != null
1292 && !groups.contains(next[j].featureGroup))
1294 groups.addElement(next[j].featureGroup);
1300 String group = null;
1304 if (groups.size() > 0 && groupIndex < groups.size())
1306 group = groups.elementAt(groupIndex).toString();
1307 out.append(newline);
1308 out.append("STARTGROUP\t");
1310 out.append(newline);
1317 for (int i = 0; i < seqs.length; i++)
1319 next = seqs[i].getSequenceFeatures();
1322 for (int j = 0; j < next.length; j++)
1324 isnonpos = next[j].begin == 0 && next[j].end == 0;
1325 if ((!nonpos && isnonpos)
1326 || (!isnonpos && visOnly && !visible
1327 .containsKey(next[j].type)))
1329 // skip if feature is nonpos and we ignore them or if we only
1330 // output visible and it isn't non-pos and it's not visible
1335 && (next[j].featureGroup == null || !next[j].featureGroup
1341 if (group == null && next[j].featureGroup != null)
1345 // we have features to output
1347 if (next[j].description == null
1348 || next[j].description.equals(""))
1350 out.append(next[j].type + "\t");
1354 if (next[j].links != null
1355 && next[j].getDescription().indexOf("<html>") == -1)
1357 out.append("<html>");
1360 out.append(next[j].description + " ");
1361 if (next[j].links != null)
1363 for (int l = 0; l < next[j].links.size(); l++)
1365 String label = next[j].links.elementAt(l).toString();
1366 String href = label.substring(label.indexOf("|") + 1);
1367 label = label.substring(0, label.indexOf("|"));
1369 if (next[j].description.indexOf(href) == -1)
1371 out.append("<a href=\"" + href + "\">" + label + "</a>");
1375 if (next[j].getDescription().indexOf("</html>") == -1)
1377 out.append("</html>");
1383 out.append(seqs[i].getName());
1384 out.append("\t-1\t");
1385 out.append(next[j].begin);
1387 out.append(next[j].end);
1389 out.append(next[j].type);
1390 if (!Float.isNaN(next[j].score))
1393 out.append(next[j].score);
1395 out.append(newline);
1402 out.append("ENDGROUP\t");
1404 out.append(newline);
1412 } while (groupIndex < groups.size() + 1);
1416 return "No Features Visible";
1419 return out.toString();
1423 * generate a gff file for sequence features includes non-pos features by
1430 public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1432 return printGFFFormat(seqs, visible, true, true);
1435 public String printGFFFormat(SequenceI[] seqs,
1436 Map<String, Object> visible, boolean visOnly, boolean nonpos)
1438 StringBuffer out = new StringBuffer();
1439 SequenceFeature[] next;
1442 for (int i = 0; i < seqs.length; i++)
1444 if (seqs[i].getSequenceFeatures() != null)
1446 next = seqs[i].getSequenceFeatures();
1447 for (int j = 0; j < next.length; j++)
1449 isnonpos = next[j].begin == 0 && next[j].end == 0;
1450 if ((!nonpos && isnonpos)
1451 || (!isnonpos && visOnly && !visible
1452 .containsKey(next[j].type)))
1457 source = next[j].featureGroup;
1460 source = next[j].getDescription();
1463 out.append(seqs[i].getName());
1467 out.append(next[j].type);
1469 out.append(next[j].begin);
1471 out.append(next[j].end);
1473 out.append(next[j].score);
1476 if (next[j].getValue("STRAND") != null)
1478 out.append(next[j].getValue("STRAND"));
1486 if (next[j].getValue("FRAME") != null)
1488 out.append(next[j].getValue("FRAME"));
1494 // TODO: verify/check GFF - should there be a /t here before attribute
1497 if (next[j].getValue("ATTRIBUTES") != null)
1499 out.append(next[j].getValue("ATTRIBUTES"));
1502 out.append(newline);
1508 return out.toString();
1512 * this is only for the benefit of object polymorphism - method does nothing.
1521 * this is only for the benefit of object polymorphism - method does nothing.
1523 * @return error message
1526 public String print()
1528 return "USE printGFFFormat() or printJalviewFormat()";