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