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