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