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.jsdev.GenericFileAdapter;
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;
35 import jalview.util.ParseHtmlBodyAndLinks;
37 import java.io.IOException;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.Hashtable;
42 import java.util.Iterator;
43 import java.util.List;
45 import java.util.StringTokenizer;
46 import java.util.Vector;
49 * Parse and create Jalview Features files Detects GFF format features files and
50 * parses. Does not implement standard print() - call specific printFeatures or
51 * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
52 * for the features annotation - this normally works on an exact match.
57 public class FeaturesFile extends AlignFile
60 * work around for GFF interpretation bug where source string becomes
61 * description rather than a group
63 private boolean doGffSource = true;
65 private int gffversion;
68 * Creates a new FeaturesFile object.
79 public FeaturesFile(String inFile, String type) throws IOException
88 public FeaturesFile(FileParse source) throws IOException
94 * @param parseImmediately
98 public FeaturesFile(boolean parseImmediately, FileParse source)
101 super(parseImmediately, source);
105 * @param parseImmediately
108 * @throws IOException
110 public FeaturesFile(boolean parseImmediately, String inFile, String type)
113 super(parseImmediately, inFile, type);
117 * Parse GFF or sequence features file using case-independent matching,
121 * - alignment/dataset containing sequences that are to be annotated
123 * - hashtable to store feature colour definitions
125 * - process html strings into plain text
126 * @return true if features were added
128 public boolean parse(AlignmentI align, Hashtable colours,
131 return parse(align, colours, null, removeHTML, false);
135 * Parse GFF or sequence features file optionally using case-independent
136 * matching, discarding URLs
139 * - alignment/dataset containing sequences that are to be annotated
141 * - hashtable to store feature colour definitions
143 * - process html strings into plain text
144 * @param relaxedIdmatching
145 * - when true, ID matches to compound sequence IDs are allowed
146 * @return true if features were added
148 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
149 boolean relaxedIdMatching)
151 return parse(align, colours, null, removeHTML, relaxedIdMatching);
155 * Parse GFF or sequence features file optionally using case-independent
159 * - alignment/dataset containing sequences that are to be annotated
161 * - hashtable to store feature colour definitions
163 * - hashtable to store associated URLs
165 * - process html strings into plain text
166 * @return true if features were added
168 public boolean parse(AlignmentI align, Map colours, Map featureLink,
171 return parse(align, colours, featureLink, removeHTML, false);
175 public void addAnnotations(AlignmentI al)
177 // TODO Auto-generated method stub
178 super.addAnnotations(al);
182 public void addProperties(AlignmentI al)
184 // TODO Auto-generated method stub
185 super.addProperties(al);
189 public void addSeqGroups(AlignmentI al)
191 // TODO Auto-generated method stub
192 super.addSeqGroups(al);
196 * Parse GFF or sequence features file
199 * - alignment/dataset containing sequences that are to be annotated
201 * - hashtable to store feature colour definitions
203 * - hashtable to store associated URLs
205 * - process html strings into plain text
206 * @param relaxedIdmatching
207 * - when true, ID matches to compound sequence IDs are allowed
208 * @return true if features were added
210 public boolean parse(AlignmentI align, Map colours, Map featureLink,
211 boolean removeHTML, boolean relaxedIdmatching)
217 SequenceI seq = null;
219 * keep track of any sequences we try to create from the data if it is a GFF3 file
221 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
222 String type, desc, token = null;
224 int index, start, end;
228 String featureGroup = null, groupLink = null;
229 Map typeLink = new Hashtable();
231 * when true, assume GFF style features rather than Jalview style.
233 boolean GFFFile = true;
234 Map<String, String> gffProps = new HashMap<String, String>();
235 while ((line = nextLine()) != null)
237 // skip comments/process pragmas
238 if (line.startsWith("#"))
240 if (line.startsWith("##"))
242 // possibly GFF2/3 version and metadata header
243 processGffPragma(line, gffProps, align, newseqs);
249 st = new StringTokenizer(line, "\t");
250 if (st.countTokens() == 1)
252 if (line.trim().equalsIgnoreCase("GFF"))
254 // Start parsing file as if it might be GFF again.
259 if (st.countTokens() > 1 && st.countTokens() < 4)
262 type = st.nextToken();
263 if (type.equalsIgnoreCase("startgroup"))
265 featureGroup = st.nextToken();
266 if (st.hasMoreElements())
268 groupLink = st.nextToken();
269 featureLink.put(featureGroup, groupLink);
272 else if (type.equalsIgnoreCase("endgroup"))
274 // We should check whether this is the current group,
275 // but at present theres no way of showing more than 1 group
282 Object colour = null;
283 String colscheme = st.nextToken();
284 if (colscheme.indexOf("|") > -1
285 || colscheme.trim().equalsIgnoreCase("label"))
287 // Parse '|' separated graduated colourscheme fields:
288 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
289 // can either provide 'label' only, first is optional, next two
290 // colors are required (but may be
291 // left blank), next is optional, nxt two min/max are required.
292 // first is either 'label'
293 // first/second and third are both hexadecimal or word equivalent
295 // next two are values parsed as floats.
296 // fifth is either 'above','below', or 'none'.
297 // sixth is a float value and only required when fifth is either
298 // 'above' or 'below'.
299 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
302 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
303 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
304 boolean labelCol = false;
306 String mincol = gcol.nextToken();
310 .println("Expected either 'label' or a colour specification in the line: "
314 String maxcol = null;
315 if (mincol.toLowerCase().indexOf("label") == 0)
318 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
320 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
322 String abso = null, minval, maxval;
325 // at least four more tokens
326 if (mincol.equals("|"))
332 gcol.nextToken(); // skip next '|'
334 // continue parsing rest of line
335 maxcol = gcol.nextToken();
336 if (maxcol.equals("|"))
342 gcol.nextToken(); // skip next '|'
344 abso = gcol.nextToken();
345 gcol.nextToken(); // skip next '|'
346 if (abso.toLowerCase().indexOf("abso") != 0)
353 minval = gcol.nextToken();
354 gcol.nextToken(); // skip next '|'
356 maxval = gcol.nextToken();
357 if (gcol.hasMoreTokens())
359 gcol.nextToken(); // skip next '|'
363 if (minval.length() > 0)
365 min = new Float(minval).floatValue();
367 } catch (Exception e)
370 .println("Couldn't parse the minimum value for graduated colour for type ("
372 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
377 if (maxval.length() > 0)
379 max = new Float(maxval).floatValue();
381 } catch (Exception e)
384 .println("Couldn't parse the maximum value for graduated colour for type ("
391 // add in some dummy min/max colours for the label-only
398 colour = new GraduatedColor(
399 new UserColourScheme(mincol).findColour('A'),
400 new UserColourScheme(maxcol).findColour('A'), min,
402 } catch (Exception e)
405 .println("Couldn't parse the graduated colour scheme ("
411 ((GraduatedColor) colour)
412 .setColourByLabel(labelCol);
413 ((GraduatedColor) colour)
414 .setAutoScaled(abso == null);
415 // add in any additional parameters
416 String ttype = null, tval = null;
417 if (gcol.hasMoreTokens())
419 // threshold type and possibly a threshold value
420 ttype = gcol.nextToken();
421 if (ttype.toLowerCase().startsWith("below"))
423 ((GraduatedColor) colour)
424 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
426 else if (ttype.toLowerCase().startsWith("above"))
428 ((GraduatedColor) colour)
429 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
433 ((GraduatedColor) colour)
434 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
435 if (!ttype.toLowerCase().startsWith("no"))
438 .println("Ignoring unrecognised threshold type : "
443 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
448 tval = gcol.nextToken();
449 ((GraduatedColor) colour)
450 .setThresh(new Float(tval).floatValue());
451 } catch (Exception e)
454 .println("Couldn't parse threshold value as a float: ("
459 // parse the thresh-is-min token ?
460 if (gcol.hasMoreTokens())
463 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
464 while (gcol.hasMoreTokens())
466 System.err.println("|" + gcol.nextToken());
468 System.err.println("\n");
474 UserColourScheme ucs = new UserColourScheme(colscheme);
475 colour = ucs.findColour('A');
479 colours.put(type, colour);
481 if (st.hasMoreElements())
483 String link = st.nextToken();
484 typeLink.put(type, link);
485 if (featureLink == null)
487 featureLink = new Hashtable();
489 featureLink.put(type, link);
495 while (st.hasMoreElements())
500 // Still possible this is an old Jalview file,
501 // which does not have type colours at the beginning
502 seqId = token = st.nextToken();
503 seq = findName(align, seqId, relaxedIdmatching, newseqs);
506 desc = st.nextToken();
508 if (doGffSource && desc.indexOf(' ') == -1)
510 // could also be a source term rather than description line
511 group = new String(desc);
513 type = st.nextToken();
516 String stt = st.nextToken();
517 if (stt.length() == 0 || stt.equals("-"))
523 start = Integer.parseInt(stt);
525 } catch (NumberFormatException ex)
531 String stt = st.nextToken();
532 if (stt.length() == 0 || stt.equals("-"))
538 end = Integer.parseInt(stt);
540 } catch (NumberFormatException ex)
544 // TODO: decide if non positional feature assertion for input data
545 // where end==0 is generally valid
548 // treat as non-positional feature, regardless.
553 score = new Float(st.nextToken()).floatValue();
554 } catch (NumberFormatException ex)
559 sf = new SequenceFeature(type, desc, start, end, score, group);
563 sf.setValue("STRAND", st.nextToken());
564 sf.setValue("FRAME", st.nextToken());
565 } catch (Exception ex)
569 if (st.hasMoreTokens())
571 StringBuffer attributes = new StringBuffer();
573 while (st.hasMoreTokens())
575 attributes.append((sep ? "\t" : "") + st.nextElement());
578 // TODO validate and split GFF2 attributes field ? parse out
579 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
580 // sf.setValue(attrib, val);
581 sf.setValue("ATTRIBUTES", attributes.toString());
584 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
587 // check whether we should add the sequence feature to any other
588 // sequences in the alignment with the same or similar
589 while ((seq = align.findName(seq, seqId, true)) != null)
591 seq.addSequenceFeature(new SequenceFeature(sf));
598 if (GFFFile && seq == null)
604 desc = st.nextToken();
606 if (!st.hasMoreTokens())
609 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
610 // in all probability, this isn't a file we understand, so bail
615 token = st.nextToken();
617 if (!token.equals("ID_NOT_SPECIFIED"))
619 seq = findName(align, seqId = token, relaxedIdmatching, null);
627 index = Integer.parseInt(st.nextToken());
628 seq = align.getSequenceAt(index);
629 } catch (NumberFormatException ex)
637 System.out.println("Sequence not found: " + line);
641 start = Integer.parseInt(st.nextToken());
642 end = Integer.parseInt(st.nextToken());
644 type = st.nextToken();
646 if (!colours.containsKey(type))
648 // Probably the old style groups file
649 UserColourScheme ucs = new UserColourScheme(type);
650 colours.put(type, ucs.findColour('A'));
652 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
653 if (st.hasMoreTokens())
657 score = new Float(st.nextToken()).floatValue();
658 // update colourgradient bounds if allowed to
659 } catch (NumberFormatException ex)
665 if (groupLink != null && removeHTML)
667 sf.addLink(groupLink);
668 sf.description += "%LINK%";
670 if (typeLink.containsKey(type) && removeHTML)
672 sf.addLink(typeLink.get(type).toString());
673 sf.description += "%LINK%";
676 parseDescriptionHTML(sf, removeHTML);
678 seq.addSequenceFeature(sf);
681 && (seq = align.findName(seq, seqId, false)) != null)
683 seq.addSequenceFeature(new SequenceFeature(sf));
685 // If we got here, its not a GFFFile
690 } catch (Exception ex)
692 // should report somewhere useful for UI if necessary
693 warningMessage = ((warningMessage == null) ? "" : warningMessage)
694 + "Parsing error at\n" + line;
695 System.out.println("Error parsing feature file: " + ex + "\n" + line);
696 ex.printStackTrace(System.err);
704 private enum GffPragmas
706 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
709 private static Map<String, GffPragmas> GFFPRAGMA;
712 GFFPRAGMA = new HashMap<String, GffPragmas>();
713 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
714 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
715 GFFPRAGMA.put("#", GffPragmas.hash);
716 GFFPRAGMA.put("fasta", GffPragmas.fasta);
717 GFFPRAGMA.put("species-build", GffPragmas.species_build);
718 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
719 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
722 private void processGffPragma(String line, Map<String, String> gffProps,
723 AlignmentI align, ArrayList<SequenceI> newseqs)
726 // line starts with ##
727 int spacepos = line.indexOf(' ');
728 String pragma = spacepos == -1 ? line.substring(2).trim() : line
729 .substring(2, spacepos);
730 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
731 if (gffpragma == null)
740 gffversion = Integer.parseInt(line.substring(spacepos + 1));
746 case feature_ontology:
747 // resolve against specific feature ontology
749 case attribute_ontology:
750 // resolve against specific attribute ontology
752 case source_ontology:
753 // resolve against specific source ontology
756 // resolve against specific NCBI taxon version
759 // close off any open feature hierarchies
762 // process the rest of the file as a fasta file and replace any dummy
764 process_as_fasta(align, newseqs);
768 System.err.println("Ignoring unknown pragma:\n" + line);
772 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
778 } catch (IOException q)
781 AlignFile parser = GenericFileAdapter.getFile("FastaFile");
782 List<SequenceI> includedseqs = parser.getSeqs();
783 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
784 // iterate over includedseqs, and replacing matching ones with newseqs
785 // sequences. Generic iterator not used here because we modify includedseqs
787 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
789 // search for any dummy seqs that this sequence can be used to update
790 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
791 if (dummyseq != null)
793 // dummyseq was created so it could be annotated and referred to in
794 // alignments/codon mappings
796 SequenceI mseq = includedseqs.get(p);
797 // mseq is the 'template' imported from the FASTA file which we'll use
798 // to coomplete dummyseq
799 if (dummyseq instanceof SequenceDummy)
801 // probably have the pattern wrong
802 // idea is that a flyweight proxy for a sequence ID can be created for
803 // 1. stable reference creation
804 // 2. addition of annotation
805 // 3. future replacement by a real sequence
806 // current pattern is to create SequenceDummy objects - a convenience
807 // constructor for a Sequence.
808 // problem is that when promoted to a real sequence, all references
810 // to be updated somehow.
811 ((SequenceDummy) dummyseq).become(mseq);
812 includedseqs.set(p, dummyseq); // template is no longer needed
816 // finally add sequences to the dataset
817 for (SequenceI seq : includedseqs)
819 align.addSequence(seq);
824 * take a sequence feature and examine its attributes to decide how it should
825 * be added to a sequence
828 * - the destination sequence constructed or discovered in the
831 * - the base feature with ATTRIBUTES property containing any
832 * additional attributes
834 * - true if we are processing a GFF annotation file
835 * @return true if sf was actually added to the sequence, false if it was
836 * processed in another way
838 public boolean processOrAddSeqFeature(AlignmentI align, 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);
876 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
878 key = pair.substring(0, eqpos);
879 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,
985 String attr, int strand) 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[]
1149 // add dummy sequence to the newseqs list
1154 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1156 if (sf.getDescription() == null)
1160 ParseHtmlBodyAndLinks parsed = new 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, Map<String,Object> visible)
1183 return printJalviewFormat(seqs, visible, true, true);
1187 * generate a features file for seqs with colours from visible (if any)
1190 * source of features
1192 * hash of Colours for each feature type
1194 * when true only feature types in 'visible' will be output
1196 * indicates if non-positional features should be output (regardless
1198 * @return features file contents
1200 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1201 boolean visOnly, boolean nonpos)
1203 StringBuffer out = new StringBuffer();
1204 SequenceFeature[] next;
1205 boolean featuresGen = false;
1206 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1208 // no point continuing.
1209 return "No Features Visible";
1212 if (visible != null && visOnly)
1214 // write feature colours only if we're given them and we are generating
1216 // TODO: decide if feature links should also be written here ?
1217 Iterator en = visible.keySet().iterator();
1219 while (en.hasNext())
1221 type = en.next().toString();
1223 if (visible.get(type) instanceof GraduatedColor)
1225 GraduatedColor gc = (GraduatedColor) visible.get(type);
1226 color = (gc.isColourByLabel() ? "label|" : "")
1227 + Format.getHexString(gc.getMinColor()) + "|"
1228 + Format.getHexString(gc.getMaxColor())
1229 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1230 + gc.getMax() + "|";
1231 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1233 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1239 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1241 System.err.println("WARNING: Unsupported threshold type ("
1242 + gc.getThreshType() + ") : Assuming 'above'");
1247 color += "|" + gc.getThresh();
1254 else if (visible.get(type) instanceof java.awt.Color)
1256 color = Format.getHexString((java.awt.Color) visible.get(type));
1260 // legacy support for integer objects containing colour triplet values
1261 color = Format.getHexString(new java.awt.Color(Integer
1262 .parseInt(visible.get(type).toString())));
1267 out.append(newline);
1270 // Work out which groups are both present and visible
1271 Vector groups = new Vector();
1273 boolean isnonpos = false;
1275 for (int i = 0; i < seqs.length; i++)
1277 next = seqs[i].getSequenceFeatures();
1280 for (int j = 0; j < next.length; j++)
1282 isnonpos = next[j].begin == 0 && next[j].end == 0;
1283 if ((!nonpos && isnonpos)
1284 || (!isnonpos && visOnly && !visible
1285 .containsKey(next[j].type)))
1290 if (next[j].featureGroup != null
1291 && !groups.contains(next[j].featureGroup))
1293 groups.addElement(next[j].featureGroup);
1299 String group = null;
1303 if (groups.size() > 0 && groupIndex < groups.size())
1305 group = groups.elementAt(groupIndex).toString();
1306 out.append(newline);
1307 out.append("STARTGROUP\t");
1309 out.append(newline);
1316 for (int i = 0; i < seqs.length; i++)
1318 next = seqs[i].getSequenceFeatures();
1321 for (int j = 0; j < next.length; j++)
1323 isnonpos = next[j].begin == 0 && next[j].end == 0;
1324 if ((!nonpos && isnonpos)
1325 || (!isnonpos && visOnly && !visible
1326 .containsKey(next[j].type)))
1328 // skip if feature is nonpos and we ignore them or if we only
1329 // output visible and it isn't non-pos and it's not visible
1334 && (next[j].featureGroup == null || !next[j].featureGroup
1340 if (group == null && next[j].featureGroup != null)
1344 // we have features to output
1346 if (next[j].description == null
1347 || next[j].description.equals(""))
1349 out.append(next[j].type + "\t");
1353 if (next[j].links != null
1354 && next[j].getDescription().indexOf("<html>") == -1)
1356 out.append("<html>");
1359 out.append(next[j].description + " ");
1360 if (next[j].links != null)
1362 for (int l = 0; l < next[j].links.size(); l++)
1364 String label = next[j].links.elementAt(l).toString();
1365 String href = label.substring(label.indexOf("|") + 1);
1366 label = label.substring(0, label.indexOf("|"));
1368 if (next[j].description.indexOf(href) == -1)
1370 out.append("<a href=\"" + href + "\">" + label + "</a>");
1374 if (next[j].getDescription().indexOf("</html>") == -1)
1376 out.append("</html>");
1382 out.append(seqs[i].getName());
1383 out.append("\t-1\t");
1384 out.append("" + next[j].begin);
1386 out.append("" + next[j].end);
1388 out.append(next[j].type);
1389 if (!Float.isNaN(next[j].score))
1392 out.append(next[j].score);
1394 out.append(newline);
1401 out.append("ENDGROUP\t");
1403 out.append(newline);
1411 } while (groupIndex < groups.size() + 1);
1415 return "No Features Visible";
1418 return out.toString();
1422 * generate a gff file for sequence features includes non-pos features by
1429 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible)
1431 return printGFFFormat(seqs, visible, true, true);
1434 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible,
1435 boolean visOnly, boolean nonpos)
1437 StringBuffer out = new StringBuffer();
1438 SequenceFeature[] next;
1441 for (int i = 0; i < seqs.length; i++)
1443 if (seqs[i].getSequenceFeatures() != null)
1445 next = seqs[i].getSequenceFeatures();
1446 for (int j = 0; j < next.length; j++)
1448 isnonpos = next[j].begin == 0 && next[j].end == 0;
1449 if ((!nonpos && isnonpos)
1450 || (!isnonpos && visOnly && !visible
1451 .containsKey(next[j].type)))
1456 source = next[j].featureGroup;
1459 source = next[j].getDescription();
1462 out.append(seqs[i].getName());
1466 out.append(next[j].type);
1468 out.append("" + next[j].begin);
1470 out.append("" + next[j].end);
1472 out.append(next[j].score);
1475 if (next[j].getValue("STRAND") != null)
1477 out.append(next[j].getValue("STRAND"));
1485 if (next[j].getValue("FRAME") != null)
1487 out.append(next[j].getValue("FRAME"));
1493 // TODO: verify/check GFF - should there be a /t here before attribute
1496 if (next[j].getValue("ATTRIBUTES") != null)
1498 out.append(next[j].getValue("ATTRIBUTES"));
1501 out.append(newline);
1507 return out.toString();
1511 * this is only for the benefit of object polymorphism - method does nothing.
1519 * this is only for the benefit of object polymorphism - method does nothing.
1521 * @return error message
1523 public String print()
1525 return "USE printGFFFormat() or printJalviewFormat()";