Merge branch 'develop' into features/JAL-653_JAL-1766_htslib_refseqsupport
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.io;
22
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;
34
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;
42 import java.util.Map;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
45
46 /**
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.
51  * 
52  * @author AMW
53  * @version $Revision$
54  */
55 public class FeaturesFile extends AlignFile
56 {
57   /**
58    * work around for GFF interpretation bug where source string becomes
59    * description rather than a group
60    */
61   private boolean doGffSource = true;
62
63   private int gffversion;
64
65   /**
66    * Creates a new FeaturesFile object.
67    */
68   public FeaturesFile()
69   {
70   }
71
72   /**
73    * @param inFile
74    * @param type
75    * @throws IOException
76    */
77   public FeaturesFile(String inFile, String type) throws IOException
78   {
79     super(inFile, type);
80   }
81
82   /**
83    * @param source
84    * @throws IOException
85    */
86   public FeaturesFile(FileParse source) throws IOException
87   {
88     super(source);
89   }
90
91   /**
92    * @param parseImmediately
93    * @param source
94    * @throws IOException
95    */
96   public FeaturesFile(boolean parseImmediately, FileParse source)
97           throws IOException
98   {
99     super(parseImmediately, source);
100   }
101
102   /**
103    * @param parseImmediately
104    * @param inFile
105    * @param type
106    * @throws IOException
107    */
108   public FeaturesFile(boolean parseImmediately, String inFile, String type)
109           throws IOException
110   {
111     super(parseImmediately, inFile, type);
112   }
113
114   /**
115    * Parse GFF or sequence features file using case-independent matching,
116    * discarding URLs
117    * 
118    * @param align
119    *          - alignment/dataset containing sequences that are to be annotated
120    * @param colours
121    *          - hashtable to store feature colour definitions
122    * @param removeHTML
123    *          - process html strings into plain text
124    * @return true if features were added
125    */
126   public boolean parse(AlignmentI align, Map colours, boolean removeHTML)
127   {
128     return parse(align, colours, null, removeHTML, false);
129   }
130
131   /**
132    * Parse GFF or sequence features file optionally using case-independent
133    * matching, discarding URLs
134    * 
135    * @param align
136    *          - alignment/dataset containing sequences that are to be annotated
137    * @param colours
138    *          - hashtable to store feature colour definitions
139    * @param removeHTML
140    *          - process html strings into plain text
141    * @param relaxedIdmatching
142    *          - when true, ID matches to compound sequence IDs are allowed
143    * @return true if features were added
144    */
145   public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
146           boolean relaxedIdMatching)
147   {
148     return parse(align, colours, null, removeHTML, relaxedIdMatching);
149   }
150
151   /**
152    * Parse GFF or sequence features file optionally using case-independent
153    * matching
154    * 
155    * @param align
156    *          - alignment/dataset containing sequences that are to be annotated
157    * @param colours
158    *          - hashtable to store feature colour definitions
159    * @param featureLink
160    *          - hashtable to store associated URLs
161    * @param removeHTML
162    *          - process html strings into plain text
163    * @return true if features were added
164    */
165   public boolean parse(AlignmentI align, Map colours, Map featureLink,
166           boolean removeHTML)
167   {
168     return parse(align, colours, featureLink, removeHTML, false);
169   }
170
171   @Override
172   public void addAnnotations(AlignmentI al)
173   {
174     super.addAnnotations(al);
175   }
176
177   @Override
178   public void addProperties(AlignmentI al)
179   {
180     super.addProperties(al);
181   }
182
183   @Override
184   public void addSeqGroups(AlignmentI al)
185   {
186     super.addSeqGroups(al);
187   }
188
189   /**
190    * Parse GFF or sequence features file
191    * 
192    * @param align
193    *          - alignment/dataset containing sequences that are to be annotated
194    * @param colours
195    *          - hashtable to store feature colour definitions
196    * @param featureLink
197    *          - hashtable to store associated URLs
198    * @param removeHTML
199    *          - process html strings into plain text
200    * @param relaxedIdmatching
201    *          - when true, ID matches to compound sequence IDs are allowed
202    * @return true if features were added
203    */
204   public boolean parse(AlignmentI align, Map colours, Map featureLink,
205           boolean removeHTML, boolean relaxedIdmatching)
206   {
207
208     String line = null;
209     try
210     {
211       SequenceI seq = null;
212       /**
213        * keep track of any sequences we try to create from the data if it is a
214        * GFF3 file
215        */
216       ArrayList<SequenceI> newseqs = new ArrayList<SequenceI>();
217       String type, desc, token = null;
218
219       int index, start, end;
220       float score;
221       StringTokenizer st;
222       SequenceFeature sf;
223       String featureGroup = null, groupLink = null;
224       Map typeLink = new Hashtable();
225       /**
226        * when true, assume GFF style features rather than Jalview style.
227        */
228       boolean GFFFile = true;
229       Map<String, String> gffProps = new HashMap<String, String>();
230       while ((line = nextLine()) != null)
231       {
232         // skip comments/process pragmas
233         if (line.startsWith("#"))
234         {
235           if (line.startsWith("##"))
236           {
237             // possibly GFF2/3 version and metadata header
238             processGffPragma(line, gffProps, align, newseqs);
239             line = "";
240           }
241           continue;
242         }
243
244         st = new StringTokenizer(line, "\t");
245         if (st.countTokens() == 1)
246         {
247           if (line.trim().equalsIgnoreCase("GFF"))
248           {
249             // Start parsing file as if it might be GFF again.
250             GFFFile = true;
251             continue;
252           }
253         }
254         if (st.countTokens() > 1 && st.countTokens() < 4)
255         {
256           GFFFile = false;
257           type = st.nextToken();
258           if (type.equalsIgnoreCase("startgroup"))
259           {
260             featureGroup = st.nextToken();
261             if (st.hasMoreElements())
262             {
263               groupLink = st.nextToken();
264               featureLink.put(featureGroup, groupLink);
265             }
266           }
267           else if (type.equalsIgnoreCase("endgroup"))
268           {
269             // We should check whether this is the current group,
270             // but at present theres no way of showing more than 1 group
271             st.nextToken();
272             featureGroup = null;
273             groupLink = null;
274           }
275           else
276           {
277             Object colour = null;
278             String colscheme = st.nextToken();
279             if (colscheme.indexOf("|") > -1
280                     || colscheme.trim().equalsIgnoreCase("label"))
281             {
282               // Parse '|' separated graduated colourscheme fields:
283               // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
284               // can either provide 'label' only, first is optional, next two
285               // colors are required (but may be
286               // left blank), next is optional, nxt two min/max are required.
287               // first is either 'label'
288               // first/second and third are both hexadecimal or word equivalent
289               // colour.
290               // next two are values parsed as floats.
291               // fifth is either 'above','below', or 'none'.
292               // sixth is a float value and only required when fifth is either
293               // 'above' or 'below'.
294               StringTokenizer gcol = new StringTokenizer(colscheme, "|",
295                       true);
296               // set defaults
297               int threshtype = AnnotationColourGradient.NO_THRESHOLD;
298               float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
299               boolean labelCol = false;
300               // Parse spec line
301               String mincol = gcol.nextToken();
302               if (mincol == "|")
303               {
304                 System.err
305                         .println("Expected either 'label' or a colour specification in the line: "
306                                 + line);
307                 continue;
308               }
309               String maxcol = null;
310               if (mincol.toLowerCase().indexOf("label") == 0)
311               {
312                 labelCol = true;
313                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
314                                                                            // '|'
315                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
316               }
317               String abso = null, minval, maxval;
318               if (mincol != null)
319               {
320                 // at least four more tokens
321                 if (mincol.equals("|"))
322                 {
323                   mincol = "";
324                 }
325                 else
326                 {
327                   gcol.nextToken(); // skip next '|'
328                 }
329                 // continue parsing rest of line
330                 maxcol = gcol.nextToken();
331                 if (maxcol.equals("|"))
332                 {
333                   maxcol = "";
334                 }
335                 else
336                 {
337                   gcol.nextToken(); // skip next '|'
338                 }
339                 abso = gcol.nextToken();
340                 gcol.nextToken(); // skip next '|'
341                 if (abso.toLowerCase().indexOf("abso") != 0)
342                 {
343                   minval = abso;
344                   abso = null;
345                 }
346                 else
347                 {
348                   minval = gcol.nextToken();
349                   gcol.nextToken(); // skip next '|'
350                 }
351                 maxval = gcol.nextToken();
352                 if (gcol.hasMoreTokens())
353                 {
354                   gcol.nextToken(); // skip next '|'
355                 }
356                 try
357                 {
358                   if (minval.length() > 0)
359                   {
360                     min = new Float(minval).floatValue();
361                   }
362                 } catch (Exception e)
363                 {
364                   System.err
365                           .println("Couldn't parse the minimum value for graduated colour for type ("
366                                   + colscheme
367                                   + ") - did you misspell 'auto' for the optional automatic colour switch ?");
368                   e.printStackTrace();
369                 }
370                 try
371                 {
372                   if (maxval.length() > 0)
373                   {
374                     max = new Float(maxval).floatValue();
375                   }
376                 } catch (Exception e)
377                 {
378                   System.err
379                           .println("Couldn't parse the maximum value for graduated colour for type ("
380                                   + colscheme + ")");
381                   e.printStackTrace();
382                 }
383               }
384               else
385               {
386                 // add in some dummy min/max colours for the label-only
387                 // colourscheme.
388                 mincol = "FFFFFF";
389                 maxcol = "000000";
390               }
391               try
392               {
393                 colour = new jalview.schemes.GraduatedColor(
394                         new UserColourScheme(mincol).findColour('A'),
395                         new UserColourScheme(maxcol).findColour('A'), min,
396                         max);
397               } catch (Exception e)
398               {
399                 System.err
400                         .println("Couldn't parse the graduated colour scheme ("
401                                 + colscheme + ")");
402                 e.printStackTrace();
403               }
404               if (colour != null)
405               {
406                 ((jalview.schemes.GraduatedColor) colour)
407                         .setColourByLabel(labelCol);
408                 ((jalview.schemes.GraduatedColor) colour)
409                         .setAutoScaled(abso == null);
410                 // add in any additional parameters
411                 String ttype = null, tval = null;
412                 if (gcol.hasMoreTokens())
413                 {
414                   // threshold type and possibly a threshold value
415                   ttype = gcol.nextToken();
416                   if (ttype.toLowerCase().startsWith("below"))
417                   {
418                     ((jalview.schemes.GraduatedColor) colour)
419                             .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
420                   }
421                   else if (ttype.toLowerCase().startsWith("above"))
422                   {
423                     ((jalview.schemes.GraduatedColor) colour)
424                             .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
425                   }
426                   else
427                   {
428                     ((jalview.schemes.GraduatedColor) colour)
429                             .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
430                     if (!ttype.toLowerCase().startsWith("no"))
431                     {
432                       System.err
433                               .println("Ignoring unrecognised threshold type : "
434                                       + ttype);
435                     }
436                   }
437                 }
438                 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
439                 {
440                   try
441                   {
442                     gcol.nextToken();
443                     tval = gcol.nextToken();
444                     ((jalview.schemes.GraduatedColor) colour)
445                             .setThresh(new Float(tval).floatValue());
446                   } catch (Exception e)
447                   {
448                     System.err
449                             .println("Couldn't parse threshold value as a float: ("
450                                     + tval + ")");
451                     e.printStackTrace();
452                   }
453                 }
454                 // parse the thresh-is-min token ?
455                 if (gcol.hasMoreTokens())
456                 {
457                   System.err
458                           .println("Ignoring additional tokens in parameters in graduated colour specification\n");
459                   while (gcol.hasMoreTokens())
460                   {
461                     System.err.println("|" + gcol.nextToken());
462                   }
463                   System.err.println("\n");
464                 }
465               }
466             }
467             else
468             {
469               UserColourScheme ucs = new UserColourScheme(colscheme);
470               colour = ucs.findColour('A');
471             }
472             if (colour != null)
473             {
474               colours.put(type, colour);
475             }
476             if (st.hasMoreElements())
477             {
478               String link = st.nextToken();
479               typeLink.put(type, link);
480               if (featureLink == null)
481               {
482                 featureLink = new Hashtable();
483               }
484               featureLink.put(type, link);
485             }
486           }
487           continue;
488         }
489         String seqId = "";
490         while (st.hasMoreElements())
491         {
492
493           if (GFFFile)
494           {
495             // Still possible this is an old Jalview file,
496             // which does not have type colours at the beginning
497             seqId = token = st.nextToken();
498             seq = findName(align, seqId, relaxedIdmatching, newseqs);
499             if (seq != null)
500             {
501               desc = st.nextToken();
502               String group = null;
503               if (doGffSource && desc.indexOf(' ') == -1)
504               {
505                 // could also be a source term rather than description line
506                 group = new String(desc);
507               }
508               type = st.nextToken();
509               try
510               {
511                 String stt = st.nextToken();
512                 if (stt.length() == 0 || stt.equals("-"))
513                 {
514                   start = 0;
515                 }
516                 else
517                 {
518                   start = Integer.parseInt(stt);
519                 }
520               } catch (NumberFormatException ex)
521               {
522                 start = 0;
523               }
524               try
525               {
526                 String stt = st.nextToken();
527                 if (stt.length() == 0 || stt.equals("-"))
528                 {
529                   end = 0;
530                 }
531                 else
532                 {
533                   end = Integer.parseInt(stt);
534                 }
535               } catch (NumberFormatException ex)
536               {
537                 end = 0;
538               }
539               // TODO: decide if non positional feature assertion for input data
540               // where end==0 is generally valid
541               if (end == 0)
542               {
543                 // treat as non-positional feature, regardless.
544                 start = 0;
545               }
546               try
547               {
548                 score = new Float(st.nextToken()).floatValue();
549               } catch (NumberFormatException ex)
550               {
551                 score = 0;
552               }
553
554               sf = new SequenceFeature(type, desc, start, end, score, group);
555
556               try
557               {
558                 sf.setValue("STRAND", st.nextToken());
559                 sf.setValue("FRAME", st.nextToken());
560               } catch (Exception ex)
561               {
562               }
563
564               if (st.hasMoreTokens())
565               {
566                 StringBuffer attributes = new StringBuffer();
567                 boolean sep = false;
568                 while (st.hasMoreTokens())
569                 {
570                   attributes.append((sep ? "\t" : "") + st.nextElement());
571                   sep = true;
572                 }
573                 // TODO validate and split GFF2 attributes field ? parse out
574                 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
575                 // sf.setValue(attrib, val);
576                 sf.setValue("ATTRIBUTES", attributes.toString());
577               }
578
579               if (processOrAddSeqFeature(align, newseqs, seq, sf, GFFFile,
580                       relaxedIdmatching))
581               {
582                 // check whether we should add the sequence feature to any other
583                 // sequences in the alignment with the same or similar
584                 while ((seq = align.findName(seq, seqId, true)) != null)
585                 {
586                   seq.addSequenceFeature(new SequenceFeature(sf));
587                 }
588               }
589               break;
590             }
591           }
592
593           if (GFFFile && seq == null)
594           {
595             desc = token;
596           }
597           else
598           {
599             desc = st.nextToken();
600           }
601           if (!st.hasMoreTokens())
602           {
603             System.err
604                     .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
605             // in all probability, this isn't a file we understand, so bail
606             // quietly.
607             return false;
608           }
609
610           token = st.nextToken();
611
612           if (!token.equals("ID_NOT_SPECIFIED"))
613           {
614             seq = findName(align, seqId = token, relaxedIdmatching, null);
615             st.nextToken();
616           }
617           else
618           {
619             seqId = null;
620             try
621             {
622               index = Integer.parseInt(st.nextToken());
623               seq = align.getSequenceAt(index);
624             } catch (NumberFormatException ex)
625             {
626               seq = null;
627             }
628           }
629
630           if (seq == null)
631           {
632             System.out.println("Sequence not found: " + line);
633             break;
634           }
635
636           start = Integer.parseInt(st.nextToken());
637           end = Integer.parseInt(st.nextToken());
638
639           type = st.nextToken();
640
641           if (!colours.containsKey(type))
642           {
643             // Probably the old style groups file
644             UserColourScheme ucs = new UserColourScheme(type);
645             colours.put(type, ucs.findColour('A'));
646           }
647           sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
648           if (st.hasMoreTokens())
649           {
650             try
651             {
652               score = new Float(st.nextToken()).floatValue();
653               // update colourgradient bounds if allowed to
654             } catch (NumberFormatException ex)
655             {
656               score = 0;
657             }
658             sf.setScore(score);
659           }
660           if (groupLink != null && removeHTML)
661           {
662             sf.addLink(groupLink);
663             sf.description += "%LINK%";
664           }
665           if (typeLink.containsKey(type) && removeHTML)
666           {
667             sf.addLink(typeLink.get(type).toString());
668             sf.description += "%LINK%";
669           }
670
671           parseDescriptionHTML(sf, removeHTML);
672
673           seq.addSequenceFeature(sf);
674
675           while (seqId != null
676                   && (seq = align.findName(seq, seqId, false)) != null)
677           {
678             seq.addSequenceFeature(new SequenceFeature(sf));
679           }
680           // If we got here, its not a GFFFile
681           GFFFile = false;
682         }
683       }
684       resetMatcher();
685     } catch (Exception ex)
686     {
687       // should report somewhere useful for UI if necessary
688       warningMessage = ((warningMessage == null) ? "" : warningMessage)
689               + "Parsing error at\n" + line;
690       System.out.println("Error parsing feature file: " + ex + "\n" + line);
691       ex.printStackTrace(System.err);
692       resetMatcher();
693       return false;
694     }
695
696     return true;
697   }
698
699   private enum GffPragmas
700   {
701     gff_version, sequence_region, feature_ontology, attribute_ontology, source_ontology, species_build, fasta, hash
702   };
703
704   private static Map<String, GffPragmas> GFFPRAGMA;
705   static
706   {
707     GFFPRAGMA = new HashMap<String, GffPragmas>();
708     GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
709     GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
710     GFFPRAGMA.put("#", GffPragmas.hash);
711     GFFPRAGMA.put("fasta", GffPragmas.fasta);
712     GFFPRAGMA.put("species-build", GffPragmas.species_build);
713     GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
714     GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
715   }
716
717   private void processGffPragma(String line, Map<String, String> gffProps,
718           AlignmentI align, ArrayList<SequenceI> newseqs)
719           throws IOException
720   {
721     // line starts with ##
722     int spacepos = line.indexOf(' ');
723     String pragma = spacepos == -1 ? line.substring(2).trim() : line
724             .substring(2, spacepos);
725     GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
726     if (gffpragma == null)
727     {
728       return;
729     }
730     switch (gffpragma)
731     {
732     case gff_version:
733       try
734       {
735         gffversion = Integer.parseInt(line.substring(spacepos + 1));
736       } finally
737       {
738
739       }
740       break;
741     case feature_ontology:
742       // resolve against specific feature ontology
743       break;
744     case attribute_ontology:
745       // resolve against specific attribute ontology
746       break;
747     case source_ontology:
748       // resolve against specific source ontology
749       break;
750     case species_build:
751       // resolve against specific NCBI taxon version
752       break;
753     case hash:
754       // close off any open feature hierarchies
755       break;
756     case fasta:
757       // process the rest of the file as a fasta file and replace any dummy
758       // sequence IDs
759       process_as_fasta(align, newseqs);
760       break;
761     default:
762       // we do nothing ?
763       System.err.println("Ignoring unknown pragma:\n" + line);
764     }
765   }
766
767   private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
768           throws IOException
769   {
770     try
771     {
772       mark();
773     } catch (IOException q)
774     {
775     }
776     FastaFile parser = new FastaFile(this);
777     List<SequenceI> includedseqs = parser.getSeqs();
778     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
779     // iterate over includedseqs, and replacing matching ones with newseqs
780     // sequences. Generic iterator not used here because we modify includedseqs
781     // as we go
782     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
783     {
784       // search for any dummy seqs that this sequence can be used to update
785       SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
786       if (dummyseq != null)
787       {
788         // dummyseq was created so it could be annotated and referred to in
789         // alignments/codon mappings
790
791         SequenceI mseq = includedseqs.get(p);
792         // mseq is the 'template' imported from the FASTA file which we'll use
793         // to coomplete dummyseq
794         if (dummyseq instanceof SequenceDummy)
795         {
796           // probably have the pattern wrong
797           // idea is that a flyweight proxy for a sequence ID can be created for
798           // 1. stable reference creation
799           // 2. addition of annotation
800           // 3. future replacement by a real sequence
801           // current pattern is to create SequenceDummy objects - a convenience
802           // constructor for a Sequence.
803           // problem is that when promoted to a real sequence, all references
804           // need
805           // to be updated somehow.
806           ((SequenceDummy) dummyseq).become(mseq);
807           includedseqs.set(p, dummyseq); // template is no longer needed
808         }
809       }
810     }
811     // finally add sequences to the dataset
812     for (SequenceI seq : includedseqs)
813     {
814       align.addSequence(seq);
815     }
816   }
817
818   /**
819    * take a sequence feature and examine its attributes to decide how it should
820    * be added to a sequence
821    * 
822    * @param seq
823    *          - the destination sequence constructed or discovered in the
824    *          current context
825    * @param sf
826    *          - the base feature with ATTRIBUTES property containing any
827    *          additional attributes
828    * @param gFFFile
829    *          - true if we are processing a GFF annotation file
830    * @return true if sf was actually added to the sequence, false if it was
831    *         processed in another way
832    */
833   public boolean processOrAddSeqFeature(AlignmentI align,
834           List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
835           boolean gFFFile, boolean relaxedIdMatching)
836   {
837     String attr = (String) sf.getValue("ATTRIBUTES");
838     boolean add = true;
839     if (gFFFile && attr != null)
840     {
841       int nattr = 8;
842
843       for (String attset : attr.split("\t"))
844       {
845         if (attset == null || attset.trim().length() == 0)
846         {
847           continue;
848         }
849         nattr++;
850         Map<String, List<String>> set = new HashMap<String, List<String>>();
851         // normally, only expect one column - 9 - in this field
852         // the attributes (Gff3) or groups (gff2) field
853         for (String pair : attset.trim().split(";"))
854         {
855           pair = pair.trim();
856           if (pair.length() == 0)
857           {
858             continue;
859           }
860
861           // expect either space seperated (gff2) or '=' separated (gff3)
862           // key/value pairs here
863
864           int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
865           String key = null, value = null;
866
867           if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
868           {
869             key = pair.substring(0, sppos);
870             value = pair.substring(sppos + 1);
871           }
872           else
873           {
874             if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
875             {
876               key = pair.substring(0, eqpos);
877               value = pair.substring(eqpos + 1);
878             }
879             else
880             {
881               key = pair;
882             }
883           }
884           if (key != null)
885           {
886             List<String> vals = set.get(key);
887             if (vals == null)
888             {
889               vals = new ArrayList<String>();
890               set.put(key, vals);
891             }
892             if (value != null)
893             {
894               vals.add(value.trim());
895             }
896           }
897         }
898         try
899         {
900           add &= processGffKey(set, nattr, seq, sf, align, newseqs,
901                   relaxedIdMatching); // process decides if
902                                       // feature is actually
903                                       // added
904         } catch (InvalidGFF3FieldException ivfe)
905         {
906           System.err.println(ivfe);
907         }
908       }
909     }
910     if (add)
911     {
912       seq.addSequenceFeature(sf);
913     }
914     return add;
915   }
916
917   public class InvalidGFF3FieldException extends Exception
918   {
919     String field, value;
920
921     public InvalidGFF3FieldException(String field,
922             Map<String, List<String>> set, String message)
923     {
924       super(message + " (Field was " + field + " and value was "
925               + set.get(field).toString());
926       this.field = field;
927       this.value = set.get(field).toString();
928     }
929
930   }
931
932   /**
933    * take a set of keys for a feature and interpret them
934    * 
935    * @param set
936    * @param nattr
937    * @param seq
938    * @param sf
939    * @return
940    */
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
945   {
946     String attr;
947     // decide how to interpret according to type
948     if (sf.getType().equals("similarity"))
949     {
950       int strand = sf.getStrand();
951       // exonerate cdna/protein map
952       // look for fields
953       List<SequenceI> querySeq = findNames(align, newseqs,
954               relaxedIdMatching, set.get(attr = "Query"));
955       if (querySeq == null || querySeq.size() != 1)
956       {
957         throw new InvalidGFF3FieldException(attr, set,
958                 "Expecting exactly one sequence in Query field (got "
959                         + set.get(attr) + ")");
960       }
961       if (set.containsKey(attr = "Align"))
962       {
963         // process the align maps and create cdna/protein maps
964         // ideally, the query sequences are in the alignment, but maybe not...
965
966         AlignedCodonFrame alco = new AlignedCodonFrame();
967         MapList codonmapping = constructCodonMappingFromAlign(set, attr,
968                 strand);
969
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 !
975         return false;
976       }
977
978     }
979     return true;
980   }
981
982   private MapList constructCodonMappingFromAlign(
983           Map<String, List<String>> set, String attr, int strand)
984           throws InvalidGFF3FieldException
985   {
986     if (strand == 0)
987     {
988       throw new InvalidGFF3FieldException(attr, set,
989               "Invalid strand for a codon mapping (cannot be 0)");
990     }
991     List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
992     int lastppos = 0, lastpframe = 0;
993     for (String range : set.get(attr))
994     {
995       List<Integer> ints = new ArrayList<Integer>();
996       StringTokenizer st = new StringTokenizer(range, " ");
997       while (st.hasMoreTokens())
998       {
999         String num = st.nextToken();
1000         try
1001         {
1002           ints.add(new Integer(num));
1003         } catch (NumberFormatException nfe)
1004         {
1005           throw new InvalidGFF3FieldException(attr, set,
1006                   "Invalid number in field " + num);
1007         }
1008       }
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
1019       //
1020       // Align 10865 281 888
1021       // Align 9977 578 1068
1022       // Align 8909 935 375
1023       //
1024       if (ints.size() != 3)
1025       {
1026         throw new InvalidGFF3FieldException(attr, set,
1027                 "Invalid number of fields for this attribute ("
1028                         + ints.size() + ")");
1029       }
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
1034       // represented
1035       if (ints.get(1).equals(lastppos) && lastpframe > 0)
1036       {
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));
1041       }
1042       else
1043       {
1044         // new to map range
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));
1049       }
1050     }
1051     // from and to ranges must end up being a series of start/end intervals
1052     if (fromrange.size() % 2 == 1)
1053     {
1054       throw new InvalidGFF3FieldException(attr, set,
1055               "Couldn't parse the DNA alignment range correctly");
1056     }
1057     if (torange.size() % 2 == 1)
1058     {
1059       throw new InvalidGFF3FieldException(attr, set,
1060               "Couldn't parse the protein alignment range correctly");
1061     }
1062     // finally, build the map
1063     int[] frommap = new int[fromrange.size()], tomap = new int[torange
1064             .size()];
1065     int p = 0;
1066     for (Integer ip : fromrange)
1067     {
1068       frommap[p++] = ip.intValue();
1069     }
1070     p = 0;
1071     for (Integer ip : torange)
1072     {
1073       tomap[p++] = ip.intValue();
1074     }
1075
1076     return new MapList(frommap, tomap, 3, 1);
1077   }
1078
1079   private List<SequenceI> findNames(AlignmentI align,
1080           List<SequenceI> newseqs, boolean relaxedIdMatching,
1081           List<String> list)
1082   {
1083     List<SequenceI> found = new ArrayList<SequenceI>();
1084     for (String seqId : list)
1085     {
1086       SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1087       if (seq != null)
1088       {
1089         found.add(seq);
1090       }
1091     }
1092     return found;
1093   }
1094
1095   private AlignmentI lastmatchedAl = null;
1096
1097   private SequenceIdMatcher matcher = null;
1098
1099   /**
1100    * clear any temporary handles used to speed up ID matching
1101    */
1102   private void resetMatcher()
1103   {
1104     lastmatchedAl = null;
1105     matcher = null;
1106   }
1107
1108   private SequenceI findName(AlignmentI align, String seqId,
1109           boolean relaxedIdMatching, List<SequenceI> newseqs)
1110   {
1111     SequenceI match = null;
1112     if (relaxedIdMatching)
1113     {
1114       if (lastmatchedAl != align)
1115       {
1116         matcher = new SequenceIdMatcher(
1117                 (lastmatchedAl = align).getSequencesArray());
1118         if (newseqs != null)
1119         {
1120           matcher.addAll(newseqs);
1121         }
1122       }
1123       match = matcher.findIdMatch(seqId);
1124     }
1125     else
1126     {
1127       match = align.findName(seqId, true);
1128       if (match == null && newseqs != null)
1129       {
1130         for (SequenceI m : newseqs)
1131         {
1132           if (seqId.equals(m.getName()))
1133           {
1134             return m;
1135           }
1136         }
1137       }
1138
1139     }
1140     if (match == null && newseqs != null)
1141     {
1142       match = new SequenceDummy(seqId);
1143       if (relaxedIdMatching)
1144       {
1145         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1146       }
1147       // add dummy sequence to the newseqs list
1148       newseqs.add(match);
1149     }
1150     return match;
1151   }
1152
1153   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1154   {
1155     if (sf.getDescription() == null)
1156     {
1157       return;
1158     }
1159     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1160             sf.getDescription(), removeHTML, newline);
1161
1162     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1163             : sf.description;
1164     for (String link : parsed.getLinks())
1165     {
1166       sf.addLink(link);
1167     }
1168
1169   }
1170
1171   /**
1172    * generate a features file for seqs includes non-pos features by default.
1173    * 
1174    * @param seqs
1175    *          source of sequence features
1176    * @param visible
1177    *          hash of feature types and colours
1178    * @return features file contents
1179    */
1180   public String printJalviewFormat(SequenceI[] seqs,
1181           Map<String, Object> visible)
1182   {
1183     return printJalviewFormat(seqs, visible, true, true);
1184   }
1185
1186   /**
1187    * generate a features file for seqs with colours from visible (if any)
1188    * 
1189    * @param seqs
1190    *          source of features
1191    * @param visible
1192    *          hash of Colours for each feature type
1193    * @param visOnly
1194    *          when true only feature types in 'visible' will be output
1195    * @param nonpos
1196    *          indicates if non-positional features should be output (regardless
1197    *          of group or type)
1198    * @return features file contents
1199    */
1200   public String printJalviewFormat(SequenceI[] seqs, Map visible,
1201           boolean visOnly, boolean nonpos)
1202   {
1203     StringBuffer out = new StringBuffer();
1204     SequenceFeature[] next;
1205     boolean featuresGen = false;
1206     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1207     {
1208       // no point continuing.
1209       return "No Features Visible";
1210     }
1211
1212     if (visible != null && visOnly)
1213     {
1214       // write feature colours only if we're given them and we are generating
1215       // viewed features
1216       // TODO: decide if feature links should also be written here ?
1217       Iterator en = visible.keySet().iterator();
1218       String type, color;
1219       while (en.hasNext())
1220       {
1221         type = en.next().toString();
1222
1223         if (visible.get(type) instanceof GraduatedColor)
1224         {
1225           GraduatedColor gc = (GraduatedColor) visible.get(type);
1226           color = (gc.isColourByLabel() ? "label|" : "")
1227                   + Format.getHexString(gc.getMinColor()) + "|"
1228                   + Format.getHexString(gc.getMaxColor())
1229                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1230                   + gc.getMax() + "|";
1231           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1232           {
1233             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1234             {
1235               color += "below";
1236             }
1237             else
1238             {
1239               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1240               {
1241                 System.err.println("WARNING: Unsupported threshold type ("
1242                         + gc.getThreshType() + ") : Assuming 'above'");
1243               }
1244               color += "above";
1245             }
1246             // add the value
1247             color += "|" + gc.getThresh();
1248           }
1249           else
1250           {
1251             color += "none";
1252           }
1253         }
1254         else if (visible.get(type) instanceof java.awt.Color)
1255         {
1256           color = Format.getHexString((java.awt.Color) visible.get(type));
1257         }
1258         else
1259         {
1260           // legacy support for integer objects containing colour triplet values
1261           color = Format.getHexString(new java.awt.Color(Integer
1262                   .parseInt(visible.get(type).toString())));
1263         }
1264         out.append(type);
1265         out.append("\t");
1266         out.append(color);
1267         out.append(newline);
1268       }
1269     }
1270     // Work out which groups are both present and visible
1271     Vector groups = new Vector();
1272     int groupIndex = 0;
1273     boolean isnonpos = false;
1274
1275     for (int i = 0; i < seqs.length; i++)
1276     {
1277       next = seqs[i].getSequenceFeatures();
1278       if (next != null)
1279       {
1280         for (int j = 0; j < next.length; j++)
1281         {
1282           isnonpos = next[j].begin == 0 && next[j].end == 0;
1283           if ((!nonpos && isnonpos)
1284                   || (!isnonpos && visOnly && !visible
1285                           .containsKey(next[j].type)))
1286           {
1287             continue;
1288           }
1289
1290           if (next[j].featureGroup != null
1291                   && !groups.contains(next[j].featureGroup))
1292           {
1293             groups.addElement(next[j].featureGroup);
1294           }
1295         }
1296       }
1297     }
1298
1299     String group = null;
1300     do
1301     {
1302
1303       if (groups.size() > 0 && groupIndex < groups.size())
1304       {
1305         group = groups.elementAt(groupIndex).toString();
1306         out.append(newline);
1307         out.append("STARTGROUP\t");
1308         out.append(group);
1309         out.append(newline);
1310       }
1311       else
1312       {
1313         group = null;
1314       }
1315
1316       for (int i = 0; i < seqs.length; i++)
1317       {
1318         next = seqs[i].getSequenceFeatures();
1319         if (next != null)
1320         {
1321           for (int j = 0; j < next.length; j++)
1322           {
1323             isnonpos = next[j].begin == 0 && next[j].end == 0;
1324             if ((!nonpos && isnonpos)
1325                     || (!isnonpos && visOnly && !visible
1326                             .containsKey(next[j].type)))
1327             {
1328               // skip if feature is nonpos and we ignore them or if we only
1329               // output visible and it isn't non-pos and it's not visible
1330               continue;
1331             }
1332
1333             if (group != null
1334                     && (next[j].featureGroup == null || !next[j].featureGroup
1335                             .equals(group)))
1336             {
1337               continue;
1338             }
1339
1340             if (group == null && next[j].featureGroup != null)
1341             {
1342               continue;
1343             }
1344             // we have features to output
1345             featuresGen = true;
1346             if (next[j].description == null
1347                     || next[j].description.equals(""))
1348             {
1349               out.append(next[j].type + "\t");
1350             }
1351             else
1352             {
1353               if (next[j].links != null
1354                       && next[j].getDescription().indexOf("<html>") == -1)
1355               {
1356                 out.append("<html>");
1357               }
1358
1359               out.append(next[j].description + " ");
1360               if (next[j].links != null)
1361               {
1362                 for (int l = 0; l < next[j].links.size(); l++)
1363                 {
1364                   String label = next[j].links.elementAt(l).toString();
1365                   String href = label.substring(label.indexOf("|") + 1);
1366                   label = label.substring(0, label.indexOf("|"));
1367
1368                   if (next[j].description.indexOf(href) == -1)
1369                   {
1370                     out.append("<a href=\"" + href + "\">" + label + "</a>");
1371                   }
1372                 }
1373
1374                 if (next[j].getDescription().indexOf("</html>") == -1)
1375                 {
1376                   out.append("</html>");
1377                 }
1378               }
1379
1380               out.append("\t");
1381             }
1382             out.append(seqs[i].getName());
1383             out.append("\t-1\t");
1384             out.append(next[j].begin);
1385             out.append("\t");
1386             out.append(next[j].end);
1387             out.append("\t");
1388             out.append(next[j].type);
1389             if (!Float.isNaN(next[j].score))
1390             {
1391               out.append("\t");
1392               out.append(next[j].score);
1393             }
1394             out.append(newline);
1395           }
1396         }
1397       }
1398
1399       if (group != null)
1400       {
1401         out.append("ENDGROUP\t");
1402         out.append(group);
1403         out.append(newline);
1404         groupIndex++;
1405       }
1406       else
1407       {
1408         break;
1409       }
1410
1411     } while (groupIndex < groups.size() + 1);
1412
1413     if (!featuresGen)
1414     {
1415       return "No Features Visible";
1416     }
1417
1418     return out.toString();
1419   }
1420
1421   /**
1422    * generate a gff file for sequence features includes non-pos features by
1423    * default.
1424    * 
1425    * @param seqs
1426    * @param visible
1427    * @return
1428    */
1429   public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1430   {
1431     return printGFFFormat(seqs, visible, true, true);
1432   }
1433
1434   public String printGFFFormat(SequenceI[] seqs,
1435           Map<String, Object> visible, boolean visOnly, boolean nonpos)
1436   {
1437     StringBuffer out = new StringBuffer();
1438     SequenceFeature[] next;
1439     String source;
1440     boolean isnonpos;
1441     for (int i = 0; i < seqs.length; i++)
1442     {
1443       if (seqs[i].getSequenceFeatures() != null)
1444       {
1445         next = seqs[i].getSequenceFeatures();
1446         for (int j = 0; j < next.length; j++)
1447         {
1448           isnonpos = next[j].begin == 0 && next[j].end == 0;
1449           if ((!nonpos && isnonpos)
1450                   || (!isnonpos && visOnly && !visible
1451                           .containsKey(next[j].type)))
1452           {
1453             continue;
1454           }
1455
1456           source = next[j].featureGroup;
1457           if (source == null)
1458           {
1459             source = next[j].getDescription();
1460           }
1461
1462           out.append(seqs[i].getName());
1463           out.append("\t");
1464           out.append(source);
1465           out.append("\t");
1466           out.append(next[j].type);
1467           out.append("\t");
1468           out.append(next[j].begin);
1469           out.append("\t");
1470           out.append(next[j].end);
1471           out.append("\t");
1472           out.append(next[j].score);
1473           out.append("\t");
1474
1475           if (next[j].getValue("STRAND") != null)
1476           {
1477             out.append(next[j].getValue("STRAND"));
1478             out.append("\t");
1479           }
1480           else
1481           {
1482             out.append(".\t");
1483           }
1484
1485           if (next[j].getValue("FRAME") != null)
1486           {
1487             out.append(next[j].getValue("FRAME"));
1488           }
1489           else
1490           {
1491             out.append(".");
1492           }
1493           // TODO: verify/check GFF - should there be a /t here before attribute
1494           // output ?
1495
1496           if (next[j].getValue("ATTRIBUTES") != null)
1497           {
1498             out.append(next[j].getValue("ATTRIBUTES"));
1499           }
1500
1501           out.append(newline);
1502
1503         }
1504       }
1505     }
1506
1507     return out.toString();
1508   }
1509
1510   /**
1511    * this is only for the benefit of object polymorphism - method does nothing.
1512    */
1513   public void parse()
1514   {
1515     // IGNORED
1516   }
1517
1518   /**
1519    * this is only for the benefit of object polymorphism - method does nothing.
1520    * 
1521    * @return error message
1522    */
1523   public String print()
1524   {
1525     return "USE printGFFFormat() or printJalviewFormat()";
1526   }
1527
1528 }