6f514203088bf246329d5d629b62cd0bbfeaa165
[jalview.git] / src / jalview / datamodel / SequenceFeature.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.datamodel;
22
23 import jalview.datamodel.features.FeatureAttributeType;
24 import jalview.datamodel.features.FeatureAttributes;
25 import jalview.datamodel.features.FeatureLocationI;
26 import jalview.datamodel.features.FeatureSourceI;
27 import jalview.datamodel.features.FeatureSources;
28 import jalview.util.StringUtils;
29
30 import java.util.Comparator;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.SortedMap;
35 import java.util.TreeMap;
36 import java.util.Vector;
37
38 import intervalstore.api.IntervalI;
39
40 /**
41  * A class that models a single contiguous feature on a sequence. If flag
42  * 'contactFeature' is true, the start and end positions are interpreted instead
43  * as two contact points.
44  */
45 public class SequenceFeature implements FeatureLocationI
46 {
47   /*
48    * score value if none is set; preferably Float.Nan, but see
49    * JAL-2060 and JAL-2554 for a couple of blockers to that
50    */
51   private static final float NO_SCORE = 0f;
52
53   private static final String STATUS = "status";
54
55   private static final String STRAND = "STRAND";
56
57   // private key for Phase designed not to conflict with real GFF data
58   private static final String PHASE = "!Phase";
59
60   // private key for ENA location designed not to conflict with real GFF data
61   private static final String LOCATION = "!Location";
62
63   private static final String ROW_DATA = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>";
64
65   /*
66    * ATTRIBUTES is reserved for the GFF 'column 9' data, formatted as
67    * name1=value1;name2=value2,value3;...etc
68    */
69   private static final String ATTRIBUTES = "ATTRIBUTES";
70
71   /*
72    * type, begin, end, featureGroup, score and contactFeature are final 
73    * to ensure that the integrity of SequenceFeatures data store 
74    * can't be broken by direct update of these fields
75    */
76   public final String type;
77
78   public final int begin;
79
80   public final int end;
81
82   public final String featureGroup;
83
84   public final float score;
85
86   private final boolean contactFeature;
87
88   public String description;
89
90   /*
91    * a map of key-value pairs; may be populated from GFF 'column 9' data,
92    * other data sources (e.g. GenBank file), or programmatically
93    */
94   public Map<String, Object> otherDetails;
95
96   public Vector<String> links;
97
98   /*
99    * the identifier (if known) for the FeatureSource held in FeatureSources,
100    * as a provider of metadata about feature attributes 
101    */
102   private String source;
103
104   /**
105    * Constructs a duplicate feature. Note: Uses makes a shallow copy of the
106    * otherDetails map, so the new and original SequenceFeature may reference the
107    * same objects in the map.
108    * 
109    * @param cpy
110    */
111   public SequenceFeature(SequenceFeature cpy)
112   {
113     this(cpy, cpy.getBegin(), cpy.getEnd(), cpy.getFeatureGroup(), cpy
114             .getScore());
115   }
116
117   /**
118    * Constructor
119    * 
120    * @param theType
121    * @param theDesc
122    * @param theBegin
123    * @param theEnd
124    * @param group
125    */
126   public SequenceFeature(String theType, String theDesc, int theBegin,
127           int theEnd, String group)
128   {
129     this(theType, theDesc, theBegin, theEnd, NO_SCORE, group);
130   }
131
132   /**
133    * Constructor including a score value
134    * 
135    * @param theType
136    * @param theDesc
137    * @param theBegin
138    * @param theEnd
139    * @param theScore
140    * @param group
141    */
142   public SequenceFeature(String theType, String theDesc, int theBegin,
143           int theEnd, float theScore, String group)
144   {
145     this.type = theType;
146     this.description = theDesc;
147     this.begin = theBegin;
148     this.end = theEnd;
149     this.featureGroup = group;
150     this.score = theScore;
151
152     /*
153      * for now, only "Disulfide/disulphide bond" is treated as a contact feature
154      */
155     this.contactFeature = "disulfide bond".equalsIgnoreCase(type)
156             || "disulphide bond".equalsIgnoreCase(type);
157   }
158
159   /**
160    * A copy constructor that allows the value of final fields to be 'modified'
161    * 
162    * @param sf
163    * @param newType
164    * @param newBegin
165    * @param newEnd
166    * @param newGroup
167    * @param newScore
168    */
169   public SequenceFeature(SequenceFeature sf, String newType, int newBegin,
170           int newEnd, String newGroup, float newScore)
171   {
172     this(newType, sf.getDescription(), newBegin, newEnd, newScore,
173             newGroup);
174
175     this.source = sf.source;
176
177     if (sf.otherDetails != null)
178     {
179       otherDetails = new HashMap<>();
180       for (Entry<String, Object> entry : sf.otherDetails.entrySet())
181       {
182         otherDetails.put(entry.getKey(), entry.getValue());
183       }
184     }
185     if (sf.links != null && sf.links.size() > 0)
186     {
187       links = new Vector<>();
188       for (int i = 0, iSize = sf.links.size(); i < iSize; i++)
189       {
190         links.addElement(sf.links.elementAt(i));
191       }
192     }
193   }
194
195   /**
196    * A copy constructor that allows the value of final fields to be 'modified'
197    * 
198    * @param sf
199    * @param newBegin
200    * @param newEnd
201    * @param newGroup
202    * @param newScore
203    */
204   public SequenceFeature(SequenceFeature sf, int newBegin, int newEnd,
205           String newGroup, float newScore)
206   {
207     this(sf, sf.getType(), newBegin, newEnd, newGroup, newScore);
208   }
209
210   /**
211    * Two features are considered equal if they have the same type, group,
212    * description, start, end, phase, strand, and (if present) 'Name', ID' and
213    * 'Parent' attributes.
214    * 
215    * Note we need to check Parent to distinguish the same exon occurring in
216    * different transcripts (in Ensembl GFF). This allows assembly of transcript
217    * sequences from their component exon regions.
218    */
219   @Override
220   public boolean equals(Object o)
221   {
222     return (o != null && (o instanceof SequenceFeature)
223             && equalsInterval((SequenceFeature) o));
224   }
225
226   /**
227    * Having determined that this is in fact a SequenceFeature, now check it for
228    * equivalence. Overridden in CrossRef; used by IntervalStore (possibly).
229    */
230   @Override
231   public boolean equalsInterval(IntervalI sf)
232   {
233     return equals((SequenceFeature) sf, false);
234   }
235   /**
236    * Overloaded method allows the equality test to optionally ignore the
237    * 'Parent' attribute of a feature. This supports avoiding adding many
238    * superficially duplicate 'exon' or CDS features to genomic or protein
239    * sequence.
240    * 
241    * @param o
242    * @param ignoreParent
243    * @return
244    */
245   public boolean equals(SequenceFeature sf, boolean ignoreParent)
246   {
247     boolean sameScore = Float.isNaN(score) ? Float.isNaN(sf.score)
248             : score == sf.score;
249     if (begin != sf.begin || end != sf.end || !sameScore)
250     {
251       return false;
252     }
253
254     if (getStrand() != sf.getStrand())
255     {
256       return false;
257     }
258
259     if (!(type + description + featureGroup + getPhase()).equals(
260             sf.type + sf.description + sf.featureGroup + sf.getPhase()))
261     {
262       return false;
263     }
264     if (!equalAttribute(getValue("ID"), sf.getValue("ID")))
265     {
266       return false;
267     }
268     if (!equalAttribute(getValue("Name"), sf.getValue("Name")))
269     {
270       return false;
271     }
272     if (!ignoreParent)
273     {
274       if (!equalAttribute(getValue("Parent"), sf.getValue("Parent")))
275       {
276         return false;
277       }
278     }
279     return true;
280   }
281
282   /**
283    * Returns true if both values are null, are both non-null and equal
284    * 
285    * @param att1
286    * @param att2
287    * @return
288    */
289   protected static boolean equalAttribute(Object att1, Object att2)
290   {
291     if (att1 == null && att2 == null)
292     {
293       return true;
294     }
295     if (att1 != null)
296     {
297       return att1.equals(att2);
298     }
299     return att2.equals(att1);
300   }
301
302   /**
303    * DOCUMENT ME!
304    * 
305    * @return DOCUMENT ME!
306    */
307   @Override
308   public int getBegin()
309   {
310     return begin;
311   }
312
313   /**
314    * DOCUMENT ME!
315    * 
316    * @return DOCUMENT ME!
317    */
318   @Override
319   public int getEnd()
320   {
321     return end;
322   }
323
324   /**
325    * DOCUMENT ME!
326    * 
327    * @return DOCUMENT ME!
328    */
329   public String getType()
330   {
331     return type;
332   }
333
334   /**
335    * DOCUMENT ME!
336    * 
337    * @return DOCUMENT ME!
338    */
339   public String getDescription()
340   {
341     return description;
342   }
343
344   public void setDescription(String desc)
345   {
346     description = desc;
347   }
348
349   public String getFeatureGroup()
350   {
351     return featureGroup;
352   }
353
354   public void addLink(String labelLink)
355   {
356     if (links == null)
357     {
358       links = new Vector<>();
359     }
360
361     if (!links.contains(labelLink))
362     {
363       links.insertElementAt(labelLink, 0);
364     }
365   }
366
367   public float getScore()
368   {
369     return score;
370   }
371
372   /**
373    * Used for getting values which are not in the basic set. eg STRAND, PHASE
374    * for GFF file
375    * 
376    * @param key
377    *          String
378    */
379   public Object getValue(String key)
380   {
381     if (otherDetails == null)
382     {
383       return null;
384     }
385     else
386     {
387       return otherDetails.get(key);
388     }
389   }
390
391   /**
392    * Answers the value of the specified attribute as string, or null if no such
393    * value. If more than one attribute name is provided, tries to resolve as keys
394    * to nested maps. For example, if attribute "CSQ" holds a map of key-value
395    * pairs, then getValueAsString("CSQ", "Allele") returns the value of "Allele"
396    * in that map.
397    * 
398    * @param key
399    * @return
400    */
401   public String getValueAsString(String... key)
402   {
403     if (otherDetails == null)
404     {
405       return null;
406     }
407     Object value = otherDetails.get(key[0]);
408     if (key.length > 1 && value instanceof Map<?, ?>)
409     {
410       value = ((Map) value).get(key[1]);
411     }
412     return value == null ? null : value.toString();
413   }
414
415   /**
416    * Returns a property value for the given key if known, else the specified
417    * default value
418    * 
419    * @param key
420    * @param defaultValue
421    * @return
422    */
423   public Object getValue(String key, Object defaultValue)
424   {
425     Object value = getValue(key);
426     return value == null ? defaultValue : value;
427   }
428
429   /**
430    * Used for setting values which are not in the basic set. eg STRAND, FRAME
431    * for GFF file
432    * 
433    * @param key
434    *          eg STRAND
435    * @param value
436    *          eg +
437    */
438   public void setValue(String key, Object value)
439   {
440     if (value != null)
441     {
442       if (otherDetails == null)
443       {
444         otherDetails = new HashMap<>();
445       }
446
447       otherDetails.put(key, value);
448       recordAttribute(key, value);
449     }
450   }
451
452   /**
453    * Notifies the addition of a feature attribute. This lets us keep track of
454    * which attributes are present on each feature type, and also the range of
455    * numerical-valued attributes.
456    * 
457    * @param key
458    * @param value
459    */
460   protected void recordAttribute(String key, Object value)
461   {
462     String attDesc = null;
463     if (source != null)
464     {
465       attDesc = FeatureSources.getInstance().getSource(source)
466               .getAttributeName(key);
467     }
468
469     FeatureAttributes.getInstance().addAttribute(this.type, attDesc, value,
470             key);
471   }
472
473   /*
474    * The following methods are added to maintain the castor Uniprot mapping file
475    * for the moment.
476    */
477   public void setStatus(String status)
478   {
479     setValue(STATUS, status);
480   }
481
482   public String getStatus()
483   {
484     return (String) getValue(STATUS);
485   }
486
487   public void setAttributes(String attr)
488   {
489     setValue(ATTRIBUTES, attr);
490   }
491
492   public String getAttributes()
493   {
494     return (String) getValue(ATTRIBUTES);
495   }
496
497   /**
498    * Return 1 for forward strand ('+' in GFF), -1 for reverse strand ('-' in
499    * GFF), and 0 for unknown or not (validly) specified
500    * 
501    * @return
502    */
503   public int getStrand()
504   {
505     int strand = 0;
506     if (otherDetails != null)
507     {
508       Object str = otherDetails.get(STRAND);
509       if ("-".equals(str))
510       {
511         strand = -1;
512       }
513       else if ("+".equals(str))
514       {
515         strand = 1;
516       }
517     }
518     return strand;
519   }
520
521   /**
522    * Set the value of strand
523    * 
524    * @param strand
525    *          should be "+" for forward, or "-" for reverse
526    */
527   public void setStrand(String strand)
528   {
529     setValue(STRAND, strand);
530   }
531
532   public void setPhase(String phase)
533   {
534     setValue(PHASE, phase);
535   }
536
537   public String getPhase()
538   {
539     return (String) getValue(PHASE);
540   }
541
542   /**
543    * Sets the 'raw' ENA format location specifier e.g. join(12..45,89..121)
544    * 
545    * @param loc
546    */
547   public void setEnaLocation(String loc)
548   {
549     setValue(LOCATION, loc);
550   }
551
552   /**
553    * Gets the 'raw' ENA format location specifier e.g. join(12..45,89..121)
554    * 
555    * @param loc
556    */
557   public String getEnaLocation()
558   {
559     return (String) getValue(LOCATION);
560   }
561
562   /**
563    * Readable representation, for debug only, not guaranteed not to change
564    * between versions
565    */
566   @Override
567   public String toString()
568   {
569     return String.format("%d %d %s %s", getBegin(), getEnd(), getType(),
570             getDescription());
571   }
572
573   /**
574    * Overridden to ensure that whenever two objects are equal, they have the
575    * same hashCode
576    */
577   @Override
578   public int hashCode()
579   {
580     String s = getType() + getDescription() + getFeatureGroup()
581             + getValue("ID") + getValue("Name") + getValue("Parent")
582             + getPhase();
583     return s.hashCode() + getBegin() + getEnd() + (int) getScore()
584             + getStrand();
585   }
586
587   /**
588    * Answers true if the feature's start/end values represent two related
589    * positions, rather than ends of a range. Such features may be visualised or
590    * reported differently to features on a range.
591    */
592   @Override
593   public boolean isContactFeature()
594   {
595     return contactFeature;
596   }
597
598   /**
599    * Answers true if the sequence has zero start and end position
600    * 
601    * @return
602    */
603   public boolean isNonPositional()
604   {
605     return begin == 0 && end == 0;
606   }
607
608   /**
609    * Answers an html-formatted report of feature details
610    * 
611    * @return
612    */
613   public String getDetailsReport()
614   {
615     FeatureSourceI metadata = FeatureSources.getInstance()
616             .getSource(source);
617
618     StringBuilder sb = new StringBuilder(128);
619     sb.append("<br>");
620     sb.append("<table>");
621     sb.append(String.format(ROW_DATA, "Type", type, ""));
622     sb.append(String.format(ROW_DATA, "Start/end", begin == end ? begin
623             : begin + (isContactFeature() ? ":" : "-") + end, ""));
624     String desc = StringUtils.stripHtmlTags(description);
625     sb.append(String.format(ROW_DATA, "Description", desc, ""));
626     if (!Float.isNaN(score) && score != 0f)
627     {
628       sb.append(String.format(ROW_DATA, "Score", score, ""));
629     }
630     if (featureGroup != null)
631     {
632       sb.append(String.format(ROW_DATA, "Group", featureGroup, ""));
633     }
634
635     if (otherDetails != null)
636     {
637       TreeMap<String, Object> ordered = new TreeMap<>(
638               String.CASE_INSENSITIVE_ORDER);
639       ordered.putAll(otherDetails);
640
641       for (Entry<String, Object> entry : ordered.entrySet())
642       {
643         String key = entry.getKey();
644         if (ATTRIBUTES.equals(key))
645         {
646           continue; // to avoid double reporting
647         }
648
649         Object value = entry.getValue();
650         if (value instanceof Map<?, ?>)
651         {
652           /*
653            * expand values in a Map attribute across separate lines
654            * copy to a TreeMap for alphabetical ordering
655            */
656           Map<String, Object> values = (Map<String, Object>) value;
657           SortedMap<String, Object> sm = new TreeMap<>(
658                   String.CASE_INSENSITIVE_ORDER);
659           sm.putAll(values);
660           for (Entry<?, ?> e : sm.entrySet())
661           {
662             sb.append(String.format(ROW_DATA, key, e.getKey().toString(), e
663                     .getValue().toString()));
664           }
665         }
666         else
667         {
668           // tried <td title="key"> but it failed to provide a tooltip :-(
669           String attDesc = null;
670           if (metadata != null)
671           {
672             attDesc = metadata.getAttributeName(key);
673           }
674           String s = entry.getValue().toString();
675           if (isValueInteresting(key, s, metadata))
676           {
677             sb.append(String.format(ROW_DATA, key, attDesc == null ? ""
678                     : attDesc, s));
679           }
680         }
681       }
682     }
683     sb.append("</table>");
684
685     String text = sb.toString();
686     return text;
687   }
688
689   /**
690    * Answers true if we judge the value is worth displaying, by some heuristic
691    * rules, else false
692    * 
693    * @param key
694    * @param value
695    * @param metadata
696    * @return
697    */
698   boolean isValueInteresting(String key, String value,
699           FeatureSourceI metadata)
700   {
701     /*
702      * currently suppressing zero values as well as null or empty
703      */
704     if (value == null || "".equals(value) || ".".equals(value)
705             || "0".equals(value))
706     {
707       return false;
708     }
709
710     if (metadata == null)
711     {
712       return true;
713     }
714
715     FeatureAttributeType attType = metadata.getAttributeType(key);
716     if (attType != null
717             && (attType == FeatureAttributeType.Float || attType
718                     .equals(FeatureAttributeType.Integer)))
719     {
720       try
721       {
722         float fval = Float.valueOf(value);
723         if (fval == 0f)
724         {
725           return false;
726         }
727       } catch (NumberFormatException e)
728       {
729         // ignore
730       }
731     }
732
733     return true; // default to interesting
734   }
735
736   /**
737    * Sets the feature source identifier
738    * 
739    * @param theSource
740    */
741   public void setSource(String theSource)
742   {
743     source = theSource;
744   }
745
746  
747 }
748
749 class SFSortByEnd implements Comparator<SequenceFeature>
750 {
751   @Override
752   public int compare(SequenceFeature a, SequenceFeature b)
753   {
754     return a.getEnd() - b.getEnd();
755   }
756 }
757
758 class SFSortByBegin implements Comparator<SequenceFeature>
759 {
760   @Override
761   public int compare(SequenceFeature a, SequenceFeature b)
762   {
763     return a.getBegin() - b.getBegin();
764   }
765 }