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.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceDummy;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.schemes.AnnotationColourGradient;
31 import jalview.schemes.GraduatedColor;
32 import jalview.schemes.UserColourScheme;
33 import jalview.util.Format;
34 import jalview.util.MapList;
36 import java.io.IOException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashMap;
40 import java.util.Hashtable;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
48 * Parse and create Jalview Features files Detects GFF format features files and
49 * parses. Does not implement standard print() - call specific printFeatures or
50 * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
51 * for the features annotation - this normally works on an exact match.
56 public class FeaturesFile extends AlignFile
59 * work around for GFF interpretation bug where source string becomes
60 * description rather than a group
62 private boolean doGffSource = true;
64 private int gffversion;
67 * Creates a new FeaturesFile object.
78 public FeaturesFile(String inFile, String type) throws IOException
87 public FeaturesFile(FileParse source) throws IOException
93 * @param parseImmediately
97 public FeaturesFile(boolean parseImmediately, FileParse source)
100 super(parseImmediately, source);
104 * @param parseImmediately
107 * @throws IOException
109 public FeaturesFile(boolean parseImmediately, String inFile, String type)
112 super(parseImmediately, inFile, type);
116 * Parse GFF or sequence features file using case-independent matching,
120 * - alignment/dataset containing sequences that are to be annotated
122 * - hashtable to store feature colour definitions
124 * - process html strings into plain text
125 * @return true if features were added
127 public boolean parse(AlignmentI align, Hashtable colours,
130 return parse(align, colours, null, removeHTML, false);
134 * Parse GFF or sequence features file optionally using case-independent
135 * matching, discarding URLs
138 * - alignment/dataset containing sequences that are to be annotated
140 * - hashtable to store feature colour definitions
142 * - process html strings into plain text
143 * @param relaxedIdmatching
144 * - when true, ID matches to compound sequence IDs are allowed
145 * @return true if features were added
147 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
148 boolean relaxedIdMatching)
150 return parse(align, colours, null, removeHTML, relaxedIdMatching);
154 * Parse GFF or sequence features file optionally using case-independent
158 * - alignment/dataset containing sequences that are to be annotated
160 * - hashtable to store feature colour definitions
162 * - hashtable to store associated URLs
164 * - process html strings into plain text
165 * @return true if features were added
167 public boolean parse(AlignmentI align, Map colours, Map featureLink,
170 return parse(align, colours, featureLink, removeHTML, false);
174 public void addAnnotations(Alignment al)
176 super.addAnnotations(al);
180 public void addProperties(Alignment al)
182 super.addProperties(al);
186 public void addSeqGroups(AlignmentI al)
188 super.addSeqGroups(al);
192 * Parse GFF or sequence features file
195 * - alignment/dataset containing sequences that are to be annotated
197 * - hashtable to store feature colour definitions
199 * - hashtable to store associated URLs
201 * - process html strings into plain text
202 * @param relaxedIdmatching
203 * - when true, ID matches to compound sequence IDs are allowed
204 * @return true if features were added
206 public boolean parse(AlignmentI align, Map colours, Map featureLink,
207 boolean removeHTML, boolean relaxedIdmatching)
213 SequenceI seq = null;
215 * keep track of any sequences we try to create from the data if it is a GFF3 file
217 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
218 String type, desc, token = null;
220 int index, start, end;
224 String featureGroup = null, groupLink = null;
225 Map typeLink = new Hashtable();
227 * when true, assume GFF style features rather than Jalview style.
229 boolean GFFFile = true;
230 Map<String, String> gffProps = new HashMap<String, String>();
231 while ((line = nextLine()) != null)
233 // skip comments/process pragmas
234 if (line.startsWith("#"))
236 if (line.startsWith("##"))
238 // possibly GFF2/3 version and metadata header
239 processGffPragma(line, gffProps, align, newseqs);
245 st = new StringTokenizer(line, "\t");
246 if (st.countTokens() == 1)
248 if (line.trim().equalsIgnoreCase("GFF"))
250 // Start parsing file as if it might be GFF again.
255 if (st.countTokens() > 1 && st.countTokens() < 4)
258 type = st.nextToken();
259 if (type.equalsIgnoreCase("startgroup"))
261 featureGroup = st.nextToken();
262 if (st.hasMoreElements())
264 groupLink = st.nextToken();
265 featureLink.put(featureGroup, groupLink);
268 else if (type.equalsIgnoreCase("endgroup"))
270 // We should check whether this is the current group,
271 // but at present theres no way of showing more than 1 group
278 Object colour = null;
279 String colscheme = st.nextToken();
280 if (colscheme.indexOf("|") > -1
281 || colscheme.trim().equalsIgnoreCase("label"))
283 // Parse '|' separated graduated colourscheme fields:
284 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
285 // can either provide 'label' only, first is optional, next two
286 // colors are required (but may be
287 // left blank), next is optional, nxt two min/max are required.
288 // first is either 'label'
289 // first/second and third are both hexadecimal or word equivalent
291 // next two are values parsed as floats.
292 // fifth is either 'above','below', or 'none'.
293 // sixth is a float value and only required when fifth is either
294 // 'above' or 'below'.
295 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
298 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
299 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
300 boolean labelCol = false;
302 String mincol = gcol.nextToken();
306 .println("Expected either 'label' or a colour specification in the line: "
310 String maxcol = null;
311 if (mincol.toLowerCase().indexOf("label") == 0)
314 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
316 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
318 String abso = null, minval, maxval;
321 // at least four more tokens
322 if (mincol.equals("|"))
328 gcol.nextToken(); // skip next '|'
330 // continue parsing rest of line
331 maxcol = gcol.nextToken();
332 if (maxcol.equals("|"))
338 gcol.nextToken(); // skip next '|'
340 abso = gcol.nextToken();
341 gcol.nextToken(); // skip next '|'
342 if (abso.toLowerCase().indexOf("abso") != 0)
349 minval = gcol.nextToken();
350 gcol.nextToken(); // skip next '|'
352 maxval = gcol.nextToken();
353 if (gcol.hasMoreTokens())
355 gcol.nextToken(); // skip next '|'
359 if (minval.length() > 0)
361 min = new Float(minval).floatValue();
363 } catch (Exception e)
366 .println("Couldn't parse the minimum value for graduated colour for type ("
368 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
373 if (maxval.length() > 0)
375 max = new Float(maxval).floatValue();
377 } catch (Exception e)
380 .println("Couldn't parse the maximum value for graduated colour for type ("
387 // add in some dummy min/max colours for the label-only
394 colour = new jalview.schemes.GraduatedColor(
395 new UserColourScheme(mincol).findColour('A'),
396 new UserColourScheme(maxcol).findColour('A'), min,
398 } catch (Exception e)
401 .println("Couldn't parse the graduated colour scheme ("
407 ((jalview.schemes.GraduatedColor) colour)
408 .setColourByLabel(labelCol);
409 ((jalview.schemes.GraduatedColor) colour)
410 .setAutoScaled(abso == null);
411 // add in any additional parameters
412 String ttype = null, tval = null;
413 if (gcol.hasMoreTokens())
415 // threshold type and possibly a threshold value
416 ttype = gcol.nextToken();
417 if (ttype.toLowerCase().startsWith("below"))
419 ((jalview.schemes.GraduatedColor) colour)
420 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
422 else if (ttype.toLowerCase().startsWith("above"))
424 ((jalview.schemes.GraduatedColor) colour)
425 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
429 ((jalview.schemes.GraduatedColor) colour)
430 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
431 if (!ttype.toLowerCase().startsWith("no"))
434 .println("Ignoring unrecognised threshold type : "
439 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
444 tval = gcol.nextToken();
445 ((jalview.schemes.GraduatedColor) colour)
446 .setThresh(new Float(tval).floatValue());
447 } catch (Exception e)
450 .println("Couldn't parse threshold value as a float: ("
455 // parse the thresh-is-min token ?
456 if (gcol.hasMoreTokens())
459 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
460 while (gcol.hasMoreTokens())
462 System.err.println("|" + gcol.nextToken());
464 System.err.println("\n");
470 UserColourScheme ucs = new UserColourScheme(colscheme);
471 colour = ucs.findColour('A');
475 colours.put(type, colour);
477 if (st.hasMoreElements())
479 String link = st.nextToken();
480 typeLink.put(type, link);
481 if (featureLink == null)
483 featureLink = new Hashtable();
485 featureLink.put(type, link);
491 while (st.hasMoreElements())
496 // Still possible this is an old Jalview file,
497 // which does not have type colours at the beginning
498 seqId = token = st.nextToken();
499 seq = findName(align, seqId, relaxedIdmatching, newseqs);
502 desc = st.nextToken();
504 if (doGffSource && desc.indexOf(' ') == -1)
506 // could also be a source term rather than description line
507 group = new String(desc);
509 type = st.nextToken();
512 String stt = st.nextToken();
513 if (stt.length() == 0 || stt.equals("-"))
519 start = Integer.parseInt(stt);
521 } catch (NumberFormatException ex)
527 String stt = st.nextToken();
528 if (stt.length() == 0 || stt.equals("-"))
534 end = Integer.parseInt(stt);
536 } catch (NumberFormatException ex)
540 // TODO: decide if non positional feature assertion for input data
541 // where end==0 is generally valid
544 // treat as non-positional feature, regardless.
549 score = new Float(st.nextToken()).floatValue();
550 } catch (NumberFormatException ex)
555 sf = new SequenceFeature(type, desc, start, end, score, group);
559 sf.setValue("STRAND", st.nextToken());
560 sf.setValue("FRAME", st.nextToken());
561 } catch (Exception ex)
565 if (st.hasMoreTokens())
567 StringBuffer attributes = new StringBuffer();
569 while (st.hasMoreTokens())
571 attributes.append((sep ? "\t" : "") + st.nextElement());
574 // TODO validate and split GFF2 attributes field ? parse out
575 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
576 // sf.setValue(attrib, val);
577 sf.setValue("ATTRIBUTES", attributes.toString());
580 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
583 // check whether we should add the sequence feature to any other
584 // sequences in the alignment with the same or similar
585 while ((seq = align.findName(seq, seqId, true)) != null)
587 seq.addSequenceFeature(new SequenceFeature(sf));
594 if (GFFFile && seq == null)
600 desc = st.nextToken();
602 if (!st.hasMoreTokens())
605 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
606 // in all probability, this isn't a file we understand, so bail
611 token = st.nextToken();
613 if (!token.equals("ID_NOT_SPECIFIED"))
615 seq = findName(align, seqId = token, relaxedIdmatching, null);
623 index = Integer.parseInt(st.nextToken());
624 seq = align.getSequenceAt(index);
625 } catch (NumberFormatException ex)
633 System.out.println("Sequence not found: " + line);
637 start = Integer.parseInt(st.nextToken());
638 end = Integer.parseInt(st.nextToken());
640 type = st.nextToken();
642 if (!colours.containsKey(type))
644 // Probably the old style groups file
645 UserColourScheme ucs = new UserColourScheme(type);
646 colours.put(type, ucs.findColour('A'));
648 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
649 if (st.hasMoreTokens())
653 score = new Float(st.nextToken()).floatValue();
654 // update colourgradient bounds if allowed to
655 } catch (NumberFormatException ex)
661 if (groupLink != null && removeHTML)
663 sf.addLink(groupLink);
664 sf.description += "%LINK%";
666 if (typeLink.containsKey(type) && removeHTML)
668 sf.addLink(typeLink.get(type).toString());
669 sf.description += "%LINK%";
672 parseDescriptionHTML(sf, removeHTML);
674 seq.addSequenceFeature(sf);
677 && (seq = align.findName(seq, seqId, false)) != null)
679 seq.addSequenceFeature(new SequenceFeature(sf));
681 // If we got here, its not a GFFFile
686 } catch (Exception ex)
688 // should report somewhere useful for UI if necessary
689 warningMessage = ((warningMessage == null) ? "" : warningMessage)
690 + "Parsing error at\n" + line;
691 System.out.println("Error parsing feature file: " + ex + "\n" + line);
692 ex.printStackTrace(System.err);
700 private enum GffPragmas
702 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
705 private static Map<String, GffPragmas> GFFPRAGMA;
708 GFFPRAGMA = new HashMap<String, GffPragmas>();
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, List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
835 boolean gFFFile, boolean relaxedIdMatching)
837 String attr = (String) sf.getValue("ATTRIBUTES");
839 if (gFFFile && attr != null)
843 for (String attset : attr.split("\t"))
845 if (attset==null || attset.trim().length()==0)
850 Map<String, List<String>> set = new HashMap<String, List<String>>();
851 // normally, only expect one column - 9 - in this field
852 // the attributes (Gff3) or groups (gff2) field
853 for (String pair : attset.trim().split(";"))
856 if (pair.length() == 0)
861 // expect either space seperated (gff2) or '=' separated (gff3)
862 // key/value pairs here
864 int eqpos = pair.indexOf('='),sppos = pair.indexOf(' ');
865 String key = null, value = null;
867 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
869 key = pair.substring(0, sppos);
870 value = pair.substring(sppos + 1);
872 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
874 key = pair.substring(0, eqpos);
875 value = pair.substring(eqpos + 1);
883 List<String> vals = set.get(key);
886 vals = new ArrayList<String>();
891 vals.add(value.trim());
897 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
898 relaxedIdMatching); // process decides if
899 // feature is actually
901 } catch (InvalidGFF3FieldException ivfe)
903 System.err.println(ivfe);
909 seq.addSequenceFeature(sf);
914 public class InvalidGFF3FieldException extends Exception
918 public InvalidGFF3FieldException(String field,
919 Map<String, List<String>> set, String message)
921 super(message + " (Field was " + field + " and value was "
922 + set.get(field).toString());
924 this.value = set.get(field).toString();
930 * take a set of keys for a feature and interpret them
938 public boolean processGffKey(Map<String, List<String>> set, int nattr,
939 SequenceI seq, SequenceFeature sf, AlignmentI align,
940 List<SequenceI> newseqs, boolean relaxedIdMatching)
941 throws InvalidGFF3FieldException
944 // decide how to interpret according to type
945 if (sf.getType().equals("similarity"))
947 int strand = sf.getStrand();
948 // exonerate cdna/protein map
950 List<SequenceI> querySeq = findNames(align, newseqs,
951 relaxedIdMatching, set.get(attr="Query"));
952 if (querySeq==null || querySeq.size()!=1)
954 throw new InvalidGFF3FieldException( attr, set,
955 "Expecting exactly one sequence in Query field (got "
956 + set.get(attr) + ")");
958 if (set.containsKey(attr="Align"))
960 // process the align maps and create cdna/protein maps
961 // ideally, the query sequences are in the alignment, but maybe not...
963 AlignedCodonFrame alco = new AlignedCodonFrame();
964 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
967 // add codon mapping, and hope!
968 alco.addMap(seq, querySeq.get(0), codonmapping);
969 align.addCodonFrame(alco);
970 // everything that's needed to be done is done
971 // no features to create here !
979 private MapList constructCodonMappingFromAlign(
980 Map<String, List<String>> set,
981 String attr, int strand) throws InvalidGFF3FieldException
985 throw new InvalidGFF3FieldException(attr, set,
986 "Invalid strand for a codon mapping (cannot be 0)");
988 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
989 int lastppos = 0, lastpframe = 0;
990 for (String range : set.get(attr))
992 List<Integer> ints = new ArrayList<Integer>();
993 StringTokenizer st = new StringTokenizer(range, " ");
994 while (st.hasMoreTokens())
996 String num = st.nextToken();
999 ints.add(new Integer(num));
1000 } catch (NumberFormatException nfe)
1002 throw new InvalidGFF3FieldException(attr, set,
1003 "Invalid number in field " + num);
1006 // Align positionInRef positionInQuery LengthInRef
1007 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1008 // 3652 - . alignment_id 0 ;
1009 // Query DDB_G0269124
1010 // Align 11270 143 120
1011 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1012 // dna in strand direction
1013 // Align 11150 187 282
1014 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1015 // dna in strand direction
1017 // Align 10865 281 888
1018 // Align 9977 578 1068
1019 // Align 8909 935 375
1021 if (ints.size() != 3)
1023 throw new InvalidGFF3FieldException(attr, set,
1024 "Invalid number of fields for this attribute ("
1025 + ints.size() + ")");
1027 fromrange.add(new Integer(ints.get(0).intValue()));
1028 fromrange.add(new Integer(ints.get(0).intValue() + strand
1029 * ints.get(2).intValue()));
1030 // how are intron/exon boundaries that do not align in codons
1032 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1034 // extend existing to map
1035 lastppos += ints.get(2) / 3;
1036 lastpframe = ints.get(2) % 3;
1037 torange.set(torange.size() - 1, new Integer(lastppos));
1042 torange.add(ints.get(1));
1043 lastppos = ints.get(1) + ints.get(2) / 3;
1044 lastpframe = ints.get(2) % 3;
1045 torange.add(new Integer(lastppos));
1048 // from and to ranges must end up being a series of start/end intervals
1049 if (fromrange.size() % 2 == 1)
1051 throw new InvalidGFF3FieldException(attr, set,
1052 "Couldn't parse the DNA alignment range correctly");
1054 if (torange.size() % 2 == 1)
1056 throw new InvalidGFF3FieldException(attr, set,
1057 "Couldn't parse the protein alignment range correctly");
1059 // finally, build the map
1060 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1063 for (Integer ip : fromrange)
1065 frommap[p++] = ip.intValue();
1068 for (Integer ip : torange)
1070 tomap[p++] = ip.intValue();
1073 return new MapList(frommap, tomap, 3, 1);
1076 private List<SequenceI> findNames(AlignmentI align,
1077 List<SequenceI> newseqs, boolean relaxedIdMatching,
1080 List<SequenceI> found = new ArrayList<SequenceI>();
1081 for (String seqId : list)
1083 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1092 private AlignmentI lastmatchedAl = null;
1094 private SequenceIdMatcher matcher = null;
1097 * clear any temporary handles used to speed up ID matching
1099 private void resetMatcher()
1101 lastmatchedAl = null;
1105 private SequenceI findName(AlignmentI align, String seqId,
1106 boolean relaxedIdMatching, List<SequenceI> newseqs)
1108 SequenceI match = null;
1109 if (relaxedIdMatching)
1111 if (lastmatchedAl != align)
1113 matcher = new SequenceIdMatcher(
1114 (lastmatchedAl = align).getSequencesArray());
1115 if (newseqs != null)
1117 matcher.addAll(newseqs);
1120 match = matcher.findIdMatch(seqId);
1124 match = align.findName(seqId, true);
1125 if (match == null && newseqs != null)
1127 for (SequenceI m : newseqs)
1129 if (seqId.equals(m.getName()))
1137 if (match==null && newseqs!=null)
1139 match = new SequenceDummy(seqId);
1140 if (relaxedIdMatching)
1142 matcher.addAll(Arrays.asList(new SequenceI[]
1145 // add dummy sequence to the newseqs list
1150 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1152 if (sf.getDescription() == null)
1156 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1157 sf.getDescription(), removeHTML, newline);
1159 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1161 for (String link : parsed.getLinks())
1169 * generate a features file for seqs includes non-pos features by default.
1172 * source of sequence features
1174 * hash of feature types and colours
1175 * @return features file contents
1177 public String printJalviewFormat(SequenceI[] seqs, Map<String,Object> visible)
1179 return printJalviewFormat(seqs, visible, true, true);
1183 * generate a features file for seqs with colours from visible (if any)
1186 * source of features
1188 * hash of Colours for each feature type
1190 * when true only feature types in 'visible' will be output
1192 * indicates if non-positional features should be output (regardless
1194 * @return features file contents
1196 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1197 boolean visOnly, boolean nonpos)
1199 StringBuffer out = new StringBuffer();
1200 SequenceFeature[] next;
1201 boolean featuresGen = false;
1202 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1204 // no point continuing.
1205 return "No Features Visible";
1208 if (visible != null && visOnly)
1210 // write feature colours only if we're given them and we are generating
1212 // TODO: decide if feature links should also be written here ?
1213 Iterator en = visible.keySet().iterator();
1215 while (en.hasNext())
1217 type = en.next().toString();
1219 if (visible.get(type) instanceof GraduatedColor)
1221 GraduatedColor gc = (GraduatedColor) visible.get(type);
1222 color = (gc.isColourByLabel() ? "label|" : "")
1223 + Format.getHexString(gc.getMinColor()) + "|"
1224 + Format.getHexString(gc.getMaxColor())
1225 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1226 + gc.getMax() + "|";
1227 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1229 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1235 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1237 System.err.println("WARNING: Unsupported threshold type ("
1238 + gc.getThreshType() + ") : Assuming 'above'");
1243 color += "|" + gc.getThresh();
1250 else if (visible.get(type) instanceof java.awt.Color)
1252 color = Format.getHexString((java.awt.Color) visible.get(type));
1256 // legacy support for integer objects containing colour triplet values
1257 color = Format.getHexString(new java.awt.Color(Integer
1258 .parseInt(visible.get(type).toString())));
1263 out.append(newline);
1266 // Work out which groups are both present and visible
1267 Vector groups = new Vector();
1269 boolean isnonpos = false;
1271 for (int i = 0; i < seqs.length; i++)
1273 next = seqs[i].getSequenceFeatures();
1276 for (int j = 0; j < next.length; j++)
1278 isnonpos = next[j].begin == 0 && next[j].end == 0;
1279 if ((!nonpos && isnonpos)
1280 || (!isnonpos && visOnly && !visible
1281 .containsKey(next[j].type)))
1286 if (next[j].featureGroup != null
1287 && !groups.contains(next[j].featureGroup))
1289 groups.addElement(next[j].featureGroup);
1295 String group = null;
1299 if (groups.size() > 0 && groupIndex < groups.size())
1301 group = groups.elementAt(groupIndex).toString();
1302 out.append(newline);
1303 out.append("STARTGROUP\t");
1305 out.append(newline);
1312 for (int i = 0; i < seqs.length; i++)
1314 next = seqs[i].getSequenceFeatures();
1317 for (int j = 0; j < next.length; j++)
1319 isnonpos = next[j].begin == 0 && next[j].end == 0;
1320 if ((!nonpos && isnonpos)
1321 || (!isnonpos && visOnly && !visible
1322 .containsKey(next[j].type)))
1324 // skip if feature is nonpos and we ignore them or if we only
1325 // output visible and it isn't non-pos and it's not visible
1330 && (next[j].featureGroup == null || !next[j].featureGroup
1336 if (group == null && next[j].featureGroup != null)
1340 // we have features to output
1342 if (next[j].description == null
1343 || next[j].description.equals(""))
1345 out.append(next[j].type + "\t");
1349 if (next[j].links != null
1350 && next[j].getDescription().indexOf("<html>") == -1)
1352 out.append("<html>");
1355 out.append(next[j].description + " ");
1356 if (next[j].links != null)
1358 for (int l = 0; l < next[j].links.size(); l++)
1360 String label = next[j].links.elementAt(l).toString();
1361 String href = label.substring(label.indexOf("|") + 1);
1362 label = label.substring(0, label.indexOf("|"));
1364 if (next[j].description.indexOf(href) == -1)
1366 out.append("<a href=\"" + href + "\">" + label + "</a>");
1370 if (next[j].getDescription().indexOf("</html>") == -1)
1372 out.append("</html>");
1378 out.append(seqs[i].getName());
1379 out.append("\t-1\t");
1380 out.append(next[j].begin);
1382 out.append(next[j].end);
1384 out.append(next[j].type);
1385 if (next[j].score != Float.NaN)
1388 out.append(next[j].score);
1390 out.append(newline);
1397 out.append("ENDGROUP\t");
1399 out.append(newline);
1407 } while (groupIndex < groups.size() + 1);
1411 return "No Features Visible";
1414 return out.toString();
1418 * generate a gff file for sequence features includes non-pos features by
1425 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible)
1427 return printGFFFormat(seqs, visible, true, true);
1430 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible,
1431 boolean visOnly, boolean nonpos)
1433 StringBuffer out = new StringBuffer();
1434 SequenceFeature[] next;
1437 for (int i = 0; i < seqs.length; i++)
1439 if (seqs[i].getSequenceFeatures() != null)
1441 next = seqs[i].getSequenceFeatures();
1442 for (int j = 0; j < next.length; j++)
1444 isnonpos = next[j].begin == 0 && next[j].end == 0;
1445 if ((!nonpos && isnonpos)
1446 || (!isnonpos && visOnly && !visible
1447 .containsKey(next[j].type)))
1452 source = next[j].featureGroup;
1455 source = next[j].getDescription();
1458 out.append(seqs[i].getName());
1462 out.append(next[j].type);
1464 out.append(next[j].begin);
1466 out.append(next[j].end);
1468 out.append(next[j].score);
1471 if (next[j].getValue("STRAND") != null)
1473 out.append(next[j].getValue("STRAND"));
1481 if (next[j].getValue("FRAME") != null)
1483 out.append(next[j].getValue("FRAME"));
1489 // TODO: verify/check GFF - should there be a /t here before attribute
1492 if (next[j].getValue("ATTRIBUTES") != null)
1494 out.append(next[j].getValue("ATTRIBUTES"));
1497 out.append(newline);
1503 return out.toString();
1507 * this is only for the benefit of object polymorphism - method does nothing.
1515 * this is only for the benefit of object polymorphism - method does nothing.
1517 * @return error message
1519 public String print()
1521 return "USE printGFFFormat() or printJalviewFormat()";