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