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