copying sequenceMapping, restrict(alstart/end) and pad(alwidth) method.
[jalview.git] / src / jalview / datamodel / AlignmentAnnotation.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.datamodel;
20
21 import java.util.Enumeration;
22 import java.util.Hashtable;
23
24 /**
25  * DOCUMENT ME!
26  *
27  * @author $author$
28  * @version $Revision$
29  */
30 public class AlignmentAnnotation
31 {
32   /** If true, this annotations is calculated every edit,
33    * eg consensus, quality or conservation graphs */
34   public boolean autoCalculated = false;
35
36   public String annotationId;
37
38   public SequenceI sequenceRef;
39
40   /** DOCUMENT ME!! */
41   public String label;
42
43   /** DOCUMENT ME!! */
44   public String description;
45
46   /** DOCUMENT ME!! */
47   public Annotation[] annotations;
48
49   public java.util.Hashtable sequenceMapping;
50
51   /** DOCUMENT ME!! */
52   public float graphMin;
53
54   /** DOCUMENT ME!! */
55   public float graphMax;
56
57   public GraphLine threshold;
58
59   // Graphical hints and tips
60
61   /** DOCUMENT ME!! */
62   public boolean editable = false;
63
64   /** DOCUMENT ME!! */
65   public boolean hasIcons; //
66
67   /** DOCUMENT ME!! */
68   public boolean hasText;
69
70   /** DOCUMENT ME!! */
71   public boolean visible = true;
72
73   public int graphGroup = -1;
74
75   /** DOCUMENT ME!! */
76   public int height = 0;
77
78   public int graph = 0;
79
80   public int graphHeight = 40;
81
82   public boolean padGaps = true;
83
84   public static final int NO_GRAPH = 0;
85
86   public static final int BAR_GRAPH = 1;
87
88   public static final int LINE_GRAPH = 2;
89
90   public static int getGraphValueFromString(String string)
91   {
92     if (string.equalsIgnoreCase("BAR_GRAPH"))
93     {
94       return BAR_GRAPH;
95     }
96     else if (string.equalsIgnoreCase("LINE_GRAPH"))
97     {
98       return LINE_GRAPH;
99     }
100     else
101     {
102       return NO_GRAPH;
103     }
104   }
105
106   /**
107    * Creates a new AlignmentAnnotation object.
108    *
109    * @param label DOCUMENT ME!
110    * @param description DOCUMENT ME!
111    * @param annotations DOCUMENT ME!
112    */
113   public AlignmentAnnotation(String label, String description,
114                              Annotation[] annotations)
115   {
116     // always editable?
117     editable = true;
118     this.label = label;
119     this.description = description;
120     this.annotations = annotations;
121
122      validateRangeAndDisplay();
123   }
124
125   void areLabelsSecondaryStructure()
126   {
127     boolean nonSSLabel = false;
128     for (int i = 0; i < annotations.length; i++)
129     {
130       if (annotations[i] == null)
131       {
132         padGaps = false;
133         continue;
134       }
135
136       if (annotations[i].secondaryStructure == 'H' ||
137           annotations[i].secondaryStructure == 'E')
138       {
139         hasIcons = true;
140       }
141
142       if (annotations[i].displayCharacter.length() == 1
143           && !annotations[i].displayCharacter.equals("H")
144           && !annotations[i].displayCharacter.equals("E")
145           && !annotations[i].displayCharacter.equals("-")
146           && !annotations[i].displayCharacter.equals("."))
147       {
148         if (jalview.schemes.ResidueProperties.aaIndex
149             [annotations[i].displayCharacter.charAt(0)] < 23)
150         {
151           nonSSLabel = true;
152         }
153       }
154
155       if (annotations[i].displayCharacter.length() > 0)
156       {
157         hasText = true;
158       }
159       else
160         padGaps = false;
161     }
162
163
164     if (nonSSLabel)
165     {
166       hasIcons = false;
167       for (int j = 0; j < annotations.length; j++)
168       {
169         if (annotations[j] != null && annotations[j].secondaryStructure != ' ')
170         {
171           annotations[j].displayCharacter
172               = String.valueOf(annotations[j].secondaryStructure);
173           annotations[j].secondaryStructure = ' ';
174         }
175
176       }
177     }
178
179     annotationId = this.hashCode() + "";
180   }
181   /**
182    * Creates a new AlignmentAnnotation object.
183    *
184    * @param label DOCUMENT ME!
185    * @param description DOCUMENT ME!
186    * @param annotations DOCUMENT ME!
187    * @param min DOCUMENT ME!
188    * @param max DOCUMENT ME!
189    * @param winLength DOCUMENT ME!
190    */
191   public AlignmentAnnotation(String label, String description,
192                              Annotation[] annotations, float min, float max,
193                              int graphType)
194   {
195     // graphs are not editable
196     editable = graphType==0;
197
198     this.label = label;
199     this.description = description;
200     this.annotations = annotations;
201     graph = graphType;
202     graphMin = min;
203     graphMax = max;
204     validateRangeAndDisplay();
205   }
206   /**
207    * checks graphMin and graphMax,
208    * secondary structure symbols,
209    * sets graphType appropriately,
210    * sets null labels to the empty string
211    * if appropriate.
212    */
213   private void validateRangeAndDisplay() {
214     int graphType = graph;
215     float min = graphMin;
216     float max = graphMax;
217     boolean drawValues = true;
218
219     if (min == max)
220     {
221       min = 999999999;
222       for (int i = 0; i < annotations.length; i++)
223       {
224         if (annotations[i] == null)
225         {
226           continue;
227         }
228
229         if (drawValues && annotations[i].displayCharacter.length() > 1)
230         {
231           drawValues = false;
232         }
233
234         if (annotations[i].value > max)
235         {
236           max = annotations[i].value;
237         }
238
239         if (annotations[i].value < min)
240         {
241           min = annotations[i].value;
242         }
243       }
244     }
245
246     graphMin = min;
247     graphMax = max;
248
249     areLabelsSecondaryStructure();
250
251     if (!drawValues && graphType != NO_GRAPH)
252     {
253       for (int i = 0; i < annotations.length; i++)
254       {
255         if (annotations[i] != null)
256         {
257           annotations[i].displayCharacter = "";
258         }
259       }
260     }
261   }
262
263   /**
264    * Copy constructor
265    * creates a new independent annotation row with the same associated sequenceRef
266    * @param annotation
267    */
268   public AlignmentAnnotation(AlignmentAnnotation annotation)
269   {
270     this.label = new String(annotation.label);
271     if (annotation.description != null)
272       this.description = new String(annotation.description);
273     this.graphMin = annotation.graphMin;
274     this.graphMax = annotation.graphMax;
275     this.graph = annotation.graph;
276     this.graphHeight = annotation.graphHeight;
277     this.graphGroup = annotation.graphGroup;
278     this.editable = annotation.editable;
279     this.autoCalculated = annotation.autoCalculated;
280     this.hasIcons = annotation.hasIcons;
281     this.hasText = annotation.hasText;
282     this.height = annotation.height;
283     this.label = annotation.label;
284     if (threshold!=null) {
285       threshold = new GraphLine(annotation.threshold);
286     }
287     if (annotation.annotations!=null) {
288       Annotation[] ann = annotation.annotations;
289       this.annotations = new Annotation[ann.length];
290       for (int i=0; i<ann.length; i++) {
291         annotations[i] = new Annotation(ann[i]);
292       };
293       if (annotation.sequenceRef!=null) {
294         this.sequenceRef = annotation.sequenceRef;
295         if (annotation.sequenceMapping!=null)
296         {
297           Integer p=null;
298           sequenceMapping = new Hashtable();
299           Enumeration pos=annotation.sequenceMapping.keys();
300           while (pos.hasMoreElements()) {
301             // could optimise this!
302             p = (Integer) pos.nextElement();
303             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
304             if (a==null)
305             {
306               continue;
307             }
308             for (int i=0; i<ann.length; i++)
309             {
310               if (ann[i]==a) 
311               { 
312                 sequenceMapping.put(p, annotations[i]);
313               }
314             }
315           }
316         } else {
317           this.sequenceMapping = null;
318         }
319       }
320     }
321     validateRangeAndDisplay(); // construct hashcodes, etc.
322   }
323
324   /**
325    * clip the annotation to the columns given by startRes and endRes (inclusive)
326    * and prune any existing sequenceMapping to just those columns.
327    * @param startRes
328    * @param endRes
329    */
330   public void restrict(int startRes, int endRes)
331   {
332     Annotation[] temp = new Annotation[endRes-startRes+1];
333     System.arraycopy(annotations, startRes, temp, 0, endRes-startRes+1);
334     if (sequenceRef!=null) {
335       // Clip the mapping, if it exists.
336       int spos = sequenceRef.findPosition(startRes);
337       int epos = sequenceRef.findPosition(endRes);
338       if (sequenceMapping!=null)
339       {
340         Hashtable newmapping = new Hashtable();
341         Enumeration e = sequenceMapping.keys();
342         while (e.hasMoreElements())
343         {
344           Integer pos = (Integer) e.nextElement();
345           if (pos.intValue()>=spos && pos.intValue()<=epos)
346           {
347             newmapping.put(pos, sequenceMapping.get(pos));
348           }
349         }
350         sequenceMapping.clear();
351         sequenceMapping = newmapping;
352       }
353     }
354     annotations=temp;
355   }
356   /**
357    * set the annotation row to be at least length Annotations
358    * @param length minimum number of columns required in the annotation row
359    * @return false if the annotation row is greater than length
360    */
361   public boolean padAnnotation(int length) {
362     if (annotations==null)
363     {
364       annotations = new Annotation[length];
365       return true;
366     }
367     if (annotations.length<length)
368     {
369       Annotation[] na = new Annotation[length];
370       System.arraycopy(annotations, 0, na, 0, annotations.length);
371       annotations = na;
372       return true;
373     }
374     return annotations.length>length;
375     
376   }
377
378   /**
379    * DOCUMENT ME!
380    *
381    * @return DOCUMENT ME!
382    */
383   public String toString()
384   {
385     StringBuffer buffer = new StringBuffer();
386
387     for (int i = 0; i < annotations.length; i++)
388     {
389       if (annotations[i] != null)
390       {
391         if (graph != 0)
392         {
393           buffer.append(annotations[i].value);
394         }
395         else if (hasIcons)
396         {
397           buffer.append(annotations[i].secondaryStructure);
398         }
399         else
400         {
401           buffer.append(annotations[i].displayCharacter);
402         }
403       }
404
405       buffer.append(", ");
406     }
407
408     if (label.equals("Consensus"))
409     {
410       buffer.append("\n");
411
412       for (int i = 0; i < annotations.length; i++)
413       {
414         if (annotations[i] != null)
415         {
416           buffer.append(annotations[i].description);
417         }
418
419         buffer.append(", ");
420       }
421     }
422
423     return buffer.toString();
424   }
425
426   public void setThreshold(GraphLine line)
427   {
428     threshold = line;
429   }
430
431   public GraphLine getThreshold()
432   {
433     return threshold;
434   }
435
436   /**
437    * Attach the annotation to seqRef, starting from startRes position. If alreadyMapped is true then the indices of the annotation[] array are sequence positions rather than alignment column positions.
438    * @param seqRef
439    * @param startRes
440    * @param alreadyMapped
441    */
442   public void createSequenceMapping(SequenceI seqRef,
443                                     int startRes,
444                                     boolean alreadyMapped)
445   {
446
447     if (seqRef == null)
448     {
449       return;
450     }
451
452     sequenceMapping = new java.util.Hashtable();
453
454     sequenceRef = seqRef;
455     int seqPos;
456
457     for (int i = 0; i < annotations.length; i++)
458     {
459       if (annotations[i] != null)
460       {
461         if (alreadyMapped)
462         {
463           seqPos = seqRef.findPosition(i);
464         }
465         else
466         {
467           seqPos = i + startRes;
468         }
469
470         sequenceMapping.put(new Integer(seqPos), annotations[i]);
471       }
472     }
473
474   }
475
476   public void adjustForAlignment()
477   {
478     if (sequenceRef==null)
479       return;
480
481     int a = 0, aSize = sequenceRef.getLength();
482
483     if (aSize == 0)
484     {
485       //Its been deleted
486       return;
487     }
488
489     int position;
490     Annotation[] temp = new Annotation[aSize];
491     Integer index;
492
493     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
494     {
495       index = new Integer(a);
496       if (sequenceMapping.containsKey(index))
497       {
498         position = sequenceRef.findIndex(a) - 1;
499
500         temp[position] = (Annotation) sequenceMapping.get(index);
501       }
502     }
503
504     annotations = temp;
505   }
506   /**
507    * remove any null entries in annotation row and return the
508    * number of non-null annotation elements.
509    * @return
510    */
511   private int compactAnnotationArray() {
512     int j=0;
513     for (int i=0;i<annotations.length; i++) {
514       if (annotations[i]!=null && j!=i) {
515         annotations[j++] = annotations[i];
516       }
517     }
518     Annotation[] ann = annotations;
519     annotations = new Annotation[j];
520     System.arraycopy(ann, 0, annotations, 0, j);
521     ann = null;
522     return j;
523   }
524
525   /**
526    * Associate this annotion with the aligned residues of a particular sequence.
527    * sequenceMapping will be updated in the following way:
528    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
529    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
530    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
531    * @param sequenceI
532    */
533   public void setSequenceRef(SequenceI sequenceI)
534   {
535     if (sequenceI != null)
536     {
537       if (sequenceRef != null)
538       {
539         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
540         {
541           // if sequenceRef isn't intersecting with sequenceI
542           // throw away old mapping and reconstruct.
543           sequenceRef = null;
544           if (sequenceMapping != null)
545           {
546             sequenceMapping = null;
547             // compactAnnotationArray();
548           }
549           createSequenceMapping(sequenceI, 1, true);
550           adjustForAlignment();
551         }
552         else
553         {
554           // Mapping carried over
555           sequenceRef = sequenceI;
556         }
557       }
558       else
559       {
560         // No mapping exists
561         createSequenceMapping(sequenceI, 1, true);
562         adjustForAlignment();
563       }
564     }
565     else
566     {
567       // throw away the mapping without compacting.
568       sequenceMapping = null;
569       sequenceRef = null;
570     }
571   }
572 }