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 // TODO Auto-generated method stub
177 super.addAnnotations(al);
181 public void addProperties(Alignment al)
183 // TODO Auto-generated method stub
184 super.addProperties(al);
188 public void addSeqGroups(AlignmentI al)
190 // TODO Auto-generated method stub
191 super.addSeqGroups(al);
195 * Parse GFF or sequence features file
198 * - alignment/dataset containing sequences that are to be annotated
200 * - hashtable to store feature colour definitions
202 * - hashtable to store associated URLs
204 * - process html strings into plain text
205 * @param relaxedIdmatching
206 * - when true, ID matches to compound sequence IDs are allowed
207 * @return true if features were added
209 public boolean parse(AlignmentI align, Map colours, Map featureLink,
210 boolean removeHTML, boolean relaxedIdmatching)
216 SequenceI seq = null;
218 * keep track of any sequences we try to create from the data if it is a GFF3 file
220 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
221 String type, desc, token = null;
223 int index, start, end;
227 String featureGroup = null, groupLink = null;
228 Map typeLink = new Hashtable();
230 * when true, assume GFF style features rather than Jalview style.
232 boolean GFFFile = true;
233 Map<String, String> gffProps = new HashMap<String, String>();
234 while ((line = nextLine()) != null)
236 // skip comments/process pragmas
237 if (line.startsWith("#"))
239 if (line.startsWith("##"))
241 // possibly GFF2/3 version and metadata header
242 processGffPragma(line, gffProps, align, newseqs);
248 st = new StringTokenizer(line, "\t");
249 if (st.countTokens() == 1)
251 if (line.trim().equalsIgnoreCase("GFF"))
253 // Start parsing file as if it might be GFF again.
258 if (st.countTokens() > 1 && st.countTokens() < 4)
261 type = st.nextToken();
262 if (type.equalsIgnoreCase("startgroup"))
264 featureGroup = st.nextToken();
265 if (st.hasMoreElements())
267 groupLink = st.nextToken();
268 featureLink.put(featureGroup, groupLink);
271 else if (type.equalsIgnoreCase("endgroup"))
273 // We should check whether this is the current group,
274 // but at present theres no way of showing more than 1 group
281 Object colour = null;
282 String colscheme = st.nextToken();
283 if (colscheme.indexOf("|") > -1
284 || colscheme.trim().equalsIgnoreCase("label"))
286 // Parse '|' separated graduated colourscheme fields:
287 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
288 // can either provide 'label' only, first is optional, next two
289 // colors are required (but may be
290 // left blank), next is optional, nxt two min/max are required.
291 // first is either 'label'
292 // first/second and third are both hexadecimal or word equivalent
294 // next two are values parsed as floats.
295 // fifth is either 'above','below', or 'none'.
296 // sixth is a float value and only required when fifth is either
297 // 'above' or 'below'.
298 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
301 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
302 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
303 boolean labelCol = false;
305 String mincol = gcol.nextToken();
309 .println("Expected either 'label' or a colour specification in the line: "
313 String maxcol = null;
314 if (mincol.toLowerCase().indexOf("label") == 0)
317 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
319 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
321 String abso = null, minval, maxval;
324 // at least four more tokens
325 if (mincol.equals("|"))
331 gcol.nextToken(); // skip next '|'
333 // continue parsing rest of line
334 maxcol = gcol.nextToken();
335 if (maxcol.equals("|"))
341 gcol.nextToken(); // skip next '|'
343 abso = gcol.nextToken();
344 gcol.nextToken(); // skip next '|'
345 if (abso.toLowerCase().indexOf("abso") != 0)
352 minval = gcol.nextToken();
353 gcol.nextToken(); // skip next '|'
355 maxval = gcol.nextToken();
356 if (gcol.hasMoreTokens())
358 gcol.nextToken(); // skip next '|'
362 if (minval.length() > 0)
364 min = new Float(minval).floatValue();
366 } catch (Exception e)
369 .println("Couldn't parse the minimum value for graduated colour for type ("
371 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
376 if (maxval.length() > 0)
378 max = new Float(maxval).floatValue();
380 } catch (Exception e)
383 .println("Couldn't parse the maximum value for graduated colour for type ("
390 // add in some dummy min/max colours for the label-only
397 colour = new jalview.schemes.GraduatedColor(
398 new UserColourScheme(mincol).findColour('A'),
399 new UserColourScheme(maxcol).findColour('A'), min,
401 } catch (Exception e)
404 .println("Couldn't parse the graduated colour scheme ("
410 ((jalview.schemes.GraduatedColor) colour)
411 .setColourByLabel(labelCol);
412 ((jalview.schemes.GraduatedColor) colour)
413 .setAutoScaled(abso == null);
414 // add in any additional parameters
415 String ttype = null, tval = null;
416 if (gcol.hasMoreTokens())
418 // threshold type and possibly a threshold value
419 ttype = gcol.nextToken();
420 if (ttype.toLowerCase().startsWith("below"))
422 ((jalview.schemes.GraduatedColor) colour)
423 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
425 else if (ttype.toLowerCase().startsWith("above"))
427 ((jalview.schemes.GraduatedColor) colour)
428 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
432 ((jalview.schemes.GraduatedColor) colour)
433 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
434 if (!ttype.toLowerCase().startsWith("no"))
437 .println("Ignoring unrecognised threshold type : "
442 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
447 tval = gcol.nextToken();
448 ((jalview.schemes.GraduatedColor) colour)
449 .setThresh(new Float(tval).floatValue());
450 } catch (Exception e)
453 .println("Couldn't parse threshold value as a float: ("
458 // parse the thresh-is-min token ?
459 if (gcol.hasMoreTokens())
462 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
463 while (gcol.hasMoreTokens())
465 System.err.println("|" + gcol.nextToken());
467 System.err.println("\n");
473 UserColourScheme ucs = new UserColourScheme(colscheme);
474 colour = ucs.findColour('A');
478 colours.put(type, colour);
480 if (st.hasMoreElements())
482 String link = st.nextToken();
483 typeLink.put(type, link);
484 if (featureLink == null)
486 featureLink = new Hashtable();
488 featureLink.put(type, link);
494 while (st.hasMoreElements())
499 // Still possible this is an old Jalview file,
500 // which does not have type colours at the beginning
501 seqId = token = st.nextToken();
502 seq = findName(align, seqId, relaxedIdmatching, newseqs);
505 desc = st.nextToken();
507 if (doGffSource && desc.indexOf(' ') == -1)
509 // could also be a source term rather than description line
510 group = new String(desc);
512 type = st.nextToken();
515 String stt = st.nextToken();
516 if (stt.length() == 0 || stt.equals("-"))
522 start = Integer.parseInt(stt);
524 } catch (NumberFormatException ex)
530 String stt = st.nextToken();
531 if (stt.length() == 0 || stt.equals("-"))
537 end = Integer.parseInt(stt);
539 } catch (NumberFormatException ex)
543 // TODO: decide if non positional feature assertion for input data
544 // where end==0 is generally valid
547 // treat as non-positional feature, regardless.
552 score = new Float(st.nextToken()).floatValue();
553 } catch (NumberFormatException ex)
558 sf = new SequenceFeature(type, desc, start, end, score, group);
562 sf.setValue("STRAND", st.nextToken());
563 sf.setValue("FRAME", st.nextToken());
564 } catch (Exception ex)
568 if (st.hasMoreTokens())
570 StringBuffer attributes = new StringBuffer();
572 while (st.hasMoreTokens())
574 attributes.append((sep ? "\t" : "") + st.nextElement());
577 // TODO validate and split GFF2 attributes field ? parse out
578 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
579 // sf.setValue(attrib, val);
580 sf.setValue("ATTRIBUTES", attributes.toString());
583 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
586 // check whether we should add the sequence feature to any other
587 // sequences in the alignment with the same or similar
588 while ((seq = align.findName(seq, seqId, true)) != null)
590 seq.addSequenceFeature(new SequenceFeature(sf));
597 if (GFFFile && seq == null)
603 desc = st.nextToken();
605 if (!st.hasMoreTokens())
608 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
609 // in all probability, this isn't a file we understand, so bail
614 token = st.nextToken();
616 if (!token.equals("ID_NOT_SPECIFIED"))
618 seq = findName(align, seqId = token, relaxedIdmatching, null);
626 index = Integer.parseInt(st.nextToken());
627 seq = align.getSequenceAt(index);
628 } catch (NumberFormatException ex)
636 System.out.println("Sequence not found: " + line);
640 start = Integer.parseInt(st.nextToken());
641 end = Integer.parseInt(st.nextToken());
643 type = st.nextToken();
645 if (!colours.containsKey(type))
647 // Probably the old style groups file
648 UserColourScheme ucs = new UserColourScheme(type);
649 colours.put(type, ucs.findColour('A'));
651 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
652 if (st.hasMoreTokens())
656 score = new Float(st.nextToken()).floatValue();
657 // update colourgradient bounds if allowed to
658 } catch (NumberFormatException ex)
664 if (groupLink != null && removeHTML)
666 sf.addLink(groupLink);
667 sf.description += "%LINK%";
669 if (typeLink.containsKey(type) && removeHTML)
671 sf.addLink(typeLink.get(type).toString());
672 sf.description += "%LINK%";
675 parseDescriptionHTML(sf, removeHTML);
677 seq.addSequenceFeature(sf);
680 && (seq = align.findName(seq, seqId, false)) != null)
682 seq.addSequenceFeature(new SequenceFeature(sf));
684 // If we got here, its not a GFFFile
689 } catch (Exception ex)
691 // should report somewhere useful for UI if necessary
692 warningMessage = ((warningMessage == null) ? "" : warningMessage)
693 + "Parsing error at\n" + line;
694 System.out.println("Error parsing feature file: " + ex + "\n" + line);
695 ex.printStackTrace(System.err);
703 private enum GffPragmas
705 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
708 private static Map<String, GffPragmas> GFFPRAGMA;
711 GFFPRAGMA = new HashMap<String, GffPragmas>();
712 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
713 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
714 GFFPRAGMA.put("#", GffPragmas.hash);
715 GFFPRAGMA.put("fasta", GffPragmas.fasta);
716 GFFPRAGMA.put("species-build", GffPragmas.species_build);
717 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
718 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
721 private void processGffPragma(String line, Map<String, String> gffProps,
722 AlignmentI align, ArrayList<SequenceI> newseqs)
725 // line starts with ##
726 int spacepos = line.indexOf(' ');
727 String pragma = spacepos == -1 ? line.substring(2).trim() : line
728 .substring(2, spacepos);
729 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
730 if (gffpragma == null)
739 gffversion = Integer.parseInt(line.substring(spacepos + 1));
745 case feature_ontology:
746 // resolve against specific feature ontology
748 case attribute_ontology:
749 // resolve against specific attribute ontology
751 case source_ontology:
752 // resolve against specific source ontology
755 // resolve against specific NCBI taxon version
758 // close off any open feature hierarchies
761 // process the rest of the file as a fasta file and replace any dummy
763 process_as_fasta(align, newseqs);
767 System.err.println("Ignoring unknown pragma:\n" + line);
771 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
777 } catch (IOException q)
780 FastaFile parser = new FastaFile(this);
781 List<SequenceI> includedseqs = parser.getSeqs();
782 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
783 // iterate over includedseqs, and replacing matching ones with newseqs
784 // sequences. Generic iterator not used here because we modify includedseqs
786 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
788 // search for any dummy seqs that this sequence can be used to update
789 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
790 if (dummyseq != null)
792 // dummyseq was created so it could be annotated and referred to in
793 // alignments/codon mappings
795 SequenceI mseq = includedseqs.get(p);
796 // mseq is the 'template' imported from the FASTA file which we'll use
797 // to coomplete dummyseq
798 if (dummyseq instanceof SequenceDummy)
800 // probably have the pattern wrong
801 // idea is that a flyweight proxy for a sequence ID can be created for
802 // 1. stable reference creation
803 // 2. addition of annotation
804 // 3. future replacement by a real sequence
805 // current pattern is to create SequenceDummy objects - a convenience
806 // constructor for a Sequence.
807 // problem is that when promoted to a real sequence, all references
809 // to be updated somehow.
810 ((SequenceDummy) dummyseq).become(mseq);
811 includedseqs.set(p, dummyseq); // template is no longer needed
815 // finally add sequences to the dataset
816 for (SequenceI seq : includedseqs)
818 align.addSequence(seq);
823 * take a sequence feature and examine its attributes to decide how it should
824 * be added to a sequence
827 * - the destination sequence constructed or discovered in the
830 * - the base feature with ATTRIBUTES property containing any
831 * additional attributes
833 * - true if we are processing a GFF annotation file
834 * @return true if sf was actually added to the sequence, false if it was
835 * processed in another way
837 public boolean processOrAddSeqFeature(AlignmentI align, List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
838 boolean gFFFile, boolean relaxedIdMatching)
840 String attr = (String) sf.getValue("ATTRIBUTES");
842 if (gFFFile && attr != null)
846 for (String attset : attr.split("\t"))
848 if (attset==null || attset.trim().length()==0)
853 Map<String, List<String>> set = new HashMap<String, List<String>>();
854 // normally, only expect one column - 9 - in this field
855 // the attributes (Gff3) or groups (gff2) field
856 for (String pair : attset.trim().split(";"))
859 if (pair.length() == 0)
864 // expect either space seperated (gff2) or '=' separated (gff3)
865 // key/value pairs here
867 int eqpos = pair.indexOf('='),sppos = pair.indexOf(' ');
868 String key = null, value = null;
870 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
872 key = pair.substring(0, sppos);
873 value = pair.substring(sppos + 1);
875 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
877 key = pair.substring(0, eqpos);
878 value = pair.substring(eqpos + 1);
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,
984 String attr, int strand) 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[]
1148 // 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, Map<String,Object> visible)
1182 return printJalviewFormat(seqs, visible, true, true);
1186 * generate a features file for seqs with colours from visible (if any)
1189 * source of features
1191 * hash of Colours for each feature type
1193 * when true only feature types in 'visible' will be output
1195 * indicates if non-positional features should be output (regardless
1197 * @return features file contents
1199 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1200 boolean visOnly, boolean nonpos)
1202 StringBuffer out = new StringBuffer();
1203 SequenceFeature[] next;
1204 boolean featuresGen = false;
1205 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1207 // no point continuing.
1208 return "No Features Visible";
1211 if (visible != null && visOnly)
1213 // write feature colours only if we're given them and we are generating
1215 // TODO: decide if feature links should also be written here ?
1216 Iterator en = visible.keySet().iterator();
1218 while (en.hasNext())
1220 type = en.next().toString();
1222 if (visible.get(type) instanceof GraduatedColor)
1224 GraduatedColor gc = (GraduatedColor) visible.get(type);
1225 color = (gc.isColourByLabel() ? "label|" : "")
1226 + Format.getHexString(gc.getMinColor()) + "|"
1227 + Format.getHexString(gc.getMaxColor())
1228 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1229 + gc.getMax() + "|";
1230 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1232 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1238 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1240 System.err.println("WARNING: Unsupported threshold type ("
1241 + gc.getThreshType() + ") : Assuming 'above'");
1246 color += "|" + gc.getThresh();
1253 else if (visible.get(type) instanceof java.awt.Color)
1255 color = Format.getHexString((java.awt.Color) visible.get(type));
1259 // legacy support for integer objects containing colour triplet values
1260 color = Format.getHexString(new java.awt.Color(Integer
1261 .parseInt(visible.get(type).toString())));
1266 out.append(newline);
1269 // Work out which groups are both present and visible
1270 Vector groups = new Vector();
1272 boolean isnonpos = false;
1274 for (int i = 0; i < seqs.length; i++)
1276 next = seqs[i].getSequenceFeatures();
1279 for (int j = 0; j < next.length; j++)
1281 isnonpos = next[j].begin == 0 && next[j].end == 0;
1282 if ((!nonpos && isnonpos)
1283 || (!isnonpos && visOnly && !visible
1284 .containsKey(next[j].type)))
1289 if (next[j].featureGroup != null
1290 && !groups.contains(next[j].featureGroup))
1292 groups.addElement(next[j].featureGroup);
1298 String group = null;
1302 if (groups.size() > 0 && groupIndex < groups.size())
1304 group = groups.elementAt(groupIndex).toString();
1305 out.append(newline);
1306 out.append("STARTGROUP\t");
1308 out.append(newline);
1315 for (int i = 0; i < seqs.length; i++)
1317 next = seqs[i].getSequenceFeatures();
1320 for (int j = 0; j < next.length; j++)
1322 isnonpos = next[j].begin == 0 && next[j].end == 0;
1323 if ((!nonpos && isnonpos)
1324 || (!isnonpos && visOnly && !visible
1325 .containsKey(next[j].type)))
1327 // skip if feature is nonpos and we ignore them or if we only
1328 // output visible and it isn't non-pos and it's not visible
1333 && (next[j].featureGroup == null || !next[j].featureGroup
1339 if (group == null && next[j].featureGroup != null)
1343 // we have features to output
1345 if (next[j].description == null
1346 || next[j].description.equals(""))
1348 out.append(next[j].type + "\t");
1352 if (next[j].links != null
1353 && next[j].getDescription().indexOf("<html>") == -1)
1355 out.append("<html>");
1358 out.append(next[j].description + " ");
1359 if (next[j].links != null)
1361 for (int l = 0; l < next[j].links.size(); l++)
1363 String label = next[j].links.elementAt(l).toString();
1364 String href = label.substring(label.indexOf("|") + 1);
1365 label = label.substring(0, label.indexOf("|"));
1367 if (next[j].description.indexOf(href) == -1)
1369 out.append("<a href=\"" + href + "\">" + label + "</a>");
1373 if (next[j].getDescription().indexOf("</html>") == -1)
1375 out.append("</html>");
1381 out.append(seqs[i].getName());
1382 out.append("\t-1\t");
1383 out.append(next[j].begin);
1385 out.append(next[j].end);
1387 out.append(next[j].type);
1388 if (next[j].score != Float.NaN)
1391 out.append(next[j].score);
1393 out.append(newline);
1400 out.append("ENDGROUP\t");
1402 out.append(newline);
1410 } while (groupIndex < groups.size() + 1);
1414 return "No Features Visible";
1417 return out.toString();
1421 * generate a gff file for sequence features includes non-pos features by
1428 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible)
1430 return printGFFFormat(seqs, visible, true, true);
1433 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible,
1434 boolean visOnly, boolean nonpos)
1436 StringBuffer out = new StringBuffer();
1437 SequenceFeature[] next;
1440 for (int i = 0; i < seqs.length; i++)
1442 if (seqs[i].getSequenceFeatures() != null)
1444 next = seqs[i].getSequenceFeatures();
1445 for (int j = 0; j < next.length; j++)
1447 isnonpos = next[j].begin == 0 && next[j].end == 0;
1448 if ((!nonpos && isnonpos)
1449 || (!isnonpos && visOnly && !visible
1450 .containsKey(next[j].type)))
1455 source = next[j].featureGroup;
1458 source = next[j].getDescription();
1461 out.append(seqs[i].getName());
1465 out.append(next[j].type);
1467 out.append(next[j].begin);
1469 out.append(next[j].end);
1471 out.append(next[j].score);
1474 if (next[j].getValue("STRAND") != null)
1476 out.append(next[j].getValue("STRAND"));
1484 if (next[j].getValue("FRAME") != null)
1486 out.append(next[j].getValue("FRAME"));
1492 // TODO: verify/check GFF - should there be a /t here before attribute
1495 if (next[j].getValue("ATTRIBUTES") != null)
1497 out.append(next[j].getValue("ATTRIBUTES"));
1500 out.append(newline);
1506 return out.toString();
1510 * this is only for the benefit of object polymorphism - method does nothing.
1518 * this is only for the benefit of object polymorphism - method does nothing.
1520 * @return error message
1522 public String print()
1524 return "USE printGFFFormat() or printJalviewFormat()";