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("sequence-region", GffPragmas.sequence_region);
709 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
710 GFFPRAGMA.put("#", GffPragmas.hash);
711 GFFPRAGMA.put("fasta", GffPragmas.fasta);
712 GFFPRAGMA.put("species-build", GffPragmas.species_build);
713 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
714 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
717 private void processGffPragma(String line, Map<String, String> gffProps,
718 AlignmentI align, ArrayList<SequenceI> newseqs)
721 // line starts with ##
722 int spacepos = line.indexOf(' ');
723 String pragma = spacepos == -1 ? line.substring(2).trim() : line
724 .substring(2, spacepos);
725 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
726 if (gffpragma == null)
735 gffversion = Integer.parseInt(line.substring(spacepos + 1));
741 case feature_ontology:
742 // resolve against specific feature ontology
744 case attribute_ontology:
745 // resolve against specific attribute ontology
747 case source_ontology:
748 // resolve against specific source ontology
751 // resolve against specific NCBI taxon version
754 // close off any open feature hierarchies
757 // process the rest of the file as a fasta file and replace any dummy
759 process_as_fasta(align, newseqs);
763 System.err.println("Ignoring unknown pragma:\n" + line);
767 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
773 } catch (IOException q)
776 FastaFile parser = new FastaFile(this);
777 List<SequenceI> includedseqs = parser.getSeqs();
778 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
779 // iterate over includedseqs, and replacing matching ones with newseqs
780 // sequences. Generic iterator not used here because we modify includedseqs
782 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
784 // search for any dummy seqs that this sequence can be used to update
785 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
786 if (dummyseq != null)
788 // dummyseq was created so it could be annotated and referred to in
789 // alignments/codon mappings
791 SequenceI mseq = includedseqs.get(p);
792 // mseq is the 'template' imported from the FASTA file which we'll use
793 // to coomplete dummyseq
794 if (dummyseq instanceof SequenceDummy)
796 // probably have the pattern wrong
797 // idea is that a flyweight proxy for a sequence ID can be created for
798 // 1. stable reference creation
799 // 2. addition of annotation
800 // 3. future replacement by a real sequence
801 // current pattern is to create SequenceDummy objects - a convenience
802 // constructor for a Sequence.
803 // problem is that when promoted to a real sequence, all references
805 // to be updated somehow.
806 ((SequenceDummy) dummyseq).become(mseq);
807 includedseqs.set(p, dummyseq); // template is no longer needed
811 // finally add sequences to the dataset
812 for (SequenceI seq : includedseqs)
814 align.addSequence(seq);
819 * take a sequence feature and examine its attributes to decide how it should
820 * be added to a sequence
823 * - the destination sequence constructed or discovered in the
826 * - the base feature with ATTRIBUTES property containing any
827 * additional attributes
829 * - true if we are processing a GFF annotation file
830 * @return true if sf was actually added to the sequence, false if it was
831 * processed in another way
833 public boolean processOrAddSeqFeature(AlignmentI align,
834 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);
874 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
876 key = pair.substring(0, eqpos);
877 value = pair.substring(eqpos + 1);
886 List<String> vals = set.get(key);
889 vals = new ArrayList<String>();
894 vals.add(value.trim());
900 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
901 relaxedIdMatching); // process decides if
902 // feature is actually
904 } catch (InvalidGFF3FieldException ivfe)
906 System.err.println(ivfe);
912 seq.addSequenceFeature(sf);
917 public class InvalidGFF3FieldException extends Exception
921 public InvalidGFF3FieldException(String field,
922 Map<String, List<String>> set, String message)
924 super(message + " (Field was " + field + " and value was "
925 + set.get(field).toString());
927 this.value = set.get(field).toString();
933 * take a set of keys for a feature and interpret them
941 public boolean processGffKey(Map<String, List<String>> set, int nattr,
942 SequenceI seq, SequenceFeature sf, AlignmentI align,
943 List<SequenceI> newseqs, boolean relaxedIdMatching)
944 throws InvalidGFF3FieldException
947 // decide how to interpret according to type
948 if (sf.getType().equals("similarity"))
950 int strand = sf.getStrand();
951 // exonerate cdna/protein map
953 List<SequenceI> querySeq = findNames(align, newseqs,
954 relaxedIdMatching, set.get(attr = "Query"));
955 if (querySeq == null || querySeq.size() != 1)
957 throw new InvalidGFF3FieldException(attr, set,
958 "Expecting exactly one sequence in Query field (got "
959 + set.get(attr) + ")");
961 if (set.containsKey(attr = "Align"))
963 // process the align maps and create cdna/protein maps
964 // ideally, the query sequences are in the alignment, but maybe not...
966 AlignedCodonFrame alco = new AlignedCodonFrame();
967 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
970 // add codon mapping, and hope!
971 alco.addMap(seq, querySeq.get(0), codonmapping);
972 align.addCodonFrame(alco);
973 // everything that's needed to be done is done
974 // no features to create here !
982 private MapList constructCodonMappingFromAlign(
983 Map<String, List<String>> set, String attr, int strand)
984 throws InvalidGFF3FieldException
988 throw new InvalidGFF3FieldException(attr, set,
989 "Invalid strand for a codon mapping (cannot be 0)");
991 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
992 int lastppos = 0, lastpframe = 0;
993 for (String range : set.get(attr))
995 List<Integer> ints = new ArrayList<Integer>();
996 StringTokenizer st = new StringTokenizer(range, " ");
997 while (st.hasMoreTokens())
999 String num = st.nextToken();
1002 ints.add(new Integer(num));
1003 } catch (NumberFormatException nfe)
1005 throw new InvalidGFF3FieldException(attr, set,
1006 "Invalid number in field " + num);
1009 // Align positionInRef positionInQuery LengthInRef
1010 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1011 // 3652 - . alignment_id 0 ;
1012 // Query DDB_G0269124
1013 // Align 11270 143 120
1014 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1015 // dna in strand direction
1016 // Align 11150 187 282
1017 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1018 // dna in strand direction
1020 // Align 10865 281 888
1021 // Align 9977 578 1068
1022 // Align 8909 935 375
1024 if (ints.size() != 3)
1026 throw new InvalidGFF3FieldException(attr, set,
1027 "Invalid number of fields for this attribute ("
1028 + ints.size() + ")");
1030 fromrange.add(new Integer(ints.get(0).intValue()));
1031 fromrange.add(new Integer(ints.get(0).intValue() + strand
1032 * ints.get(2).intValue()));
1033 // how are intron/exon boundaries that do not align in codons
1035 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1037 // extend existing to map
1038 lastppos += ints.get(2) / 3;
1039 lastpframe = ints.get(2) % 3;
1040 torange.set(torange.size() - 1, new Integer(lastppos));
1045 torange.add(ints.get(1));
1046 lastppos = ints.get(1) + ints.get(2) / 3;
1047 lastpframe = ints.get(2) % 3;
1048 torange.add(new Integer(lastppos));
1051 // from and to ranges must end up being a series of start/end intervals
1052 if (fromrange.size() % 2 == 1)
1054 throw new InvalidGFF3FieldException(attr, set,
1055 "Couldn't parse the DNA alignment range correctly");
1057 if (torange.size() % 2 == 1)
1059 throw new InvalidGFF3FieldException(attr, set,
1060 "Couldn't parse the protein alignment range correctly");
1062 // finally, build the map
1063 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1066 for (Integer ip : fromrange)
1068 frommap[p++] = ip.intValue();
1071 for (Integer ip : torange)
1073 tomap[p++] = ip.intValue();
1076 return new MapList(frommap, tomap, 3, 1);
1079 private List<SequenceI> findNames(AlignmentI align,
1080 List<SequenceI> newseqs, boolean relaxedIdMatching,
1083 List<SequenceI> found = new ArrayList<SequenceI>();
1084 for (String seqId : list)
1086 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1095 private AlignmentI lastmatchedAl = null;
1097 private SequenceIdMatcher matcher = null;
1100 * clear any temporary handles used to speed up ID matching
1102 private void resetMatcher()
1104 lastmatchedAl = null;
1108 private SequenceI findName(AlignmentI align, String seqId,
1109 boolean relaxedIdMatching, List<SequenceI> newseqs)
1111 SequenceI match = null;
1112 if (relaxedIdMatching)
1114 if (lastmatchedAl != align)
1116 matcher = new SequenceIdMatcher(
1117 (lastmatchedAl = align).getSequencesArray());
1118 if (newseqs != null)
1120 matcher.addAll(newseqs);
1123 match = matcher.findIdMatch(seqId);
1127 match = align.findName(seqId, true);
1128 if (match == null && newseqs != null)
1130 for (SequenceI m : newseqs)
1132 if (seqId.equals(m.getName()))
1140 if (match == null && newseqs != null)
1142 match = new SequenceDummy(seqId);
1143 if (relaxedIdMatching)
1145 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1147 // add dummy sequence to the newseqs list
1153 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1155 if (sf.getDescription() == null)
1159 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1160 sf.getDescription(), removeHTML, newline);
1162 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1164 for (String link : parsed.getLinks())
1172 * generate a features file for seqs includes non-pos features by default.
1175 * source of sequence features
1177 * hash of feature types and colours
1178 * @return features file contents
1180 public String printJalviewFormat(SequenceI[] seqs,
1181 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,
1435 Map<String, Object> visible, 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()";