JAL-1925 update source version in license
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9.0b2)
3  * Copyright (C) 2015 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceDummy;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.schemes.AnnotationColourGradient;
30 import jalview.schemes.GraduatedColor;
31 import jalview.schemes.UserColourScheme;
32 import jalview.util.Format;
33 import jalview.util.MapList;
34
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.Hashtable;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
45
46 /**
47  * Parse and create Jalview Features files Detects GFF format features files and
48  * parses. Does not implement standard print() - call specific printFeatures or
49  * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
50  * for the features annotation - this normally works on an exact match.
51  * 
52  * @author AMW
53  * @version $Revision$
54  */
55 public class FeaturesFile extends AlignFile
56 {
57   /**
58    * work around for GFF interpretation bug where source string becomes
59    * description rather than a group
60    */
61   private boolean doGffSource = true;
62
63   private int gffversion;
64
65   /**
66    * Creates a new FeaturesFile object.
67    */
68   public FeaturesFile()
69   {
70   }
71
72   /**
73    * @param inFile
74    * @param type
75    * @throws IOException
76    */
77   public FeaturesFile(String inFile, String type) throws IOException
78   {
79     super(inFile, type);
80   }
81
82   /**
83    * @param source
84    * @throws IOException
85    */
86   public FeaturesFile(FileParse source) throws IOException
87   {
88     super(source);
89   }
90
91   /**
92    * @param parseImmediately
93    * @param source
94    * @throws IOException
95    */
96   public FeaturesFile(boolean parseImmediately, FileParse source)
97           throws IOException
98   {
99     super(parseImmediately, source);
100   }
101
102   /**
103    * @param parseImmediately
104    * @param inFile
105    * @param type
106    * @throws IOException
107    */
108   public FeaturesFile(boolean parseImmediately, String inFile, String type)
109           throws IOException
110   {
111     super(parseImmediately, inFile, type);
112   }
113
114   /**
115    * Parse GFF or sequence features file using case-independent matching,
116    * discarding URLs
117    * 
118    * @param align
119    *          - alignment/dataset containing sequences that are to be annotated
120    * @param colours
121    *          - hashtable to store feature colour definitions
122    * @param removeHTML
123    *          - process html strings into plain text
124    * @return true if features were added
125    */
126   public boolean parse(AlignmentI align, Map colours, boolean removeHTML)
127   {
128     return parse(align, colours, null, removeHTML, false);
129   }
130
131   /**
132    * Parse GFF or sequence features file optionally using case-independent
133    * matching, discarding URLs
134    * 
135    * @param align
136    *          - alignment/dataset containing sequences that are to be annotated
137    * @param colours
138    *          - hashtable to store feature colour definitions
139    * @param removeHTML
140    *          - process html strings into plain text
141    * @param relaxedIdmatching
142    *          - when true, ID matches to compound sequence IDs are allowed
143    * @return true if features were added
144    */
145   public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
146           boolean relaxedIdMatching)
147   {
148     return parse(align, colours, null, removeHTML, relaxedIdMatching);
149   }
150
151   /**
152    * Parse GFF or sequence features file optionally using case-independent
153    * matching
154    * 
155    * @param align
156    *          - alignment/dataset containing sequences that are to be annotated
157    * @param colours
158    *          - hashtable to store feature colour definitions
159    * @param featureLink
160    *          - hashtable to store associated URLs
161    * @param removeHTML
162    *          - process html strings into plain text
163    * @return true if features were added
164    */
165   public boolean parse(AlignmentI align, Map colours, Map featureLink,
166           boolean removeHTML)
167   {
168     return parse(align, colours, featureLink, removeHTML, false);
169   }
170
171   @Override
172   public void addAnnotations(AlignmentI al)
173   {
174     // TODO Auto-generated method stub
175     super.addAnnotations(al);
176   }
177
178   @Override
179   public void addProperties(AlignmentI al)
180   {
181     // TODO Auto-generated method stub
182     super.addProperties(al);
183   }
184
185   @Override
186   public void addSeqGroups(AlignmentI al)
187   {
188     // TODO Auto-generated method stub
189     super.addSeqGroups(al);
190   }
191
192   /**
193    * Parse GFF or sequence features file
194    * 
195    * @param align
196    *          - alignment/dataset containing sequences that are to be annotated
197    * @param colours
198    *          - hashtable to store feature colour definitions
199    * @param featureLink
200    *          - hashtable to store associated URLs
201    * @param removeHTML
202    *          - process html strings into plain text
203    * @param relaxedIdmatching
204    *          - when true, ID matches to compound sequence IDs are allowed
205    * @return true if features were added
206    */
207   public boolean parse(AlignmentI align, Map colours, Map featureLink,
208           boolean removeHTML, boolean relaxedIdmatching)
209   {
210
211     String line = null;
212     try
213     {
214       SequenceI seq = null;
215       /**
216        * keep track of any sequences we try to create from the data if it is a
217        * 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,
837           List<SequenceI> newseqs, SequenceI seq, SequenceFeature sf,
838           boolean gFFFile, boolean relaxedIdMatching)
839   {
840     String attr = (String) sf.getValue("ATTRIBUTES");
841     boolean add = true;
842     if (gFFFile && attr != null)
843     {
844       int nattr = 8;
845
846       for (String attset : attr.split("\t"))
847       {
848         if (attset == null || attset.trim().length() == 0)
849         {
850           continue;
851         }
852         nattr++;
853         Map<String, List<String>> set = new HashMap<String, List<String>>();
854         // normally, only expect one column - 9 - in this field
855         // the attributes (Gff3) or groups (gff2) field
856         for (String pair : attset.trim().split(";"))
857         {
858           pair = pair.trim();
859           if (pair.length() == 0)
860           {
861             continue;
862           }
863
864           // expect either space seperated (gff2) or '=' separated (gff3)
865           // key/value pairs here
866
867           int eqpos = pair.indexOf('='), sppos = pair.indexOf(' ');
868           String key = null, value = null;
869
870           if (sppos > -1 && (eqpos == -1 || sppos < eqpos))
871           {
872             key = pair.substring(0, sppos);
873             value = pair.substring(sppos + 1);
874           }
875           else
876           {
877             if (eqpos > -1 && (sppos == -1 || eqpos < sppos))
878             {
879               key = pair.substring(0, eqpos);
880               value = pair.substring(eqpos + 1);
881             }
882             else
883             {
884               key = pair;
885             }
886           }
887           if (key != null)
888           {
889             List<String> vals = set.get(key);
890             if (vals == null)
891             {
892               vals = new ArrayList<String>();
893               set.put(key, vals);
894             }
895             if (value != null)
896             {
897               vals.add(value.trim());
898             }
899           }
900         }
901         try
902         {
903           add &= processGffKey(set, nattr, seq, sf, align, newseqs,
904                   relaxedIdMatching); // process decides if
905                                       // feature is actually
906                                       // added
907         } catch (InvalidGFF3FieldException ivfe)
908         {
909           System.err.println(ivfe);
910         }
911       }
912     }
913     if (add)
914     {
915       seq.addSequenceFeature(sf);
916     }
917     return add;
918   }
919
920   public class InvalidGFF3FieldException extends Exception
921   {
922     String field, value;
923
924     public InvalidGFF3FieldException(String field,
925             Map<String, List<String>> set, String message)
926     {
927       super(message + " (Field was " + field + " and value was "
928               + set.get(field).toString());
929       this.field = field;
930       this.value = set.get(field).toString();
931     }
932
933   }
934
935   /**
936    * take a set of keys for a feature and interpret them
937    * 
938    * @param set
939    * @param nattr
940    * @param seq
941    * @param sf
942    * @return
943    */
944   public boolean processGffKey(Map<String, List<String>> set, int nattr,
945           SequenceI seq, SequenceFeature sf, AlignmentI align,
946           List<SequenceI> newseqs, boolean relaxedIdMatching)
947           throws InvalidGFF3FieldException
948   {
949     String attr;
950     // decide how to interpret according to type
951     if (sf.getType().equals("similarity"))
952     {
953       int strand = sf.getStrand();
954       // exonerate cdna/protein map
955       // look for fields
956       List<SequenceI> querySeq = findNames(align, newseqs,
957               relaxedIdMatching, set.get(attr = "Query"));
958       if (querySeq == null || querySeq.size() != 1)
959       {
960         throw new InvalidGFF3FieldException(attr, set,
961                 "Expecting exactly one sequence in Query field (got "
962                         + set.get(attr) + ")");
963       }
964       if (set.containsKey(attr = "Align"))
965       {
966         // process the align maps and create cdna/protein maps
967         // ideally, the query sequences are in the alignment, but maybe not...
968
969         AlignedCodonFrame alco = new AlignedCodonFrame();
970         MapList codonmapping = constructCodonMappingFromAlign(set, attr,
971                 strand);
972
973         // add codon mapping, and hope!
974         alco.addMap(seq, querySeq.get(0), codonmapping);
975         align.addCodonFrame(alco);
976         // everything that's needed to be done is done
977         // no features to create here !
978         return false;
979       }
980
981     }
982     return true;
983   }
984
985   private MapList constructCodonMappingFromAlign(
986           Map<String, List<String>> set, String attr, int strand)
987           throws InvalidGFF3FieldException
988   {
989     if (strand == 0)
990     {
991       throw new InvalidGFF3FieldException(attr, set,
992               "Invalid strand for a codon mapping (cannot be 0)");
993     }
994     List<Integer> fromrange = new ArrayList<Integer>(), torange = new ArrayList<Integer>();
995     int lastppos = 0, lastpframe = 0;
996     for (String range : set.get(attr))
997     {
998       List<Integer> ints = new ArrayList<Integer>();
999       StringTokenizer st = new StringTokenizer(range, " ");
1000       while (st.hasMoreTokens())
1001       {
1002         String num = st.nextToken();
1003         try
1004         {
1005           ints.add(new Integer(num));
1006         } catch (NumberFormatException nfe)
1007         {
1008           throw new InvalidGFF3FieldException(attr, set,
1009                   "Invalid number in field " + num);
1010         }
1011       }
1012       // Align positionInRef positionInQuery LengthInRef
1013       // contig_1146 exonerate:protein2genome:local similarity 8534 11269
1014       // 3652 - . alignment_id 0 ;
1015       // Query DDB_G0269124
1016       // Align 11270 143 120
1017       // corresponds to : 120 bases align at pos 143 in protein to 11270 on
1018       // dna in strand direction
1019       // Align 11150 187 282
1020       // corresponds to : 282 bases align at pos 187 in protein to 11150 on
1021       // dna in strand direction
1022       //
1023       // Align 10865 281 888
1024       // Align 9977 578 1068
1025       // Align 8909 935 375
1026       //
1027       if (ints.size() != 3)
1028       {
1029         throw new InvalidGFF3FieldException(attr, set,
1030                 "Invalid number of fields for this attribute ("
1031                         + ints.size() + ")");
1032       }
1033       fromrange.add(new Integer(ints.get(0).intValue()));
1034       fromrange.add(new Integer(ints.get(0).intValue() + strand
1035               * ints.get(2).intValue()));
1036       // how are intron/exon boundaries that do not align in codons
1037       // represented
1038       if (ints.get(1).equals(lastppos) && lastpframe > 0)
1039       {
1040         // extend existing to map
1041         lastppos += ints.get(2) / 3;
1042         lastpframe = ints.get(2) % 3;
1043         torange.set(torange.size() - 1, new Integer(lastppos));
1044       }
1045       else
1046       {
1047         // new to map range
1048         torange.add(ints.get(1));
1049         lastppos = ints.get(1) + ints.get(2) / 3;
1050         lastpframe = ints.get(2) % 3;
1051         torange.add(new Integer(lastppos));
1052       }
1053     }
1054     // from and to ranges must end up being a series of start/end intervals
1055     if (fromrange.size() % 2 == 1)
1056     {
1057       throw new InvalidGFF3FieldException(attr, set,
1058               "Couldn't parse the DNA alignment range correctly");
1059     }
1060     if (torange.size() % 2 == 1)
1061     {
1062       throw new InvalidGFF3FieldException(attr, set,
1063               "Couldn't parse the protein alignment range correctly");
1064     }
1065     // finally, build the map
1066     int[] frommap = new int[fromrange.size()], tomap = new int[torange
1067             .size()];
1068     int p = 0;
1069     for (Integer ip : fromrange)
1070     {
1071       frommap[p++] = ip.intValue();
1072     }
1073     p = 0;
1074     for (Integer ip : torange)
1075     {
1076       tomap[p++] = ip.intValue();
1077     }
1078
1079     return new MapList(frommap, tomap, 3, 1);
1080   }
1081
1082   private List<SequenceI> findNames(AlignmentI align,
1083           List<SequenceI> newseqs, boolean relaxedIdMatching,
1084           List<String> list)
1085   {
1086     List<SequenceI> found = new ArrayList<SequenceI>();
1087     for (String seqId : list)
1088     {
1089       SequenceI seq = findName(align, seqId, relaxedIdMatching, newseqs);
1090       if (seq != null)
1091       {
1092         found.add(seq);
1093       }
1094     }
1095     return found;
1096   }
1097
1098   private AlignmentI lastmatchedAl = null;
1099
1100   private SequenceIdMatcher matcher = null;
1101
1102   /**
1103    * clear any temporary handles used to speed up ID matching
1104    */
1105   private void resetMatcher()
1106   {
1107     lastmatchedAl = null;
1108     matcher = null;
1109   }
1110
1111   private SequenceI findName(AlignmentI align, String seqId,
1112           boolean relaxedIdMatching, List<SequenceI> newseqs)
1113   {
1114     SequenceI match = null;
1115     if (relaxedIdMatching)
1116     {
1117       if (lastmatchedAl != align)
1118       {
1119         matcher = new SequenceIdMatcher(
1120                 (lastmatchedAl = align).getSequencesArray());
1121         if (newseqs != null)
1122         {
1123           matcher.addAll(newseqs);
1124         }
1125       }
1126       match = matcher.findIdMatch(seqId);
1127     }
1128     else
1129     {
1130       match = align.findName(seqId, true);
1131       if (match == null && newseqs != null)
1132       {
1133         for (SequenceI m : newseqs)
1134         {
1135           if (seqId.equals(m.getName()))
1136           {
1137             return m;
1138           }
1139         }
1140       }
1141
1142     }
1143     if (match == null && newseqs != null)
1144     {
1145       match = new SequenceDummy(seqId);
1146       if (relaxedIdMatching)
1147       {
1148         matcher.addAll(Arrays.asList(new SequenceI[] { match }));
1149       }
1150       // add dummy sequence to the newseqs list
1151       newseqs.add(match);
1152     }
1153     return match;
1154   }
1155
1156   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
1157   {
1158     if (sf.getDescription() == null)
1159     {
1160       return;
1161     }
1162     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
1163             sf.getDescription(), removeHTML, newline);
1164
1165     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
1166             : sf.description;
1167     for (String link : parsed.getLinks())
1168     {
1169       sf.addLink(link);
1170     }
1171
1172   }
1173
1174   /**
1175    * generate a features file for seqs includes non-pos features by default.
1176    * 
1177    * @param seqs
1178    *          source of sequence features
1179    * @param visible
1180    *          hash of feature types and colours
1181    * @return features file contents
1182    */
1183   public String printJalviewFormat(SequenceI[] seqs,
1184           Map<String, Object> visible)
1185   {
1186     return printJalviewFormat(seqs, visible, true, true);
1187   }
1188
1189   /**
1190    * generate a features file for seqs with colours from visible (if any)
1191    * 
1192    * @param seqs
1193    *          source of features
1194    * @param visible
1195    *          hash of Colours for each feature type
1196    * @param visOnly
1197    *          when true only feature types in 'visible' will be output
1198    * @param nonpos
1199    *          indicates if non-positional features should be output (regardless
1200    *          of group or type)
1201    * @return features file contents
1202    */
1203   public String printJalviewFormat(SequenceI[] seqs, Map visible,
1204           boolean visOnly, boolean nonpos)
1205   {
1206     StringBuffer out = new StringBuffer();
1207     SequenceFeature[] next;
1208     boolean featuresGen = false;
1209     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
1210     {
1211       // no point continuing.
1212       return "No Features Visible";
1213     }
1214
1215     if (visible != null && visOnly)
1216     {
1217       // write feature colours only if we're given them and we are generating
1218       // viewed features
1219       // TODO: decide if feature links should also be written here ?
1220       Iterator en = visible.keySet().iterator();
1221       String type, color;
1222       while (en.hasNext())
1223       {
1224         type = en.next().toString();
1225
1226         if (visible.get(type) instanceof GraduatedColor)
1227         {
1228           GraduatedColor gc = (GraduatedColor) visible.get(type);
1229           color = (gc.isColourByLabel() ? "label|" : "")
1230                   + Format.getHexString(gc.getMinColor()) + "|"
1231                   + Format.getHexString(gc.getMaxColor())
1232                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
1233                   + gc.getMax() + "|";
1234           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
1235           {
1236             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1237             {
1238               color += "below";
1239             }
1240             else
1241             {
1242               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
1243               {
1244                 System.err.println("WARNING: Unsupported threshold type ("
1245                         + gc.getThreshType() + ") : Assuming 'above'");
1246               }
1247               color += "above";
1248             }
1249             // add the value
1250             color += "|" + gc.getThresh();
1251           }
1252           else
1253           {
1254             color += "none";
1255           }
1256         }
1257         else if (visible.get(type) instanceof java.awt.Color)
1258         {
1259           color = Format.getHexString((java.awt.Color) visible.get(type));
1260         }
1261         else
1262         {
1263           // legacy support for integer objects containing colour triplet values
1264           color = Format.getHexString(new java.awt.Color(Integer
1265                   .parseInt(visible.get(type).toString())));
1266         }
1267         out.append(type);
1268         out.append("\t");
1269         out.append(color);
1270         out.append(newline);
1271       }
1272     }
1273     // Work out which groups are both present and visible
1274     Vector groups = new Vector();
1275     int groupIndex = 0;
1276     boolean isnonpos = false;
1277
1278     for (int i = 0; i < seqs.length; i++)
1279     {
1280       next = seqs[i].getSequenceFeatures();
1281       if (next != null)
1282       {
1283         for (int j = 0; j < next.length; j++)
1284         {
1285           isnonpos = next[j].begin == 0 && next[j].end == 0;
1286           if ((!nonpos && isnonpos)
1287                   || (!isnonpos && visOnly && !visible
1288                           .containsKey(next[j].type)))
1289           {
1290             continue;
1291           }
1292
1293           if (next[j].featureGroup != null
1294                   && !groups.contains(next[j].featureGroup))
1295           {
1296             groups.addElement(next[j].featureGroup);
1297           }
1298         }
1299       }
1300     }
1301
1302     String group = null;
1303     do
1304     {
1305
1306       if (groups.size() > 0 && groupIndex < groups.size())
1307       {
1308         group = groups.elementAt(groupIndex).toString();
1309         out.append(newline);
1310         out.append("STARTGROUP\t");
1311         out.append(group);
1312         out.append(newline);
1313       }
1314       else
1315       {
1316         group = null;
1317       }
1318
1319       for (int i = 0; i < seqs.length; i++)
1320       {
1321         next = seqs[i].getSequenceFeatures();
1322         if (next != null)
1323         {
1324           for (int j = 0; j < next.length; j++)
1325           {
1326             isnonpos = next[j].begin == 0 && next[j].end == 0;
1327             if ((!nonpos && isnonpos)
1328                     || (!isnonpos && visOnly && !visible
1329                             .containsKey(next[j].type)))
1330             {
1331               // skip if feature is nonpos and we ignore them or if we only
1332               // output visible and it isn't non-pos and it's not visible
1333               continue;
1334             }
1335
1336             if (group != null
1337                     && (next[j].featureGroup == null || !next[j].featureGroup
1338                             .equals(group)))
1339             {
1340               continue;
1341             }
1342
1343             if (group == null && next[j].featureGroup != null)
1344             {
1345               continue;
1346             }
1347             // we have features to output
1348             featuresGen = true;
1349             if (next[j].description == null
1350                     || next[j].description.equals(""))
1351             {
1352               out.append(next[j].type + "\t");
1353             }
1354             else
1355             {
1356               if (next[j].links != null
1357                       && next[j].getDescription().indexOf("<html>") == -1)
1358               {
1359                 out.append("<html>");
1360               }
1361
1362               out.append(next[j].description + " ");
1363               if (next[j].links != null)
1364               {
1365                 for (int l = 0; l < next[j].links.size(); l++)
1366                 {
1367                   String label = next[j].links.elementAt(l).toString();
1368                   String href = label.substring(label.indexOf("|") + 1);
1369                   label = label.substring(0, label.indexOf("|"));
1370
1371                   if (next[j].description.indexOf(href) == -1)
1372                   {
1373                     out.append("<a href=\"" + href + "\">" + label + "</a>");
1374                   }
1375                 }
1376
1377                 if (next[j].getDescription().indexOf("</html>") == -1)
1378                 {
1379                   out.append("</html>");
1380                 }
1381               }
1382
1383               out.append("\t");
1384             }
1385             out.append(seqs[i].getName());
1386             out.append("\t-1\t");
1387             out.append(next[j].begin);
1388             out.append("\t");
1389             out.append(next[j].end);
1390             out.append("\t");
1391             out.append(next[j].type);
1392             if (!Float.isNaN(next[j].score))
1393             {
1394               out.append("\t");
1395               out.append(next[j].score);
1396             }
1397             out.append(newline);
1398           }
1399         }
1400       }
1401
1402       if (group != null)
1403       {
1404         out.append("ENDGROUP\t");
1405         out.append(group);
1406         out.append(newline);
1407         groupIndex++;
1408       }
1409       else
1410       {
1411         break;
1412       }
1413
1414     } while (groupIndex < groups.size() + 1);
1415
1416     if (!featuresGen)
1417     {
1418       return "No Features Visible";
1419     }
1420
1421     return out.toString();
1422   }
1423
1424   /**
1425    * generate a gff file for sequence features includes non-pos features by
1426    * default.
1427    * 
1428    * @param seqs
1429    * @param visible
1430    * @return
1431    */
1432   public String printGFFFormat(SequenceI[] seqs, Map<String, Object> visible)
1433   {
1434     return printGFFFormat(seqs, visible, true, true);
1435   }
1436
1437   public String printGFFFormat(SequenceI[] seqs,
1438           Map<String, Object> visible, boolean visOnly, boolean nonpos)
1439   {
1440     StringBuffer out = new StringBuffer();
1441     SequenceFeature[] next;
1442     String source;
1443     boolean isnonpos;
1444     for (int i = 0; i < seqs.length; i++)
1445     {
1446       if (seqs[i].getSequenceFeatures() != null)
1447       {
1448         next = seqs[i].getSequenceFeatures();
1449         for (int j = 0; j < next.length; j++)
1450         {
1451           isnonpos = next[j].begin == 0 && next[j].end == 0;
1452           if ((!nonpos && isnonpos)
1453                   || (!isnonpos && visOnly && !visible
1454                           .containsKey(next[j].type)))
1455           {
1456             continue;
1457           }
1458
1459           source = next[j].featureGroup;
1460           if (source == null)
1461           {
1462             source = next[j].getDescription();
1463           }
1464
1465           out.append(seqs[i].getName());
1466           out.append("\t");
1467           out.append(source);
1468           out.append("\t");
1469           out.append(next[j].type);
1470           out.append("\t");
1471           out.append(next[j].begin);
1472           out.append("\t");
1473           out.append(next[j].end);
1474           out.append("\t");
1475           out.append(next[j].score);
1476           out.append("\t");
1477
1478           if (next[j].getValue("STRAND") != null)
1479           {
1480             out.append(next[j].getValue("STRAND"));
1481             out.append("\t");
1482           }
1483           else
1484           {
1485             out.append(".\t");
1486           }
1487
1488           if (next[j].getValue("FRAME") != null)
1489           {
1490             out.append(next[j].getValue("FRAME"));
1491           }
1492           else
1493           {
1494             out.append(".");
1495           }
1496           // TODO: verify/check GFF - should there be a /t here before attribute
1497           // output ?
1498
1499           if (next[j].getValue("ATTRIBUTES") != null)
1500           {
1501             out.append(next[j].getValue("ATTRIBUTES"));
1502           }
1503
1504           out.append(newline);
1505
1506         }
1507       }
1508     }
1509
1510     return out.toString();
1511   }
1512
1513   /**
1514    * this is only for the benefit of object polymorphism - method does nothing.
1515    */
1516   public void parse()
1517   {
1518     // IGNORED
1519   }
1520
1521   /**
1522    * this is only for the benefit of object polymorphism - method does nothing.
1523    * 
1524    * @return error message
1525    */
1526   public String print()
1527   {
1528     return "USE printGFFFormat() or printJalviewFormat()";
1529   }
1530
1531 }