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