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