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