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.
73 * Creates a new FeaturesFile object.
83 public FeaturesFile(String inFile, String type) throws IOException
88 public FeaturesFile(FileParse source) throws IOException
94 * Parse GFF or sequence features file using case-independent matching,
98 * - alignment/dataset containing sequences that are to be annotated
100 * - hashtable to store feature colour definitions
102 * - process html strings into plain text
103 * @return true if features were added
105 public boolean parse(AlignmentI align, Hashtable colours,
108 return parse(align, colours, null, removeHTML, false);
112 * Parse GFF or sequence features file optionally using case-independent
113 * matching, discarding URLs
116 * - alignment/dataset containing sequences that are to be annotated
118 * - hashtable to store feature colour definitions
120 * - process html strings into plain text
121 * @param relaxedIdmatching
122 * - when true, ID matches to compound sequence IDs are allowed
123 * @return true if features were added
125 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
126 boolean relaxedIdMatching)
128 return parse(align, colours, null, removeHTML, relaxedIdMatching);
132 * Parse GFF or sequence features file optionally using case-independent
136 * - alignment/dataset containing sequences that are to be annotated
138 * - hashtable to store feature colour definitions
140 * - hashtable to store associated URLs
142 * - process html strings into plain text
143 * @return true if features were added
145 public boolean parse(AlignmentI align, Map colours, Map featureLink,
148 return parse(align, colours, featureLink, removeHTML, false);
152 * Parse GFF or sequence features file
155 * - alignment/dataset containing sequences that are to be annotated
157 * - hashtable to store feature colour definitions
159 * - hashtable to store associated URLs
161 * - process html strings into plain text
162 * @param relaxedIdmatching
163 * - when true, ID matches to compound sequence IDs are allowed
164 * @return true if features were added
166 public boolean parse(AlignmentI align, Map colours, Map featureLink,
167 boolean removeHTML, boolean relaxedIdmatching)
173 SequenceI seq = null;
175 * keep track of any sequences we try to create from the data if it is a GFF3 file
177 ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
178 String type, desc, token = null;
180 int index, start, end;
184 String featureGroup = null, groupLink = null;
185 Map typeLink = new Hashtable();
187 * when true, assume GFF style features rather than Jalview style.
189 boolean GFFFile = true;
190 Map<String, String> gffProps = new HashMap<String, String>();
191 while ((line = nextLine()) != null)
193 // skip comments/process pragmas
194 if (line.startsWith("#"))
196 if (line.startsWith("##"))
198 // possibly GFF2/3 version and metadata header
199 processGffPragma(line, gffProps, align, newseqs);
205 st = new StringTokenizer(line, "\t");
206 if (st.countTokens() == 1)
208 if (line.trim().equalsIgnoreCase("GFF"))
210 // Start parsing file as if it might be GFF again.
215 if (st.countTokens() > 1 && st.countTokens() < 4)
218 type = st.nextToken();
219 if (type.equalsIgnoreCase("startgroup"))
221 featureGroup = st.nextToken();
222 if (st.hasMoreElements())
224 groupLink = st.nextToken();
225 featureLink.put(featureGroup, groupLink);
228 else if (type.equalsIgnoreCase("endgroup"))
230 // We should check whether this is the current group,
231 // but at present theres no way of showing more than 1 group
238 Object colour = null;
239 String colscheme = st.nextToken();
240 if (colscheme.indexOf("|") > -1
241 || colscheme.trim().equalsIgnoreCase("label"))
243 // Parse '|' separated graduated colourscheme fields:
244 // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
245 // can either provide 'label' only, first is optional, next two
246 // colors are required (but may be
247 // left blank), next is optional, nxt two min/max are required.
248 // first is either 'label'
249 // first/second and third are both hexadecimal or word equivalent
251 // next two are values parsed as floats.
252 // fifth is either 'above','below', or 'none'.
253 // sixth is a float value and only required when fifth is either
254 // 'above' or 'below'.
255 StringTokenizer gcol = new StringTokenizer(colscheme, "|",
258 int threshtype = AnnotationColourGradient.NO_THRESHOLD;
259 float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
260 boolean labelCol = false;
262 String mincol = gcol.nextToken();
266 .println("Expected either 'label' or a colour specification in the line: "
270 String maxcol = null;
271 if (mincol.toLowerCase().indexOf("label") == 0)
274 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
276 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
278 String abso = null, minval, maxval;
281 // at least four more tokens
282 if (mincol.equals("|"))
288 gcol.nextToken(); // skip next '|'
290 // continue parsing rest of line
291 maxcol = gcol.nextToken();
292 if (maxcol.equals("|"))
298 gcol.nextToken(); // skip next '|'
300 abso = gcol.nextToken();
301 gcol.nextToken(); // skip next '|'
302 if (abso.toLowerCase().indexOf("abso") != 0)
309 minval = gcol.nextToken();
310 gcol.nextToken(); // skip next '|'
312 maxval = gcol.nextToken();
313 if (gcol.hasMoreTokens())
315 gcol.nextToken(); // skip next '|'
319 if (minval.length() > 0)
321 min = new Float(minval).floatValue();
323 } catch (Exception e)
326 .println("Couldn't parse the minimum value for graduated colour for type ("
328 + ") - did you misspell 'auto' for the optional automatic colour switch ?");
333 if (maxval.length() > 0)
335 max = new Float(maxval).floatValue();
337 } catch (Exception e)
340 .println("Couldn't parse the maximum value for graduated colour for type ("
347 // add in some dummy min/max colours for the label-only
354 colour = new jalview.schemes.GraduatedColor(
355 new UserColourScheme(mincol).findColour('A'),
356 new UserColourScheme(maxcol).findColour('A'), min,
358 } catch (Exception e)
361 .println("Couldn't parse the graduated colour scheme ("
367 ((jalview.schemes.GraduatedColor) colour)
368 .setColourByLabel(labelCol);
369 ((jalview.schemes.GraduatedColor) colour)
370 .setAutoScaled(abso == null);
371 // add in any additional parameters
372 String ttype = null, tval = null;
373 if (gcol.hasMoreTokens())
375 // threshold type and possibly a threshold value
376 ttype = gcol.nextToken();
377 if (ttype.toLowerCase().startsWith("below"))
379 ((jalview.schemes.GraduatedColor) colour)
380 .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
382 else if (ttype.toLowerCase().startsWith("above"))
384 ((jalview.schemes.GraduatedColor) colour)
385 .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
389 ((jalview.schemes.GraduatedColor) colour)
390 .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
391 if (!ttype.toLowerCase().startsWith("no"))
394 .println("Ignoring unrecognised threshold type : "
399 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
404 tval = gcol.nextToken();
405 ((jalview.schemes.GraduatedColor) colour)
406 .setThresh(new Float(tval).floatValue());
407 } catch (Exception e)
410 .println("Couldn't parse threshold value as a float: ("
415 // parse the thresh-is-min token ?
416 if (gcol.hasMoreTokens())
419 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
420 while (gcol.hasMoreTokens())
422 System.err.println("|" + gcol.nextToken());
424 System.err.println("\n");
430 UserColourScheme ucs = new UserColourScheme(colscheme);
431 colour = ucs.findColour('A');
435 colours.put(type, colour);
437 if (st.hasMoreElements())
439 String link = st.nextToken();
440 typeLink.put(type, link);
441 if (featureLink == null)
443 featureLink = new Hashtable();
445 featureLink.put(type, link);
451 while (st.hasMoreElements())
456 // Still possible this is an old Jalview file,
457 // which does not have type colours at the beginning
458 seqId = token = st.nextToken();
459 seq = findName(align, seqId, relaxedIdmatching, newseqs);
462 desc = st.nextToken();
464 if (doGffSource && desc.indexOf(' ') == -1)
466 // could also be a source term rather than description line
467 group = new String(desc);
469 type = st.nextToken();
472 String stt = st.nextToken();
473 if (stt.length() == 0 || stt.equals("-"))
479 start = Integer.parseInt(stt);
481 } catch (NumberFormatException ex)
487 String stt = st.nextToken();
488 if (stt.length() == 0 || stt.equals("-"))
494 end = Integer.parseInt(stt);
496 } catch (NumberFormatException ex)
500 // TODO: decide if non positional feature assertion for input data
501 // where end==0 is generally valid
504 // treat as non-positional feature, regardless.
509 score = new Float(st.nextToken()).floatValue();
510 } catch (NumberFormatException ex)
515 sf = new SequenceFeature(type, desc, start, end, score, group);
519 sf.setValue("STRAND", st.nextToken());
520 sf.setValue("FRAME", st.nextToken());
521 } catch (Exception ex)
525 if (st.hasMoreTokens())
527 StringBuffer attributes = new StringBuffer();
529 while (st.hasMoreTokens())
531 attributes.append((sep ? "\t" : "") + st.nextElement());
534 // TODO validate and split GFF2 attributes field ? parse out
535 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
536 // sf.setValue(attrib, val);
537 sf.setValue("ATTRIBUTES", attributes.toString());
540 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
543 // check whether we should add the sequence feature to any other
544 // sequences in the alignment with the same or similar
545 while ((seq = align.findName(seq, seqId, true)) != null)
547 seq.addSequenceFeature(new SequenceFeature(sf));
554 if (GFFFile && seq == null)
560 desc = st.nextToken();
562 if (!st.hasMoreTokens())
565 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
566 // in all probability, this isn't a file we understand, so bail
571 token = st.nextToken();
573 if (!token.equals("ID_NOT_SPECIFIED"))
575 seq = findName(align, seqId = token, relaxedIdmatching, null);
583 index = Integer.parseInt(st.nextToken());
584 seq = align.getSequenceAt(index);
585 } catch (NumberFormatException ex)
593 System.out.println("Sequence not found: " + line);
597 start = Integer.parseInt(st.nextToken());
598 end = Integer.parseInt(st.nextToken());
600 type = st.nextToken();
602 if (!colours.containsKey(type))
604 // Probably the old style groups file
605 UserColourScheme ucs = new UserColourScheme(type);
606 colours.put(type, ucs.findColour('A'));
608 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
609 if (st.hasMoreTokens())
613 score = new Float(st.nextToken()).floatValue();
614 // update colourgradient bounds if allowed to
615 } catch (NumberFormatException ex)
621 if (groupLink != null && removeHTML)
623 sf.addLink(groupLink);
624 sf.description += "%LINK%";
626 if (typeLink.containsKey(type) && removeHTML)
628 sf.addLink(typeLink.get(type).toString());
629 sf.description += "%LINK%";
632 parseDescriptionHTML(sf, removeHTML);
634 seq.addSequenceFeature(sf);
637 && (seq = align.findName(seq, seqId, false)) != null)
639 seq.addSequenceFeature(new SequenceFeature(sf));
641 // If we got here, its not a GFFFile
646 } catch (Exception ex)
648 // should report somewhere useful for UI if necessary
649 warningMessage = ((warningMessage == null) ? "" : warningMessage)
650 + "Parsing error at\n" + line;
651 System.out.println("Error parsing feature file: " + ex + "\n" + line);
652 ex.printStackTrace(System.err);
660 private enum GffPragmas
662 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
665 private static Map<String, GffPragmas> GFFPRAGMA;
668 GFFPRAGMA = new HashMap<String, GffPragmas>();
669 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
670 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
671 GFFPRAGMA.put("#", GffPragmas.hash);
672 GFFPRAGMA.put("fasta", GffPragmas.fasta);
673 GFFPRAGMA.put("species-build", GffPragmas.species_build);
674 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
675 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
678 private void processGffPragma(String line, Map<String, String> gffProps,
679 AlignmentI align, ArrayList<SequenceI> newseqs)
682 // line starts with ##
683 int spacepos = line.indexOf(' ');
684 String pragma = spacepos == -1 ? line.substring(2).trim() : line
685 .substring(2, spacepos);
686 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
687 if (gffpragma == null)
696 gffversion = Integer.parseInt(line.substring(spacepos + 1));
702 case feature_ontology:
703 // resolve against specific feature ontology
705 case attribute_ontology:
706 // resolve against specific attribute ontology
708 case source_ontology:
709 // resolve against specific source ontology
712 // resolve against specific NCBI taxon version
715 // close off any open feature hierarchies
718 // process the rest of the file as a fasta file and replace any dummy
720 process_as_fasta(align, newseqs);
724 System.err.println("Ignoring unknown pragma:\n" + line);
728 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
734 } catch (IOException q)
737 FastaFile parser = new FastaFile(this);
738 List<SequenceI> includedseqs = parser.getSeqs();
739 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
740 // iterate over includedseqs, and replacing matching ones with newseqs
741 // sequences. Generic iterator not used here because we modify includedseqs
743 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
745 // search for any dummy seqs that this sequence can be used to update
746 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
747 if (dummyseq != null)
749 // dummyseq was created so it could be annotated and referred to in
750 // alignments/codon mappings
752 SequenceI mseq = includedseqs.get(p);
753 // mseq is the 'template' imported from the FASTA file which we'll use
754 // to coomplete dummyseq
755 if (dummyseq instanceof SequenceDummy)
757 // probably have the pattern wrong
758 // idea is that a flyweight proxy for a sequence ID can be created for
759 // 1. stable reference creation
760 // 2. addition of annotation
761 // 3. future replacement by a real sequence
762 // current pattern is to create SequenceDummy objects - a convenience
763 // constructor for a Sequence.
764 // problem is that when promoted to a real sequence, all references
766 // to be updated somehow.
767 ((SequenceDummy) dummyseq).become(mseq);
768 includedseqs.set(p, dummyseq); // template is no longer needed
772 // finally add sequences to the dataset
773 for (SequenceI seq : includedseqs)
775 align.addSequence(seq);
780 * take a sequence feature and examine its attributes to decide how it should
781 * be added to a sequence
784 * - the destination sequence constructed or discovered in the
787 * - the base feature with ATTRIBUTES property containing any
788 * additional attributes
790 * - true if we are processing a GFF annotation file
791 * @return true if sf was actually added to the sequence, false if it was
792 * processed in another way
794 public boolean processOrAddSeqFeature(AlignmentI align, List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
795 boolean gFFFile, boolean relaxedIdMatching)
797 String attr = (String) sf.getValue("ATTRIBUTES");
799 if (gFFFile && attr != null)
803 for (String attset : attr.split("\t"))
805 if (attset==null || attset.trim().length()==0)
810 Map<String, List<String>> set = new HashMap<String, List<String>>();
811 // normally, only expect one column - 9 - in this field
812 // the attributes (Gff3) or groups (gff2) field
813 for (String pair : attset.trim().split(";"))
816 if (pair.length() == 0)
821 // expect either space seperated (gff2) or '=' separated (gff3)
822 // key/value pairs here
824 int eqpos = pair.indexOf('='),sppos = pair.indexOf(' ');
825 String key = null, value = null;
827 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
829 key = pair.substring(0, sppos);
830 value = pair.substring(sppos + 1);
832 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
834 key = pair.substring(0, eqpos);
835 value = pair.substring(eqpos + 1);
843 List<String> vals = set.get(key);
846 vals = new ArrayList<String>();
851 vals.add(value.trim());
857 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
858 relaxedIdMatching); // process decides if
859 // feature is actually
861 } catch (InvalidGFF3FieldException ivfe)
863 System.err.println(ivfe);
869 seq.addSequenceFeature(sf);
874 public class InvalidGFF3FieldException extends Exception
878 public InvalidGFF3FieldException(String field,
879 Map<String, List<String>> set, String message)
881 super(message + " (Field was " + field + " and value was "
882 + set.get(field).toString());
884 this.value = set.get(field).toString();
890 * take a set of keys for a feature and interpret them
898 public boolean processGffKey(Map<String, List<String>> set, int nattr,
899 SequenceI seq, SequenceFeature sf, AlignmentI align,
900 List<SequenceI> newseqs, boolean relaxedIdMatching)
901 throws InvalidGFF3FieldException
904 // decide how to interpret according to type
905 if (sf.getType().equals("similarity"))
907 int strand = sf.getStrand();
908 // exonerate cdna/protein map
910 List<SequenceI> querySeq = findNames(align, newseqs,
911 relaxedIdMatching, set.get(attr="Query"));
912 if (querySeq==null || querySeq.size()!=1)
914 throw new InvalidGFF3FieldException( attr, set,
915 "Expecting exactly one sequence in Query field (got "
916 + set.get(attr) + ")");
918 if (set.containsKey(attr="Align"))
920 // process the align maps and create cdna/protein maps
921 // ideally, the query sequences are in the alignment, but maybe not...
923 AlignedCodonFrame alco = new AlignedCodonFrame();
924 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
927 // add codon mapping, and hope!
928 alco.addMap(seq, querySeq.get(0), codonmapping);
929 align.addCodonFrame(alco);
930 // everything that's needed to be done is done
931 // no features to create here !
939 private MapList constructCodonMappingFromAlign(
940 Map<String, List<String>> set,
941 String attr, int strand) throws InvalidGFF3FieldException
945 throw new InvalidGFF3FieldException(attr, set,
946 "Invalid strand for a codon mapping (cannot be 0)");
948 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
949 int lastppos = 0, lastpframe = 0;
950 for (String range : set.get(attr))
952 List<Integer> ints = new ArrayList<Integer>();
953 StringTokenizer st = new StringTokenizer(range, " ");
954 while (st.hasMoreTokens())
956 String num = st.nextToken();
959 ints.add(new Integer(num));
960 } catch (NumberFormatException nfe)
962 throw new InvalidGFF3FieldException(attr, set,
963 "Invalid number in field " + num);
966 // Align positionInRef positionInQuery LengthInRef
967 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
968 // 3652 - . alignment_id 0 ;
969 // Query DDB_G0269124
970 // Align 11270 143 120
971 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
972 // dna in strand direction
973 // Align 11150 187 282
974 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
975 // dna in strand direction
977 // Align 10865 281 888
978 // Align 9977 578 1068
979 // Align 8909 935 375
981 if (ints.size() != 3)
983 throw new InvalidGFF3FieldException(attr, set,
984 "Invalid number of fields for this attribute ("
985 + ints.size() + ")");
987 fromrange.add(new Integer(ints.get(0).intValue()));
988 fromrange.add(new Integer(ints.get(0).intValue() + strand
989 * ints.get(2).intValue()));
990 // how are intron/exon boundaries that do not align in codons
992 if (ints.get(1).equals(lastppos) && lastpframe > 0)
994 // extend existing to map
995 lastppos += ints.get(2) / 3;
996 lastpframe = ints.get(2) % 3;
997 torange.set(torange.size() - 1, new Integer(lastppos));
1002 torange.add(ints.get(1));
1003 lastppos = ints.get(1) + ints.get(2) / 3;
1004 lastpframe = ints.get(2) % 3;
1005 torange.add(new Integer(lastppos));
1008 // from and to ranges must end up being a series of start/end intervals
1009 if (fromrange.size() % 2 == 1)
1011 throw new InvalidGFF3FieldException(attr, set,
1012 "Couldn't parse the DNA alignment range correctly");
1014 if (torange.size() % 2 == 1)
1016 throw new InvalidGFF3FieldException(attr, set,
1017 "Couldn't parse the protein alignment range correctly");
1019 // finally, build the map
1020 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1023 for (Integer ip : fromrange)
1025 frommap[p++] = ip.intValue();
1028 for (Integer ip : torange)
1030 tomap[p++] = ip.intValue();
1033 return new MapList(frommap, tomap, 3, 1);
1036 private List<SequenceI> findNames(AlignmentI align,
1037 List<SequenceI> newseqs, boolean relaxedIdMatching,
1040 List<SequenceI> found = new ArrayList<SequenceI>();
1041 for (String seqId : list)
1043 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1052 private AlignmentI lastmatchedAl = null;
1054 private SequenceIdMatcher matcher = null;
1057 * clear any temporary handles used to speed up ID matching
1059 private void resetMatcher()
1061 lastmatchedAl = null;
1065 private SequenceI findName(AlignmentI align, String seqId,
1066 boolean relaxedIdMatching, List<SequenceI> newseqs)
1068 SequenceI match = null;
1069 if (relaxedIdMatching)
1071 if (lastmatchedAl != align)
1073 matcher = new SequenceIdMatcher(
1074 (lastmatchedAl = align).getSequencesArray());
1075 if (newseqs != null)
1077 matcher.addAll(newseqs);
1080 match = matcher.findIdMatch(seqId);
1084 match = align.findName(seqId, true);
1085 if (match == null && newseqs != null)
1087 for (SequenceI m : newseqs)
1089 if (seqId.equals(m.getName()))
1097 if (match==null && newseqs!=null)
1099 match = new SequenceDummy(seqId);
1100 if (relaxedIdMatching)
1102 matcher.addAll(Arrays.asList(new SequenceI[]
1105 // add dummy sequence to the newseqs list
1110 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1112 if (sf.getDescription() == null)
1116 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1117 sf.getDescription(), removeHTML, newline);
1119 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1121 for (String link : parsed.getLinks())
1129 * generate a features file for seqs includes non-pos features by default.
1132 * source of sequence features
1134 * hash of feature types and colours
1135 * @return features file contents
1137 public String printJalviewFormat(SequenceI[] seqs, Map<String,Object> visible)
1139 return printJalviewFormat(seqs, visible, true, true);
1143 * generate a features file for seqs with colours from visible (if any)
1146 * source of features
1148 * hash of Colours for each feature type
1150 * when true only feature types in 'visible' will be output
1152 * indicates if non-positional features should be output (regardless
1154 * @return features file contents
1156 public String printJalviewFormat(SequenceI[] seqs, Map visible,
1157 boolean visOnly, boolean nonpos)
1159 StringBuffer out = new StringBuffer();
1160 SequenceFeature[] next;
1161 boolean featuresGen = false;
1162 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1164 // no point continuing.
1165 return "No Features Visible";
1168 if (visible != null && visOnly)
1170 // write feature colours only if we're given them and we are generating
1172 // TODO: decide if feature links should also be written here ?
1173 Iterator en = visible.keySet().iterator();
1175 while (en.hasNext())
1177 type = en.next().toString();
1179 if (visible.get(type) instanceof GraduatedColor)
1181 GraduatedColor gc = (GraduatedColor) visible.get(type);
1182 color = (gc.isColourByLabel() ? "label|" : "")
1183 + Format.getHexString(gc.getMinColor()) + "|"
1184 + Format.getHexString(gc.getMaxColor())
1185 + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1186 + gc.getMax() + "|";
1187 if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1189 if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1195 if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1197 System.err.println("WARNING: Unsupported threshold type ("
1198 + gc.getThreshType() + ") : Assuming 'above'");
1203 color += "|" + gc.getThresh();
1210 else if (visible.get(type) instanceof java.awt.Color)
1212 color = Format.getHexString((java.awt.Color) visible.get(type));
1216 // legacy support for integer objects containing colour triplet values
1217 color = Format.getHexString(new java.awt.Color(Integer
1218 .parseInt(visible.get(type).toString())));
1223 out.append(newline);
1226 // Work out which groups are both present and visible
1227 Vector groups = new Vector();
1229 boolean isnonpos = false;
1231 for (int i = 0; i < seqs.length; i++)
1233 next = seqs[i].getSequenceFeatures();
1236 for (int j = 0; j < next.length; j++)
1238 isnonpos = next[j].begin == 0 && next[j].end == 0;
1239 if ((!nonpos && isnonpos)
1240 || (!isnonpos && visOnly && !visible
1241 .containsKey(next[j].type)))
1246 if (next[j].featureGroup != null
1247 && !groups.contains(next[j].featureGroup))
1249 groups.addElement(next[j].featureGroup);
1255 String group = null;
1259 if (groups.size() > 0 && groupIndex < groups.size())
1261 group = groups.elementAt(groupIndex).toString();
1262 out.append(newline);
1263 out.append("STARTGROUP\t");
1265 out.append(newline);
1272 for (int i = 0; i < seqs.length; i++)
1274 next = seqs[i].getSequenceFeatures();
1277 for (int j = 0; j < next.length; j++)
1279 isnonpos = next[j].begin == 0 && next[j].end == 0;
1280 if ((!nonpos && isnonpos)
1281 || (!isnonpos && visOnly && !visible
1282 .containsKey(next[j].type)))
1284 // skip if feature is nonpos and we ignore them or if we only
1285 // output visible and it isn't non-pos and it's not visible
1290 && (next[j].featureGroup == null || !next[j].featureGroup
1296 if (group == null && next[j].featureGroup != null)
1300 // we have features to output
1302 if (next[j].description == null
1303 || next[j].description.equals(""))
1305 out.append(next[j].type + "\t");
1309 if (next[j].links != null
1310 && next[j].getDescription().indexOf("<html>") == -1)
1312 out.append("<html>");
1315 out.append(next[j].description + " ");
1316 if (next[j].links != null)
1318 for (int l = 0; l < next[j].links.size(); l++)
1320 String label = next[j].links.elementAt(l).toString();
1321 String href = label.substring(label.indexOf("|") + 1);
1322 label = label.substring(0, label.indexOf("|"));
1324 if (next[j].description.indexOf(href) == -1)
1326 out.append("<a href=\"" + href + "\">" + label + "</a>");
1330 if (next[j].getDescription().indexOf("</html>") == -1)
1332 out.append("</html>");
1338 out.append(seqs[i].getName());
1339 out.append("\t-1\t");
1340 out.append(next[j].begin);
1342 out.append(next[j].end);
1344 out.append(next[j].type);
1345 if (next[j].score != Float.NaN)
1348 out.append(next[j].score);
1350 out.append(newline);
1357 out.append("ENDGROUP\t");
1359 out.append(newline);
1367 } while (groupIndex < groups.size() + 1);
1371 return "No Features Visible";
1374 return out.toString();
1378 * generate a gff file for sequence features includes non-pos features by
1385 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible)
1387 return printGFFFormat(seqs, visible, true, true);
1390 public String printGFFFormat(SequenceI[] seqs, Map<String,Object> visible,
1391 boolean visOnly, boolean nonpos)
1393 StringBuffer out = new StringBuffer();
1394 SequenceFeature[] next;
1397 for (int i = 0; i < seqs.length; i++)
1399 if (seqs[i].getSequenceFeatures() != null)
1401 next = seqs[i].getSequenceFeatures();
1402 for (int j = 0; j < next.length; j++)
1404 isnonpos = next[j].begin == 0 && next[j].end == 0;
1405 if ((!nonpos && isnonpos)
1406 || (!isnonpos && visOnly && !visible
1407 .containsKey(next[j].type)))
1412 source = next[j].featureGroup;
1415 source = next[j].getDescription();
1418 out.append(seqs[i].getName());
1422 out.append(next[j].type);
1424 out.append(next[j].begin);
1426 out.append(next[j].end);
1428 out.append(next[j].score);
1431 if (next[j].getValue("STRAND") != null)
1433 out.append(next[j].getValue("STRAND"));
1441 if (next[j].getValue("FRAME") != null)
1443 out.append(next[j].getValue("FRAME"));
1449 // TODO: verify/check GFF - should there be a /t here before attribute
1452 if (next[j].getValue("ATTRIBUTES") != null)
1454 out.append(next[j].getValue("ATTRIBUTES"));
1457 out.append(newline);
1463 return out.toString();
1467 * this is only for the benefit of object polymorphism - method does nothing.
1475 * this is only for the benefit of object polymorphism - method does nothing.
1477 * @return error message
1479 public String print()
1481 return "USE printGFFFormat() or printJalviewFormat()";