score and visible copy construction
[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   /**
58    * Score associated with label and description.
59    */
60   public float score= Float.NaN;
61   /**
62    * flag indicating if annotation has a score.
63    */
64   public boolean hasScore=false;
65
66   public GraphLine threshold;
67
68   // Graphical hints and tips
69
70   /** DOCUMENT ME!! */
71   public boolean editable = false;
72
73   /** DOCUMENT ME!! */
74   public boolean hasIcons; //
75
76   /** DOCUMENT ME!! */
77   public boolean hasText;
78
79   /** DOCUMENT ME!! */
80   public boolean visible = true;
81
82   public int graphGroup = -1;
83
84   /** DOCUMENT ME!! */
85   public int height = 0;
86
87   public int graph = 0;
88
89   public int graphHeight = 40;
90
91   public boolean padGaps = true;
92
93   public static final int NO_GRAPH = 0;
94
95   public static final int BAR_GRAPH = 1;
96
97   public static final int LINE_GRAPH = 2;
98
99   public boolean belowAlignment = true;
100
101
102   public static int getGraphValueFromString(String string)
103   {
104     if (string.equalsIgnoreCase("BAR_GRAPH"))
105     {
106       return BAR_GRAPH;
107     }
108     else if (string.equalsIgnoreCase("LINE_GRAPH"))
109     {
110       return LINE_GRAPH;
111     }
112     else
113     {
114       return NO_GRAPH;
115     }
116   }
117
118   /**
119    * Creates a new AlignmentAnnotation object.
120    *
121    * @param label DOCUMENT ME!
122    * @param description DOCUMENT ME!
123    * @param annotations DOCUMENT ME!about:blank
124 Loading...
125    */
126   public AlignmentAnnotation(String label, String description,
127                              Annotation[] annotations)
128   {
129     // always editable?
130     editable = true;
131     this.label = label;
132     this.description = description;
133     this.annotations = annotations;
134
135      validateRangeAndDisplay();
136   }
137
138   void areLabelsSecondaryStructure()
139   {
140     boolean nonSSLabel = false;
141     for (int i = 0; i < annotations.length; i++)
142     {
143       if (annotations[i] == null)
144       {
145         padGaps = false;
146         continue;
147       }
148       if (annotations[i].secondaryStructure == 'H' ||
149           annotations[i].secondaryStructure == 'E')
150       {
151           hasIcons = true;
152       }
153
154       if(annotations[i].displayCharacter==null)
155         continue;
156
157
158       if (annotations[i].displayCharacter.length() == 1
159           && !annotations[i].displayCharacter.equals("H")
160           && !annotations[i].displayCharacter.equals("E")
161           && !annotations[i].displayCharacter.equals("-")
162           && !annotations[i].displayCharacter.equals("."))
163         {
164           if (jalview.schemes.ResidueProperties.aaIndex
165                   [annotations[i].displayCharacter.charAt(0)] < 23)
166           {
167             nonSSLabel = true;
168           }
169         }
170
171         if (annotations[i].displayCharacter.length() > 0)
172         {
173           hasText = true;
174         }
175         else
176           padGaps = false;
177       }
178
179     if (nonSSLabel)
180     {
181       hasIcons = false;
182       for (int j = 0; j < annotations.length; j++)
183       {
184         if (annotations[j] != null && annotations[j].secondaryStructure != ' ')
185         {
186           annotations[j].displayCharacter
187               = String.valueOf(annotations[j].secondaryStructure);
188           annotations[j].secondaryStructure = ' ';
189         }
190
191       }
192     }
193
194     annotationId = this.hashCode() + "";
195   }
196   /**
197    * Creates a new AlignmentAnnotation object.
198    *
199    * @param label DOCUMENT ME!
200    * @param description DOCUMENT ME!
201    * @param annotations DOCUMENT ME!
202    * @param min DOCUMENT ME!
203    * @param max DOCUMENT ME!
204    * @param winLength DOCUMENT ME!
205    */
206   public AlignmentAnnotation(String label, String description,
207                              Annotation[] annotations, float min, float max,
208                              int graphType)
209   {
210     // graphs are not editable
211     editable = graphType==0;
212
213     this.label = label;
214     this.description = description;
215     this.annotations = annotations;
216     graph = graphType;
217     graphMin = min;
218     graphMax = max;
219     validateRangeAndDisplay();
220   }
221   /**
222    * checks graphMin and graphMax,
223    * secondary structure symbols,
224    * sets graphType appropriately,
225    * sets null labels to the empty string
226    * if appropriate.
227    */
228   private void validateRangeAndDisplay() {
229
230     if (annotations==null)
231     {
232       visible=false; // try to prevent renderer from displaying.
233       return; // this is a non-annotation row annotation - ie a sequence score.
234     }
235
236     int graphType = graph;
237     float min = graphMin;
238     float max = graphMax;
239     boolean drawValues = true;
240
241     if (min == max)
242     {
243       min = 999999999;
244       for (int i = 0; i < annotations.length; i++)
245       {
246         if (annotations[i] == null)
247         {
248           continue;
249         }
250
251         if (drawValues
252             && annotations[i].displayCharacter!=null
253             && annotations[i].displayCharacter.length() > 1)
254         {
255           drawValues = false;
256         }
257
258         if (annotations[i].value > max)
259         {
260           max = annotations[i].value;
261         }
262
263         if (annotations[i].value < min)
264         {
265           min = annotations[i].value;
266         }
267       }
268     }
269
270     graphMin = min;
271     graphMax = max;
272
273     areLabelsSecondaryStructure();
274
275     if (!drawValues && graphType != NO_GRAPH)
276     {
277       for (int i = 0; i < annotations.length; i++)
278       {
279         if (annotations[i] != null)
280         {
281           annotations[i].displayCharacter = "";
282         }
283       }
284     }
285   }
286
287   /**
288    * Copy constructor
289    * creates a new independent annotation row with the same associated sequenceRef
290    * @param annotation
291    */
292   public AlignmentAnnotation(AlignmentAnnotation annotation)
293   {
294     this.label = new String(annotation.label);
295     if (annotation.description != null)
296       this.description = new String(annotation.description);
297     this.graphMin = annotation.graphMin;
298     this.graphMax = annotation.graphMax;
299     this.graph = annotation.graph;
300     this.graphHeight = annotation.graphHeight;
301     this.graphGroup = annotation.graphGroup;
302     this.editable = annotation.editable;
303     this.autoCalculated = annotation.autoCalculated;
304     this.hasIcons = annotation.hasIcons;
305     this.hasText = annotation.hasText;
306     this.height = annotation.height;
307     this.label = annotation.label;
308     this.padGaps = annotation.padGaps;
309     this.visible = annotation.visible;
310     if (this.hasScore = annotation.hasScore)
311     {
312       this.score = annotation.score;
313     }
314     if (threshold!=null) {
315       threshold = new GraphLine(annotation.threshold);
316     }
317     if (annotation.annotations!=null) {
318       Annotation[] ann = annotation.annotations;
319       this.annotations = new Annotation[ann.length];
320       for (int i=0; i<ann.length; i++) {
321         annotations[i] = new Annotation(ann[i]);
322       };
323       if (annotation.sequenceRef!=null) {
324         this.sequenceRef = annotation.sequenceRef;
325         if (annotation.sequenceMapping!=null)
326         {
327           Integer p=null;
328           sequenceMapping = new Hashtable();
329           Enumeration pos=annotation.sequenceMapping.keys();
330           while (pos.hasMoreElements()) {
331             // could optimise this!
332             p = (Integer) pos.nextElement();
333             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
334             if (a==null)
335             {
336               continue;
337             }
338             for (int i=0; i<ann.length; i++)
339             {
340               if (ann[i]==a)
341               {
342                 sequenceMapping.put(p, annotations[i]);
343               }
344             }
345           }
346         } else {
347           this.sequenceMapping = null;
348         }
349       }
350     }
351     validateRangeAndDisplay(); // construct hashcodes, etc.
352   }
353
354   /**
355    * clip the annotation to the columns given by startRes and endRes (inclusive)
356    * and prune any existing sequenceMapping to just those columns.
357    * @param startRes
358    * @param endRes
359    */
360   public void restrict(int startRes, int endRes)
361   {
362     if (annotations==null)
363       return;
364     Annotation[] temp = new Annotation[endRes-startRes+1];
365     if (startRes<annotations.length)
366     {
367       System.arraycopy(annotations, startRes, temp, 0, Math.min(endRes, annotations.length-1)-startRes+1);
368     }
369     if (sequenceRef!=null) {
370       // Clip the mapping, if it exists.
371       int spos = sequenceRef.findPosition(startRes);
372       int epos = sequenceRef.findPosition(endRes);
373       if (sequenceMapping!=null)
374       {
375         Hashtable newmapping = new Hashtable();
376         Enumeration e = sequenceMapping.keys();
377         while (e.hasMoreElements())
378         {
379           Integer pos = (Integer) e.nextElement();
380           if (pos.intValue()>=spos && pos.intValue()<=epos)
381           {
382             newmapping.put(pos, sequenceMapping.get(pos));
383           }
384         }
385         sequenceMapping.clear();
386         sequenceMapping = newmapping;
387       }
388     }
389     annotations=temp;
390   }
391   /**
392    * set the annotation row to be at least length Annotations
393    * @param length minimum number of columns required in the annotation row
394    * @return false if the annotation row is greater than length
395    */
396   public boolean padAnnotation(int length) {
397     if (annotations==null)
398     {
399       annotations = new Annotation[length];
400       return true;
401     }
402     if (annotations.length<length)
403     {
404       Annotation[] na = new Annotation[length];
405       System.arraycopy(annotations, 0, na, 0, annotations.length);
406       annotations = na;
407       return true;
408     }
409     return annotations.length>length;
410
411   }
412
413   /**
414    * DOCUMENT ME!
415    *
416    * @return DOCUMENT ME!
417    */
418   public String toString()
419   {
420     StringBuffer buffer = new StringBuffer();
421
422     for (int i = 0; i < annotations.length; i++)
423     {
424       if (annotations[i] != null)
425       {
426         if (graph != 0)
427         {
428           buffer.append(annotations[i].value);
429         }
430         else if (hasIcons)
431         {
432           buffer.append(annotations[i].secondaryStructure);
433         }
434         else
435         {
436           buffer.append(annotations[i].displayCharacter);
437         }
438       }
439
440       buffer.append(", ");
441     }
442
443     if (label.equals("Consensus"))
444     {
445       buffer.append("\n");
446
447       for (int i = 0; i < annotations.length; i++)
448       {
449         if (annotations[i] != null)
450         {
451           buffer.append(annotations[i].description);
452         }
453
454         buffer.append(", ");
455       }
456     }
457
458     return buffer.toString();
459   }
460
461   public void setThreshold(GraphLine line)
462   {
463     threshold = line;
464   }
465
466   public GraphLine getThreshold()
467   {
468     return threshold;
469   }
470
471   /**
472    * 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.
473    * @param seqRef
474    * @param startRes
475    * @param alreadyMapped
476    */
477   public void createSequenceMapping(SequenceI seqRef,
478                                     int startRes,
479                                     boolean alreadyMapped)
480   {
481
482     if (seqRef == null)
483     {
484       return;
485     }
486     if (annotations==null)
487     {
488       return;
489     }
490     sequenceMapping = new java.util.Hashtable();
491
492     sequenceRef = seqRef;
493     int seqPos;
494
495     for (int i = 0; i < annotations.length; i++)
496     {
497       if (annotations[i] != null)
498       {
499         if (alreadyMapped)
500         {
501           seqPos = seqRef.findPosition(i);
502         }
503         else
504         {
505           seqPos = i + startRes;
506         }
507
508         sequenceMapping.put(new Integer(seqPos), annotations[i]);
509       }
510     }
511
512   }
513
514   public void adjustForAlignment()
515   {
516     if (sequenceRef==null)
517       return;
518
519     if (annotations==null)
520     {
521       return;
522     }
523
524     int a = 0, aSize = sequenceRef.getLength();
525
526     if (aSize == 0)
527     {
528       //Its been deleted
529       return;
530     }
531
532     int position;
533     Annotation[] temp = new Annotation[aSize];
534     Integer index;
535
536     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
537     {
538       index = new Integer(a);
539       if (sequenceMapping.containsKey(index))
540       {
541         position = sequenceRef.findIndex(a) - 1;
542
543         temp[position] = (Annotation) sequenceMapping.get(index);
544       }
545     }
546
547     annotations = temp;
548   }
549   /**
550    * remove any null entries in annotation row and return the
551    * number of non-null annotation elements.
552    * @return
553    */
554   private int compactAnnotationArray() {
555     int j=0;
556     for (int i=0;i<annotations.length; i++) {
557       if (annotations[i]!=null && j!=i) {
558         annotations[j++] = annotations[i];
559       }
560     }
561     Annotation[] ann = annotations;
562     annotations = new Annotation[j];
563     System.arraycopy(ann, 0, annotations, 0, j);
564     ann = null;
565     return j;
566   }
567
568   /**
569    * Associate this annotion with the aligned residues of a particular sequence.
570    * sequenceMapping will be updated in the following way:
571    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
572    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
573    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
574    * @param sequenceI
575    */
576   public void setSequenceRef(SequenceI sequenceI)
577   {
578     if (sequenceI != null)
579     {
580       if (sequenceRef != null)
581       {
582         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
583         {
584           // if sequenceRef isn't intersecting with sequenceI
585           // throw away old mapping and reconstruct.
586           sequenceRef = null;
587           if (sequenceMapping != null)
588           {
589             sequenceMapping = null;
590             // compactAnnotationArray();
591           }
592           createSequenceMapping(sequenceI, 1, true);
593           adjustForAlignment();
594         }
595         else
596         {
597           // Mapping carried over
598           sequenceRef = sequenceI;
599         }
600       }
601       else
602       {
603         // No mapping exists
604         createSequenceMapping(sequenceI, 1, true);
605         adjustForAlignment();
606       }
607     }
608     else
609     {
610       // throw away the mapping without compacting.
611       sequenceMapping = null;
612       sequenceRef = null;
613     }
614   }
615
616   /**
617    * @return the score
618    */
619   public float getScore()
620   {
621     return score;
622   }
623
624   /**
625    * @param score the score to set
626    */
627   public void setScore(float score)
628   {
629     this.score = score;
630   }
631   /**
632    *
633    * @return true if annotation has an associated score
634    */
635   public boolean hasScore()
636   {
637     return hasScore;
638   }
639 }