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.api.FeatureColourI;
25 import jalview.datamodel.AlignedCodonFrame;
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.FeatureColour;
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, Map colours, boolean removeHTML)
129 return parse(align, colours, null, removeHTML, false);
133 * Parse GFF or sequence features file optionally using case-independent
134 * matching, discarding URLs
137 * - alignment/dataset containing sequences that are to be annotated
139 * - hashtable to store feature colour definitions
141 * - process html strings into plain text
142 * @param relaxedIdmatching
143 * - when true, ID matches to compound sequence IDs are allowed
144 * @return true if features were added
146 public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
147 boolean relaxedIdMatching)
149 return parse(align, colours, null, removeHTML, relaxedIdMatching);
153 * Parse GFF or sequence features file optionally using case-independent
157 * - alignment/dataset containing sequences that are to be annotated
159 * - hashtable to store feature colour definitions
161 * - hashtable to store associated URLs
163 * - process html strings into plain text
164 * @return true if features were added
166 public boolean parse(AlignmentI align, Map colours, Map featureLink,
169 return parse(align, colours, featureLink, removeHTML, false);
173 public void addAnnotations(AlignmentI al)
175 // TODO Auto-generated method stub
176 super.addAnnotations(al);
180 public void addProperties(AlignmentI al)
182 // TODO Auto-generated method stub
183 super.addProperties(al);
187 public void addSeqGroups(AlignmentI al)
189 // TODO Auto-generated method stub
190 super.addSeqGroups(al);
194 * Parse GFF or sequence features file
197 * - alignment/dataset containing sequences that are to be annotated
199 * - hashtable to store feature colour definitions
201 * - hashtable to store associated URLs
203 * - process html strings into plain text
204 * @param relaxedIdmatching
205 * - when true, ID matches to compound sequence IDs are allowed
206 * @return true if features were added
208 public boolean parse(AlignmentI align, Map colours, Map featureLink,
209 boolean removeHTML, boolean relaxedIdmatching)
215 SequenceI seq = null;
217 * keep track of any sequences we try to create from the data if it is a
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 FeatureColourI 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 FeatureColour(
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 colour.setColourByLabel(labelCol);
411 colour.setAutoScaled(abso == null);
412 // add in any additional parameters
413 String ttype = null, tval = null;
414 if (gcol.hasMoreTokens())
416 // threshold type and possibly a threshold value
417 ttype = gcol.nextToken();
418 if (ttype.toLowerCase().startsWith("below"))
420 colour.setBelowThreshold(true);
422 else if (ttype.toLowerCase().startsWith("above"))
424 colour.setAboveThreshold(true);
428 if (!ttype.toLowerCase().startsWith("no"))
431 .println("Ignoring unrecognised threshold type : "
436 if (colour.hasThreshold())
441 tval = gcol.nextToken();
442 colour.setThreshold(new Float(tval).floatValue());
443 } catch (Exception e)
446 .println("Couldn't parse threshold value as a float: ("
451 // parse the thresh-is-min token ?
452 if (gcol.hasMoreTokens())
455 .println("Ignoring additional tokens in parameters in graduated colour specification\n");
456 while (gcol.hasMoreTokens())
458 System.err.println("|" + gcol.nextToken());
460 System.err.println("\n");
466 UserColourScheme ucs = new UserColourScheme(colscheme);
467 colour = new FeatureColour(ucs.findColour('A'));
471 colours.put(type, colour);
473 if (st.hasMoreElements())
475 String link = st.nextToken();
476 typeLink.put(type, link);
477 if (featureLink == null)
479 featureLink = new Hashtable();
481 featureLink.put(type, link);
487 while (st.hasMoreElements())
492 // Still possible this is an old Jalview file,
493 // which does not have type colours at the beginning
494 seqId = token = st.nextToken();
495 seq = findName(align, seqId, relaxedIdmatching, newseqs);
498 desc = st.nextToken();
500 if (doGffSource && desc.indexOf(' ') == -1)
502 // could also be a source term rather than description line
503 group = new String(desc);
505 type = st.nextToken();
508 String stt = st.nextToken();
509 if (stt.length() == 0 || stt.equals("-"))
515 start = Integer.parseInt(stt);
517 } catch (NumberFormatException ex)
523 String stt = st.nextToken();
524 if (stt.length() == 0 || stt.equals("-"))
530 end = Integer.parseInt(stt);
532 } catch (NumberFormatException ex)
536 // TODO: decide if non positional feature assertion for input data
537 // where end==0 is generally valid
540 // treat as non-positional feature, regardless.
545 score = new Float(st.nextToken()).floatValue();
546 } catch (NumberFormatException ex)
551 sf = new SequenceFeature(type, desc, start, end, score, group);
555 sf.setValue("STRAND", st.nextToken());
556 sf.setValue("FRAME", st.nextToken());
557 } catch (Exception ex)
561 if (st.hasMoreTokens())
563 StringBuffer attributes = new StringBuffer();
565 while (st.hasMoreTokens())
567 attributes.append((sep ? "\t" : "") + st.nextElement());
570 // TODO validate and split GFF2 attributes field ? parse out
571 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
572 // sf.setValue(attrib, val);
573 sf.setValue("ATTRIBUTES", attributes.toString());
576 if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
579 // check whether we should add the sequence feature to any other
580 // sequences in the alignment with the same or similar
581 while ((seq = align.findName(seq, seqId, true)) != null)
583 seq.addSequenceFeature(new SequenceFeature(sf));
590 if (GFFFile && seq == null)
596 desc = st.nextToken();
598 if (!st.hasMoreTokens())
601 .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
602 // in all probability, this isn't a file we understand, so bail
607 token = st.nextToken();
609 if (!token.equals("ID_NOT_SPECIFIED"))
611 seq = findName(align, seqId = token, relaxedIdmatching, null);
619 index = Integer.parseInt(st.nextToken());
620 seq = align.getSequenceAt(index);
621 } catch (NumberFormatException ex)
629 System.out.println("Sequence not found: " + line);
633 start = Integer.parseInt(st.nextToken());
634 end = Integer.parseInt(st.nextToken());
636 type = st.nextToken();
638 if (!colours.containsKey(type))
640 // Probably the old style groups file
641 UserColourScheme ucs = new UserColourScheme(type);
642 colours.put(type, ucs.findColour('A'));
644 sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
645 if (st.hasMoreTokens())
649 score = new Float(st.nextToken()).floatValue();
650 // update colourgradient bounds if allowed to
651 } catch (NumberFormatException ex)
657 if (groupLink != null && removeHTML)
659 sf.addLink(groupLink);
660 sf.description += "%LINK%";
662 if (typeLink.containsKey(type) && removeHTML)
664 sf.addLink(typeLink.get(type).toString());
665 sf.description += "%LINK%";
668 parseDescriptionHTML(sf, removeHTML);
670 seq.addSequenceFeature(sf);
673 && (seq = align.findName(seq, seqId, false)) != null)
675 seq.addSequenceFeature(new SequenceFeature(sf));
677 // If we got here, its not a GFFFile
682 } catch (Exception ex)
684 // should report somewhere useful for UI if necessary
685 warningMessage = ((warningMessage == null) ? "" : warningMessage)
686 + "Parsing error at\n" + line;
687 System.out.println("Error parsing feature file: " + ex + "\n" + line);
688 ex.printStackTrace(System.err);
696 private enum GffPragmas
698 gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
701 private static Map<String, GffPragmas> GFFPRAGMA;
704 GFFPRAGMA = new HashMap<String, GffPragmas>();
705 GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
706 GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
707 GFFPRAGMA.put("#", GffPragmas.hash);
708 GFFPRAGMA.put("fasta", GffPragmas.fasta);
709 GFFPRAGMA.put("species-build", GffPragmas.species_build);
710 GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
711 GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
714 private void processGffPragma(String line, Map<String, String> gffProps,
715 AlignmentI align, ArrayList<SequenceI> newseqs)
718 // line starts with ##
719 int spacepos = line.indexOf(' ');
720 String pragma = spacepos == -1 ? line.substring(2).trim() : line
721 .substring(2, spacepos);
722 GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
723 if (gffpragma == null)
732 gffversion = Integer.parseInt(line.substring(spacepos + 1));
738 case feature_ontology:
739 // resolve against specific feature ontology
741 case attribute_ontology:
742 // resolve against specific attribute ontology
744 case source_ontology:
745 // resolve against specific source ontology
748 // resolve against specific NCBI taxon version
751 // close off any open feature hierarchies
754 // process the rest of the file as a fasta file and replace any dummy
756 process_as_fasta(align, newseqs);
760 System.err.println("Ignoring unknown pragma:\n" + line);
764 private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
770 } catch (IOException q)
773 FastaFile parser = new FastaFile(this);
774 List<SequenceI> includedseqs = parser.getSeqs();
775 SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
776 // iterate over includedseqs, and replacing matching ones with newseqs
777 // sequences. Generic iterator not used here because we modify includedseqs
779 for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
781 // search for any dummy seqs that this sequence can be used to update
782 SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
783 if (dummyseq != null)
785 // dummyseq was created so it could be annotated and referred to in
786 // alignments/codon mappings
788 SequenceI mseq = includedseqs.get(p);
789 // mseq is the 'template' imported from the FASTA file which we'll use
790 // to coomplete dummyseq
791 if (dummyseq instanceof SequenceDummy)
793 // probably have the pattern wrong
794 // idea is that a flyweight proxy for a sequence ID can be created for
795 // 1. stable reference creation
796 // 2. addition of annotation
797 // 3. future replacement by a real sequence
798 // current pattern is to create SequenceDummy objects - a convenience
799 // constructor for a Sequence.
800 // problem is that when promoted to a real sequence, all references
802 // to be updated somehow.
803 ((SequenceDummy) dummyseq).become(mseq);
804 includedseqs.set(p, dummyseq); // template is no longer needed
808 // finally add sequences to the dataset
809 for (SequenceI seq : includedseqs)
811 align.addSequence(seq);
816 * take a sequence feature and examine its attributes to decide how it should
817 * be added to a sequence
820 * - the destination sequence constructed or discovered in the
823 * - the base feature with ATTRIBUTES property containing any
824 * additional attributes
826 * - true if we are processing a GFF annotation file
827 * @return true if sf was actually added to the sequence, false if it was
828 * processed in another way
830 public boolean processOrAddSeqFeature(AlignmentI align,
831 List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
832 boolean gFFFile, boolean relaxedIdMatching)
834 String attr = (String) sf.getValue("ATTRIBUTES");
836 if (gFFFile && attr != null)
840 for (String attset : attr.split("\t"))
842 if (attset == null || attset.trim().length() == 0)
847 Map<String, List<String>> set = new HashMap<String, List<String>>();
848 // normally, only expect one column - 9 - in this field
849 // the attributes (Gff3) or groups (gff2) field
850 for (String pair : attset.trim().split(";"))
853 if (pair.length() == 0)
858 // expect either space seperated (gff2) or '=' separated (gff3)
859 // key/value pairs here
861 int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
862 String key = null, value = null;
864 if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
866 key = pair.substring(0, sppos);
867 value = pair.substring(sppos + 1);
871 if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
873 key = pair.substring(0, eqpos);
874 value = pair.substring(eqpos + 1);
883 List<String> vals = set.get(key);
886 vals = new ArrayList<String>();
891 vals.add(value.trim());
897 add &= processGffKey(set, nattr, seq, sf, align, newseqs,
898 relaxedIdMatching); // process decides if
899 // feature is actually
901 } catch (InvalidGFF3FieldException ivfe)
903 System.err.println(ivfe);
909 seq.addSequenceFeature(sf);
914 public class InvalidGFF3FieldException extends Exception
918 public InvalidGFF3FieldException(String field,
919 Map<String, List<String>> set, String message)
921 super(message + " (Field was " + field + " and value was "
922 + set.get(field).toString());
924 this.value = set.get(field).toString();
930 * take a set of keys for a feature and interpret them
938 public boolean processGffKey(Map<String, List<String>> set, int nattr,
939 SequenceI seq, SequenceFeature sf, AlignmentI align,
940 List<SequenceI> newseqs, boolean relaxedIdMatching)
941 throws InvalidGFF3FieldException
944 // decide how to interpret according to type
945 if (sf.getType().equals("similarity"))
947 int strand = sf.getStrand();
948 // exonerate cdna/protein map
950 List<SequenceI> querySeq = findNames(align, newseqs,
951 relaxedIdMatching, set.get(attr = "Query"));
952 if (querySeq == null || querySeq.size() != 1)
954 throw new InvalidGFF3FieldException(attr, set,
955 "Expecting exactly one sequence in Query field (got "
956 + set.get(attr) + ")");
958 if (set.containsKey(attr = "Align"))
960 // process the align maps and create cdna/protein maps
961 // ideally, the query sequences are in the alignment, but maybe not...
963 AlignedCodonFrame alco = new AlignedCodonFrame();
964 MapList codonmapping = constructCodonMappingFromAlign(set, attr,
967 // add codon mapping, and hope!
968 alco.addMap(seq, querySeq.get(0), codonmapping);
969 align.addCodonFrame(alco);
970 // everything that's needed to be done is done
971 // no features to create here !
979 private MapList constructCodonMappingFromAlign(
980 Map<String, List<String>> set, String attr, int strand)
981 throws InvalidGFF3FieldException
985 throw new InvalidGFF3FieldException(attr, set,
986 "Invalid strand for a codon mapping (cannot be 0)");
988 List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
989 int lastppos = 0, lastpframe = 0;
990 for (String range : set.get(attr))
992 List<Integer> ints = new ArrayList<Integer>();
993 StringTokenizer st = new StringTokenizer(range, " ");
994 while (st.hasMoreTokens())
996 String num = st.nextToken();
999 ints.add(new Integer(num));
1000 } catch (NumberFormatException nfe)
1002 throw new InvalidGFF3FieldException(attr, set,
1003 "Invalid number in field " + num);
1006 // Align positionInRef positionInQuery LengthInRef
1007 // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1008 // 3652 - . alignment_id 0 ;
1009 // Query DDB_G0269124
1010 // Align 11270 143 120
1011 // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1012 // dna in strand direction
1013 // Align 11150 187 282
1014 // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1015 // dna in strand direction
1017 // Align 10865 281 888
1018 // Align 9977 578 1068
1019 // Align 8909 935 375
1021 if (ints.size() != 3)
1023 throw new InvalidGFF3FieldException(attr, set,
1024 "Invalid number of fields for this attribute ("
1025 + ints.size() + ")");
1027 fromrange.add(new Integer(ints.get(0).intValue()));
1028 fromrange.add(new Integer(ints.get(0).intValue() + strand
1029 * ints.get(2).intValue()));
1030 // how are intron/exon boundaries that do not align in codons
1032 if (ints.get(1).equals(lastppos) && lastpframe > 0)
1034 // extend existing to map
1035 lastppos += ints.get(2) / 3;
1036 lastpframe = ints.get(2) % 3;
1037 torange.set(torange.size() - 1, new Integer(lastppos));
1042 torange.add(ints.get(1));
1043 lastppos = ints.get(1) + ints.get(2) / 3;
1044 lastpframe = ints.get(2) % 3;
1045 torange.add(new Integer(lastppos));
1048 // from and to ranges must end up being a series of start/end intervals
1049 if (fromrange.size() % 2 == 1)
1051 throw new InvalidGFF3FieldException(attr, set,
1052 "Couldn't parse the DNA alignment range correctly");
1054 if (torange.size() % 2 == 1)
1056 throw new InvalidGFF3FieldException(attr, set,
1057 "Couldn't parse the protein alignment range correctly");
1059 // finally, build the map
1060 int[] frommap = new int[fromrange.size()], tomap = new int[torange
1063 for (Integer ip : fromrange)
1065 frommap[p++] = ip.intValue();
1068 for (Integer ip : torange)
1070 tomap[p++] = ip.intValue();
1073 return new MapList(frommap, tomap, 3, 1);
1076 private List<SequenceI> findNames(AlignmentI align,
1077 List<SequenceI> newseqs, boolean relaxedIdMatching,
1080 List<SequenceI> found = new ArrayList<SequenceI>();
1081 for (String seqId : list)
1083 SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1092 private AlignmentI lastmatchedAl = null;
1094 private SequenceIdMatcher matcher = null;
1097 * clear any temporary handles used to speed up ID matching
1099 private void resetMatcher()
1101 lastmatchedAl = null;
1105 private SequenceI findName(AlignmentI align, String seqId,
1106 boolean relaxedIdMatching, List<SequenceI> newseqs)
1108 SequenceI match = null;
1109 if (relaxedIdMatching)
1111 if (lastmatchedAl != align)
1113 matcher = new SequenceIdMatcher(
1114 (lastmatchedAl = align).getSequencesArray());
1115 if (newseqs != null)
1117 matcher.addAll(newseqs);
1120 match = matcher.findIdMatch(seqId);
1124 match = align.findName(seqId, true);
1125 if (match == null && newseqs != null)
1127 for (SequenceI m : newseqs)
1129 if (seqId.equals(m.getName()))
1137 if (match == null && newseqs != null)
1139 match = new SequenceDummy(seqId);
1140 if (relaxedIdMatching)
1142 matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1144 // add dummy sequence to the newseqs list
1150 public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1152 if (sf.getDescription() == null)
1156 jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1157 sf.getDescription(), removeHTML, newline);
1159 sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1161 for (String link : parsed.getLinks())
1169 * generate a features file for seqs includes non-pos features by default.
1172 * source of sequence features
1174 * hash of feature types and colours
1175 * @return features file contents
1177 public String printJalviewFormat(SequenceI[] seqs,
1178 Map<String, FeatureColourI> map)
1180 return printJalviewFormat(seqs, map, true, true);
1184 * generate a features file for seqs with colours from visible (if any)
1187 * source of features
1189 * hash of Colours for each feature type
1191 * when true only feature types in 'visible' will be output
1193 * indicates if non-positional features should be output (regardless
1195 * @return features file contents
1197 public String printJalviewFormat(SequenceI[] sequences,
1198 Map<String, FeatureColourI> visible,
1199 boolean visOnly, boolean nonpos)
1201 StringBuffer out = new StringBuffer();
1202 SequenceFeature[] next;
1203 boolean featuresGen = false;
1204 if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1206 // no point continuing.
1207 return "No Features Visible";
1210 if (visible != null && visOnly)
1212 // write feature colours only if we're given them and we are generating
1214 // TODO: decide if feature links should also be written here ?
1215 Iterator<String> en = visible.keySet().iterator();
1216 String feature, color;
1217 while (en.hasNext())
1219 feature = en.next();
1221 FeatureColourI gc = visible.get(feature);
1222 if (!gc.isSimpleColour())
1224 color = (gc.isColourByLabel() ? "label|" : "")
1225 + Format.getHexString(gc.getMinColour()) + "|"
1226 + Format.getHexString(gc.getMaxColour())
1227 + (gc.isAutoScaled() ? "|" : "|abso|") + gc.getMin()
1229 + gc.getMax() + "|";
1230 if (gc.isBelowThreshold())
1232 color += "below|" + gc.getThreshold();
1234 else if (gc.isAboveThreshold())
1236 color += "above|" + gc.getThreshold();
1245 color = Format.getHexString(gc.getColour());
1249 // // legacy support for integer objects containing colour triplet
1251 // color = Format.getHexString(new java.awt.Color(Integer
1252 // .parseInt(visible.get(type).toString())));
1254 out.append(feature);
1257 out.append(newline);
1260 // Work out which groups are both present and visible
1261 Vector groups = new Vector();
1263 boolean isnonpos = false;
1265 for (int i = 0; i < sequences.length; i++)
1267 next = sequences[i].getSequenceFeatures();
1270 for (int j = 0; j < next.length; j++)
1272 isnonpos = next[j].begin == 0 && next[j].end == 0;
1273 if ((!nonpos && isnonpos)
1274 || (!isnonpos && visOnly && !visible
1275 .containsKey(next[j].type)))
1280 if (next[j].featureGroup != null
1281 && !groups.contains(next[j].featureGroup))
1283 groups.addElement(next[j].featureGroup);
1289 String group = null;
1293 if (groups.size() > 0 && groupIndex < groups.size())
1295 group = groups.elementAt(groupIndex).toString();
1296 out.append(newline);
1297 out.append("STARTGROUP\t");
1299 out.append(newline);
1306 for (int i = 0; i < sequences.length; i++)
1308 next = sequences[i].getSequenceFeatures();
1311 for (int j = 0; j < next.length; j++)
1313 isnonpos = next[j].begin == 0 && next[j].end == 0;
1314 if ((!nonpos && isnonpos)
1315 || (!isnonpos && visOnly && !visible
1316 .containsKey(next[j].type)))
1318 // skip if feature is nonpos and we ignore them or if we only
1319 // output visible and it isn't non-pos and it's not visible
1324 && (next[j].featureGroup == null || !next[j].featureGroup
1330 if (group == null && next[j].featureGroup != null)
1334 // we have features to output
1336 if (next[j].description == null
1337 || next[j].description.equals(""))
1339 out.append(next[j].type + "\t");
1343 if (next[j].links != null
1344 && next[j].getDescription().indexOf("<html>") == -1)
1346 out.append("<html>");
1349 out.append(next[j].description + " ");
1350 if (next[j].links != null)
1352 for (int l = 0; l < next[j].links.size(); l++)
1354 String label = next[j].links.elementAt(l).toString();
1355 String href = label.substring(label.indexOf("|") + 1);
1356 label = label.substring(0, label.indexOf("|"));
1358 if (next[j].description.indexOf(href) == -1)
1360 out.append("<a href=\"" + href + "\">" + label + "</a>");
1364 if (next[j].getDescription().indexOf("</html>") == -1)
1366 out.append("</html>");
1372 out.append(sequences[i].getName());
1373 out.append("\t-1\t");
1374 out.append(next[j].begin);
1376 out.append(next[j].end);
1378 out.append(next[j].type);
1379 if (!Float.isNaN(next[j].score))
1382 out.append(next[j].score);
1384 out.append(newline);
1391 out.append("ENDGROUP\t");
1393 out.append(newline);
1401 } while (groupIndex < groups.size() + 1);
1405 return "No Features Visible";
1408 return out.toString();
1412 * generate a gff file for sequence features includes non-pos features by
1419 public String printGFFFormat(SequenceI[] seqs,
1420 Map<String, FeatureColourI> map)
1422 return printGFFFormat(seqs, map, true, true);
1425 public String printGFFFormat(SequenceI[] seqs,
1426 Map<String, FeatureColourI> map, boolean visOnly, boolean nonpos)
1428 StringBuffer out = new StringBuffer();
1429 SequenceFeature[] next;
1432 for (int i = 0; i < seqs.length; i++)
1434 if (seqs[i].getSequenceFeatures() != null)
1436 next = seqs[i].getSequenceFeatures();
1437 for (int j = 0; j < next.length; j++)
1439 isnonpos = next[j].begin == 0 && next[j].end == 0;
1440 if ((!nonpos && isnonpos)
1441 || (!isnonpos && visOnly && !map
1442 .containsKey(next[j].type)))
1447 source = next[j].featureGroup;
1450 source = next[j].getDescription();
1453 out.append(seqs[i].getName());
1457 out.append(next[j].type);
1459 out.append(next[j].begin);
1461 out.append(next[j].end);
1463 out.append(next[j].score);
1466 if (next[j].getValue("STRAND") != null)
1468 out.append(next[j].getValue("STRAND"));
1476 if (next[j].getValue("FRAME") != null)
1478 out.append(next[j].getValue("FRAME"));
1484 // TODO: verify/check GFF - should there be a /t here before attribute
1487 if (next[j].getValue("ATTRIBUTES") != null)
1489 out.append(next[j].getValue("ATTRIBUTES"));
1492 out.append(newline);
1498 return out.toString();
1502 * this is only for the benefit of object polymorphism - method does nothing.
1511 * this is only for the benefit of object polymorphism - method does nothing.
1513 * @return error message
1516 public String print()
1518 return "USE printGFFFormat() or printJalviewFormat()";