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