JAL-653 added missing pragma string to processing filter
[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("gff-version", GffPragmas.gff_version);
709     GFFPRAGMA.put("sequence-region", GffPragmas.sequence_region);
710     GFFPRAGMA.put("feature-ontology", GffPragmas.feature_ontology);
711     GFFPRAGMA.put("#", GffPragmas.hash);
712     GFFPRAGMA.put("fasta", GffPragmas.fasta);
713     GFFPRAGMA.put("species-build", GffPragmas.species_build);
714     GFFPRAGMA.put("source-ontology", GffPragmas.source_ontology);
715     GFFPRAGMA.put("attribute-ontology", GffPragmas.attribute_ontology);
716   }
717
718   private void processGffPragma(String line, Map<String, String> gffProps,
719           AlignmentI align, ArrayList<SequenceI> newseqs)
720           throws IOException
721   {
722     // line starts with ##
723     int spacepos = line.indexOf(' ');
724     String pragma = spacepos == -1 ? line.substring(2).trim() : line
725             .substring(2, spacepos);
726     GffPragmas gffpragma = GFFPRAGMA.get(pragma.toLowerCase());
727     if (gffpragma == null)
728     {
729       return;
730     }
731     switch (gffpragma)
732     {
733     case gff_version:
734       try
735       {
736         gffversion = Integer.parseInt(line.substring(spacepos + 1));
737       } finally
738       {
739
740       }
741       break;
742     case feature_ontology:
743       // resolve against specific feature ontology
744       break;
745     case attribute_ontology:
746       // resolve against specific attribute ontology
747       break;
748     case source_ontology:
749       // resolve against specific source ontology
750       break;
751     case species_build:
752       // resolve against specific NCBI taxon version
753       break;
754     case hash:
755       // close off any open feature hierarchies
756       break;
757     case fasta:
758       // process the rest of the file as a fasta file and replace any dummy
759       // sequence IDs
760       process_as_fasta(align, newseqs);
761       break;
762     default:
763       // we do nothing ?
764       System.err.println("Ignoring unknown pragma:\n" + line);
765     }
766   }
767
768   private void process_as_fasta(AlignmentI align, List<SequenceI> newseqs)
769           throws IOException
770   {
771     try
772     {
773       mark();
774     } catch (IOException q)
775     {
776     }
777     FastaFile parser = new FastaFile(this);
778     List<SequenceI> includedseqs = parser.getSeqs();
779     SequenceIdMatcher smatcher = new SequenceIdMatcher(newseqs);
780     // iterate over includedseqs, and replacing matching ones with newseqs
781     // sequences. Generic iterator not used here because we modify includedseqs
782     // as we go
783     for (int p = 0, pSize = includedseqs.size(); p < pSize; p++)
784     {
785       // search for any dummy seqs that this sequence can be used to update
786       SequenceI dummyseq = smatcher.findIdMatch(includedseqs.get(p));
787       if (dummyseq != null)
788       {
789         // dummyseq was created so it could be annotated and referred to in
790         // alignments/codon mappings
791
792         SequenceI mseq = includedseqs.get(p);
793         // mseq is the 'template' imported from the FASTA file which we'll use
794         // to coomplete dummyseq
795         if (dummyseq instanceof SequenceDummy)
796         {
797           // probably have the pattern wrong
798           // idea is that a flyweight proxy for a sequence ID can be created for
799           // 1. stable reference creation
800           // 2. addition of annotation
801           // 3. future replacement by a real sequence
802           // current pattern is to create SequenceDummy objects - a convenience
803           // constructor for a Sequence.
804           // problem is that when promoted to a real sequence, all references
805           // need
806           // to be updated somehow.
807           ((SequenceDummy) dummyseq).become(mseq);
808           includedseqs.set(p, dummyseq); // template is no longer needed
809         }
810       }
811     }
812     // finally add sequences to the dataset
813     for (SequenceI seq : includedseqs)
814     {
815       align.addSequence(seq);
816     }
817   }
818
819   /**
820    * take a sequence feature and examine its attributes to decide how it should
821    * be added to a sequence
822    * 
823    * @param seq
824    *          - the destination sequence constructed or discovered in the
825    *          current context
826    * @param sf
827    *          - the base feature with ATTRIBUTES property containing any
828    *          additional attributes
829    * @param gFFFile
830    *          - true if we are processing a GFF annotation file
831    * @return true if sf was actually added to the sequence, false if it was
832    *         processed in another way
833    */
834   public boolean processOrAddSeqFeature(AlignmentI align,
835           List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
836           boolean gFFFile, boolean relaxedIdMatching)
837   {
838     String attr = (String) sf.getValue("ATTRIBUTES");
839     boolean add = true;
840     if (gFFFile && attr != null)
841     {
842       int nattr = 8;
843
844       for (String attset : attr.split("\t"))
845       {
846         if (attset == null || attset.trim().length() == 0)
847         {
848           continue;
849         }
850         nattr++;
851         Map<String, List<String>> set = new HashMap<String, List<String>>();
852         // normally, only expect one column - 9 - in this field
853         // the attributes (Gff3) or groups (gff2) field
854         for (String pair : attset.trim().split(";"))
855         {
856           pair = pair.trim();
857           if (pair.length() == 0)
858           {
859             continue;
860           }
861
862           // expect either space seperated (gff2) or '=' separated (gff3)
863           // key/value pairs here
864
865           int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
866           String key = null, value = null;
867
868           if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
869           {
870             key = pair.substring(0, sppos);
871             value = pair.substring(sppos + 1);
872           }
873           else
874           {
875             if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
876             {
877               key = pair.substring(0, eqpos);
878               value = pair.substring(eqpos + 1);
879             }
880             else
881             {
882               key = pair;
883             }
884           }
885           if (key != null)
886           {
887             List<String> vals = set.get(key);
888             if (vals == null)
889             {
890               vals = new ArrayList<String>();
891               set.put(key, vals);
892             }
893             if (value != null)
894             {
895               vals.add(value.trim());
896             }
897           }
898         }
899         try
900         {
901           add &= processGffKey(set, nattr, seq, sf, align, newseqs,
902                   relaxedIdMatching); // process decides if
903                                       // feature is actually
904                                       // added
905         } catch (InvalidGFF3FieldException ivfe)
906         {
907           System.err.println(ivfe);
908         }
909       }
910     }
911     if (add)
912     {
913       seq.addSequenceFeature(sf);
914     }
915     return add;
916   }
917
918   public class InvalidGFF3FieldException extends Exception
919   {
920     String field, value;
921
922     public InvalidGFF3FieldException(String field,
923             Map<String, List<String>> set, String message)
924     {
925       super(message + " (Field was " + field + " and value was "
926               + set.get(field).toString());
927       this.field = field;
928       this.value = set.get(field).toString();
929     }
930
931   }
932
933   /**
934    * take a set of keys for a feature and interpret them
935    * 
936    * @param set
937    * @param nattr
938    * @param seq
939    * @param sf
940    * @return
941    */
942   public boolean processGffKey(Map<String, List<String>> set, int nattr,
943           SequenceI seq, SequenceFeature sf, AlignmentI align,
944           List<SequenceI> newseqs, boolean relaxedIdMatching)
945           throws InvalidGFF3FieldException
946   {
947     String attr;
948     // decide how to interpret according to type
949     if (sf.getType().equals("similarity"))
950     {
951       int strand = sf.getStrand();
952       // exonerate cdna/protein map
953       // look for fields
954       List<SequenceI> querySeq = findNames(align, newseqs,
955               relaxedIdMatching, set.get(attr = "Query"));
956       if (querySeq == null || querySeq.size() != 1)
957       {
958         throw new InvalidGFF3FieldException(attr, set,
959                 "Expecting exactly one sequence in Query field (got "
960                         + set.get(attr) + ")");
961       }
962       if (set.containsKey(attr = "Align"))
963       {
964         // process the align maps and create cdna/protein maps
965         // ideally, the query sequences are in the alignment, but maybe not...
966
967         AlignedCodonFrame alco = new AlignedCodonFrame();
968         MapList codonmapping = constructCodonMappingFromAlign(set, attr,
969                 strand);
970
971         // add codon mapping, and hope!
972         alco.addMap(seq, querySeq.get(0), codonmapping);
973         align.addCodonFrame(alco);
974         // everything that's needed to be done is done
975         // no features to create here !
976         return false;
977       }
978
979     }
980     return true;
981   }
982
983   private MapList constructCodonMappingFromAlign(
984           Map<String, List<String>> set, String attr, int strand)
985           throws InvalidGFF3FieldException
986   {
987     if (strand == 0)
988     {
989       throw new InvalidGFF3FieldException(attr, set,
990               "Invalid strand for a codon mapping (cannot be 0)");
991     }
992     List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
993     int lastppos = 0, lastpframe = 0;
994     for (String range : set.get(attr))
995     {
996       List<Integer> ints = new ArrayList<Integer>();
997       StringTokenizer st = new StringTokenizer(range, " ");
998       while (st.hasMoreTokens())
999       {
1000         String num = st.nextToken();
1001         try
1002         {
1003           ints.add(new Integer(num));
1004         } catch (NumberFormatException nfe)
1005         {
1006           throw new InvalidGFF3FieldException(attr, set,
1007                   "Invalid number in field " + num);
1008         }
1009       }
1010       // Align positionInRef positionInQuery LengthInRef
1011       // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1012       // 3652 - . alignment_id 0 ;
1013       // Query DDB_G0269124
1014       // Align 11270 143 120
1015       // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1016       // dna in strand direction
1017       // Align 11150 187 282
1018       // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1019       // dna in strand direction
1020       //
1021       // Align 10865 281 888
1022       // Align 9977 578 1068
1023       // Align 8909 935 375
1024       //
1025       if (ints.size() != 3)
1026       {
1027         throw new InvalidGFF3FieldException(attr, set,
1028                 "Invalid number of fields for this attribute ("
1029                         + ints.size() + ")");
1030       }
1031       fromrange.add(new Integer(ints.get(0).intValue()));
1032       fromrange.add(new Integer(ints.get(0).intValue() + strand
1033               * ints.get(2).intValue()));
1034       // how are intron/exon boundaries that do not align in codons
1035       // represented
1036       if (ints.get(1).equals(lastppos) && lastpframe > 0)
1037       {
1038         // extend existing to map
1039         lastppos += ints.get(2) / 3;
1040         lastpframe = ints.get(2) % 3;
1041         torange.set(torange.size() - 1, new Integer(lastppos));
1042       }
1043       else
1044       {
1045         // new to map range
1046         torange.add(ints.get(1));
1047         lastppos = ints.get(1) + ints.get(2) / 3;
1048         lastpframe = ints.get(2) % 3;
1049         torange.add(new Integer(lastppos));
1050       }
1051     }
1052     // from and to ranges must end up being a series of start/end intervals
1053     if (fromrange.size() % 2 == 1)
1054     {
1055       throw new InvalidGFF3FieldException(attr, set,
1056               "Couldn't parse the DNA alignment range correctly");
1057     }
1058     if (torange.size() % 2 == 1)
1059     {
1060       throw new InvalidGFF3FieldException(attr, set,
1061               "Couldn't parse the protein alignment range correctly");
1062     }
1063     // finally, build the map
1064     int[] frommap = new int[fromrange.size()], tomap = new int[torange
1065             .size()];
1066     int p = 0;
1067     for (Integer ip : fromrange)
1068     {
1069       frommap[p++] = ip.intValue();
1070     }
1071     p = 0;
1072     for (Integer ip : torange)
1073     {
1074       tomap[p++] = ip.intValue();
1075     }
1076
1077     return new MapList(frommap, tomap, 3, 1);
1078   }
1079
1080   private List<SequenceI> findNames(AlignmentI align,
1081           List<SequenceI> newseqs, boolean relaxedIdMatching,
1082           List<String> list)
1083   {
1084     List<SequenceI> found = new ArrayList<SequenceI>();
1085     for (String seqId : list)
1086     {
1087       SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1088       if (seq != null)
1089       {
1090         found.add(seq);
1091       }
1092     }
1093     return found;
1094   }
1095
1096   private AlignmentI lastmatchedAl = null;
1097
1098   private SequenceIdMatcher matcher = null;
1099
1100   /**
1101    * clear any temporary handles used to speed up ID matching
1102    */
1103   private void resetMatcher()
1104   {
1105     lastmatchedAl = null;
1106     matcher = null;
1107   }
1108
1109   private SequenceI findName(AlignmentI align, String seqId,
1110           boolean relaxedIdMatching, List<SequenceI> newseqs)
1111   {
1112     SequenceI match = null;
1113     if (relaxedIdMatching)
1114     {
1115       if (lastmatchedAl != align)
1116       {
1117         matcher = new SequenceIdMatcher(
1118                 (lastmatchedAl = align).getSequencesArray());
1119         if (newseqs != null)
1120         {
1121           matcher.addAll(newseqs);
1122         }
1123       }
1124       match = matcher.findIdMatch(seqId);
1125     }
1126     else
1127     {
1128       match = align.findName(seqId, true);
1129       if (match == null && newseqs != null)
1130       {
1131         for (SequenceI m : newseqs)
1132         {
1133           if (seqId.equals(m.getName()))
1134           {
1135             return m;
1136           }
1137         }
1138       }
1139
1140     }
1141     if (match == null && newseqs != null)
1142     {
1143       match = new SequenceDummy(seqId);
1144       if (relaxedIdMatching)
1145       {
1146         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1147       }
1148       // add dummy sequence to the newseqs list
1149       newseqs.add(match);
1150     }
1151     return match;
1152   }
1153
1154   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1155   {
1156     if (sf.getDescription() == null)
1157     {
1158       return;
1159     }
1160     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1161             sf.getDescription(), removeHTML, newline);
1162
1163     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1164             : sf.description;
1165     for (String link : parsed.getLinks())
1166     {
1167       sf.addLink(link);
1168     }
1169
1170   }
1171
1172   /**
1173    * generate a features file for seqs includes non-pos features by default.
1174    * 
1175    * @param seqs
1176    *          source of sequence features
1177    * @param visible
1178    *          hash of feature types and colours
1179    * @return features file contents
1180    */
1181   public String printJalviewFormat(SequenceI[] seqs,
1182           Map<String, Object> visible)
1183   {
1184     return printJalviewFormat(seqs, visible, true, true);
1185   }
1186
1187   /**
1188    * generate a features file for seqs with colours from visible (if any)
1189    * 
1190    * @param seqs
1191    *          source of features
1192    * @param visible
1193    *          hash of Colours for each feature type
1194    * @param visOnly
1195    *          when true only feature types in 'visible' will be output
1196    * @param nonpos
1197    *          indicates if non-positional features should be output (regardless
1198    *          of group or type)
1199    * @return features file contents
1200    */
1201   public String printJalviewFormat(SequenceI[] seqs, Map visible,
1202           boolean visOnly, boolean nonpos)
1203   {
1204     StringBuffer out = new StringBuffer();
1205     SequenceFeature[] next;
1206     boolean featuresGen = false;
1207     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1208     {
1209       // no point continuing.
1210       return "No Features Visible";
1211     }
1212
1213     if (visible != null && visOnly)
1214     {
1215       // write feature colours only if we're given them and we are generating
1216       // viewed features
1217       // TODO: decide if feature links should also be written here ?
1218       Iterator en = visible.keySet().iterator();
1219       String type, color;
1220       while (en.hasNext())
1221       {
1222         type = en.next().toString();
1223
1224         if (visible.get(type) instanceof GraduatedColor)
1225         {
1226           GraduatedColor gc = (GraduatedColor) visible.get(type);
1227           color = (gc.isColourByLabel() ? "label|" : "")
1228                   + Format.getHexString(gc.getMinColor()) + "|"
1229                   + Format.getHexString(gc.getMaxColor())
1230                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1231                   + gc.getMax() + "|";
1232           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1233           {
1234             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1235             {
1236               color += "below";
1237             }
1238             else
1239             {
1240               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1241               {
1242                 System.err.println("WARNING: Unsupported threshold type ("
1243                         + gc.getThreshType() + ") : Assuming 'above'");
1244               }
1245               color += "above";
1246             }
1247             // add the value
1248             color += "|" + gc.getThresh();
1249           }
1250           else
1251           {
1252             color += "none";
1253           }
1254         }
1255         else if (visible.get(type) instanceof java.awt.Color)
1256         {
1257           color = Format.getHexString((java.awt.Color) visible.get(type));
1258         }
1259         else
1260         {
1261           // legacy support for integer objects containing colour triplet values
1262           color = Format.getHexString(new java.awt.Color(Integer
1263                   .parseInt(visible.get(type).toString())));
1264         }
1265         out.append(type);
1266         out.append("\t");
1267         out.append(color);
1268         out.append(newline);
1269       }
1270     }
1271     // Work out which groups are both present and visible
1272     Vector groups = new Vector();
1273     int groupIndex = 0;
1274     boolean isnonpos = false;
1275
1276     for (int i = 0; i < seqs.length; i++)
1277     {
1278       next = seqs[i].getSequenceFeatures();
1279       if (next != null)
1280       {
1281         for (int j = 0; j < next.length; j++)
1282         {
1283           isnonpos = next[j].begin == 0 && next[j].end == 0;
1284           if ((!nonpos && isnonpos)
1285                   || (!isnonpos && visOnly && !visible
1286                           .containsKey(next[j].type)))
1287           {
1288             continue;
1289           }
1290
1291           if (next[j].featureGroup != null
1292                   && !groups.contains(next[j].featureGroup))
1293           {
1294             groups.addElement(next[j].featureGroup);
1295           }
1296         }
1297       }
1298     }
1299
1300     String group = null;
1301     do
1302     {
1303
1304       if (groups.size() > 0 && groupIndex < groups.size())
1305       {
1306         group = groups.elementAt(groupIndex).toString();
1307         out.append(newline);
1308         out.append("STARTGROUP\t");
1309         out.append(group);
1310         out.append(newline);
1311       }
1312       else
1313       {
1314         group = null;
1315       }
1316
1317       for (int i = 0; i < seqs.length; i++)
1318       {
1319         next = seqs[i].getSequenceFeatures();
1320         if (next != null)
1321         {
1322           for (int j = 0; j < next.length; j++)
1323           {
1324             isnonpos = next[j].begin == 0 && next[j].end == 0;
1325             if ((!nonpos && isnonpos)
1326                     || (!isnonpos && visOnly && !visible
1327                             .containsKey(next[j].type)))
1328             {
1329               // skip if feature is nonpos and we ignore them or if we only
1330               // output visible and it isn't non-pos and it's not visible
1331               continue;
1332             }
1333
1334             if (group != null
1335                     && (next[j].featureGroup == null || !next[j].featureGroup
1336                             .equals(group)))
1337             {
1338               continue;
1339             }
1340
1341             if (group == null && next[j].featureGroup != null)
1342             {
1343               continue;
1344             }
1345             // we have features to output
1346             featuresGen = true;
1347             if (next[j].description == null
1348                     || next[j].description.equals(""))
1349             {
1350               out.append(next[j].type + "\t");
1351             }
1352             else
1353             {
1354               if (next[j].links != null
1355                       && next[j].getDescription().indexOf("<html>") == -1)
1356               {
1357                 out.append("<html>");
1358               }
1359
1360               out.append(next[j].description + " ");
1361               if (next[j].links != null)
1362               {
1363                 for (int l = 0; l < next[j].links.size(); l++)
1364                 {
1365                   String label = next[j].links.elementAt(l).toString();
1366                   String href = label.substring(label.indexOf("|") + 1);
1367                   label = label.substring(0, label.indexOf("|"));
1368
1369                   if (next[j].description.indexOf(href) == -1)
1370                   {
1371                     out.append("<a href=\"" + href + "\">" + label + "</a>");
1372                   }
1373                 }
1374
1375                 if (next[j].getDescription().indexOf("</html>") == -1)
1376                 {
1377                   out.append("</html>");
1378                 }
1379               }
1380
1381               out.append("\t");
1382             }
1383             out.append(seqs[i].getName());
1384             out.append("\t-1\t");
1385             out.append(next[j].begin);
1386             out.append("\t");
1387             out.append(next[j].end);
1388             out.append("\t");
1389             out.append(next[j].type);
1390             if (!Float.isNaN(next[j].score))
1391             {
1392               out.append("\t");
1393               out.append(next[j].score);
1394             }
1395             out.append(newline);
1396           }
1397         }
1398       }
1399
1400       if (group != null)
1401       {
1402         out.append("ENDGROUP\t");
1403         out.append(group);
1404         out.append(newline);
1405         groupIndex++;
1406       }
1407       else
1408       {
1409         break;
1410       }
1411
1412     } while (groupIndex < groups.size() + 1);
1413
1414     if (!featuresGen)
1415     {
1416       return "No Features Visible";
1417     }
1418
1419     return out.toString();
1420   }
1421
1422   /**
1423    * generate a gff file for sequence features includes non-pos features by
1424    * default.
1425    * 
1426    * @param seqs
1427    * @param visible
1428    * @return
1429    */
1430   public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1431   {
1432     return printGFFFormat(seqs, visible, true, true);
1433   }
1434
1435   public String printGFFFormat(SequenceI[] seqs,
1436           Map<String, Object> visible, boolean visOnly, boolean nonpos)
1437   {
1438     StringBuffer out = new StringBuffer();
1439     SequenceFeature[] next;
1440     String source;
1441     boolean isnonpos;
1442     for (int i = 0; i < seqs.length; i++)
1443     {
1444       if (seqs[i].getSequenceFeatures() != null)
1445       {
1446         next = seqs[i].getSequenceFeatures();
1447         for (int j = 0; j < next.length; j++)
1448         {
1449           isnonpos = next[j].begin == 0 && next[j].end == 0;
1450           if ((!nonpos && isnonpos)
1451                   || (!isnonpos && visOnly && !visible
1452                           .containsKey(next[j].type)))
1453           {
1454             continue;
1455           }
1456
1457           source = next[j].featureGroup;
1458           if (source == null)
1459           {
1460             source = next[j].getDescription();
1461           }
1462
1463           out.append(seqs[i].getName());
1464           out.append("\t");
1465           out.append(source);
1466           out.append("\t");
1467           out.append(next[j].type);
1468           out.append("\t");
1469           out.append(next[j].begin);
1470           out.append("\t");
1471           out.append(next[j].end);
1472           out.append("\t");
1473           out.append(next[j].score);
1474           out.append("\t");
1475
1476           if (next[j].getValue("STRAND") != null)
1477           {
1478             out.append(next[j].getValue("STRAND"));
1479             out.append("\t");
1480           }
1481           else
1482           {
1483             out.append(".\t");
1484           }
1485
1486           if (next[j].getValue("FRAME") != null)
1487           {
1488             out.append(next[j].getValue("FRAME"));
1489           }
1490           else
1491           {
1492             out.append(".");
1493           }
1494           // TODO: verify/check GFF - should there be a /t here before attribute
1495           // output ?
1496
1497           if (next[j].getValue("ATTRIBUTES") != null)
1498           {
1499             out.append(next[j].getValue("ATTRIBUTES"));
1500           }
1501
1502           out.append(newline);
1503
1504         }
1505       }
1506     }
1507
1508     return out.toString();
1509   }
1510
1511   /**
1512    * this is only for the benefit of object polymorphism - method does nothing.
1513    */
1514   @Override
1515   public void parse()
1516   {
1517     // IGNORED
1518   }
1519
1520   /**
1521    * this is only for the benefit of object polymorphism - method does nothing.
1522    * 
1523    * @return error message
1524    */
1525   @Override
1526   public String print()
1527   {
1528     return "USE printGFFFormat() or printJalviewFormat()";
1529   }
1530
1531 }