alignmentProperties added
[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     if (threshold!=null) {
310       threshold = new GraphLine(annotation.threshold);
311     }
312     if (annotation.annotations!=null) {
313       Annotation[] ann = annotation.annotations;
314       this.annotations = new Annotation[ann.length];
315       for (int i=0; i<ann.length; i++) {
316         annotations[i] = new Annotation(ann[i]);
317       };
318       if (annotation.sequenceRef!=null) {
319         this.sequenceRef = annotation.sequenceRef;
320         if (annotation.sequenceMapping!=null)
321         {
322           Integer p=null;
323           sequenceMapping = new Hashtable();
324           Enumeration pos=annotation.sequenceMapping.keys();
325           while (pos.hasMoreElements()) {
326             // could optimise this!
327             p = (Integer) pos.nextElement();
328             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
329             if (a==null)
330             {
331               continue;
332             }
333             for (int i=0; i<ann.length; i++)
334             {
335               if (ann[i]==a)
336               {
337                 sequenceMapping.put(p, annotations[i]);
338               }
339             }
340           }
341         } else {
342           this.sequenceMapping = null;
343         }
344       }
345     }
346     validateRangeAndDisplay(); // construct hashcodes, etc.
347   }
348
349   /**
350    * clip the annotation to the columns given by startRes and endRes (inclusive)
351    * and prune any existing sequenceMapping to just those columns.
352    * @param startRes
353    * @param endRes
354    */
355   public void restrict(int startRes, int endRes)
356   {
357     Annotation[] temp = new Annotation[endRes-startRes+1];
358     if (startRes<annotations.length)
359     {
360       System.arraycopy(annotations, startRes, temp, 0, Math.min(endRes, annotations.length-1)-startRes+1);
361     }
362     if (sequenceRef!=null) {
363       // Clip the mapping, if it exists.
364       int spos = sequenceRef.findPosition(startRes);
365       int epos = sequenceRef.findPosition(endRes);
366       if (sequenceMapping!=null)
367       {
368         Hashtable newmapping = new Hashtable();
369         Enumeration e = sequenceMapping.keys();
370         while (e.hasMoreElements())
371         {
372           Integer pos = (Integer) e.nextElement();
373           if (pos.intValue()>=spos && pos.intValue()<=epos)
374           {
375             newmapping.put(pos, sequenceMapping.get(pos));
376           }
377         }
378         sequenceMapping.clear();
379         sequenceMapping = newmapping;
380       }
381     }
382     annotations=temp;
383   }
384   /**
385    * set the annotation row to be at least length Annotations
386    * @param length minimum number of columns required in the annotation row
387    * @return false if the annotation row is greater than length
388    */
389   public boolean padAnnotation(int length) {
390     if (annotations==null)
391     {
392       annotations = new Annotation[length];
393       return true;
394     }
395     if (annotations.length<length)
396     {
397       Annotation[] na = new Annotation[length];
398       System.arraycopy(annotations, 0, na, 0, annotations.length);
399       annotations = na;
400       return true;
401     }
402     return annotations.length>length;
403
404   }
405
406   /**
407    * DOCUMENT ME!
408    *
409    * @return DOCUMENT ME!
410    */
411   public String toString()
412   {
413     StringBuffer buffer = new StringBuffer();
414
415     for (int i = 0; i < annotations.length; i++)
416     {
417       if (annotations[i] != null)
418       {
419         if (graph != 0)
420         {
421           buffer.append(annotations[i].value);
422         }
423         else if (hasIcons)
424         {
425           buffer.append(annotations[i].secondaryStructure);
426         }
427         else
428         {
429           buffer.append(annotations[i].displayCharacter);
430         }
431       }
432
433       buffer.append(", ");
434     }
435
436     if (label.equals("Consensus"))
437     {
438       buffer.append("\n");
439
440       for (int i = 0; i < annotations.length; i++)
441       {
442         if (annotations[i] != null)
443         {
444           buffer.append(annotations[i].description);
445         }
446
447         buffer.append(", ");
448       }
449     }
450
451     return buffer.toString();
452   }
453
454   public void setThreshold(GraphLine line)
455   {
456     threshold = line;
457   }
458
459   public GraphLine getThreshold()
460   {
461     return threshold;
462   }
463
464   /**
465    * 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.
466    * @param seqRef
467    * @param startRes
468    * @param alreadyMapped
469    */
470   public void createSequenceMapping(SequenceI seqRef,
471                                     int startRes,
472                                     boolean alreadyMapped)
473   {
474
475     if (seqRef == null)
476     {
477       return;
478     }
479     if (annotations==null)
480     {
481       return;
482     }
483     sequenceMapping = new java.util.Hashtable();
484
485     sequenceRef = seqRef;
486     int seqPos;
487
488     for (int i = 0; i < annotations.length; i++)
489     {
490       if (annotations[i] != null)
491       {
492         if (alreadyMapped)
493         {
494           seqPos = seqRef.findPosition(i);
495         }
496         else
497         {
498           seqPos = i + startRes;
499         }
500
501         sequenceMapping.put(new Integer(seqPos), annotations[i]);
502       }
503     }
504
505   }
506
507   public void adjustForAlignment()
508   {
509     if (sequenceRef==null)
510       return;
511
512     if (annotations==null)
513     {
514       return;
515     }
516
517     int a = 0, aSize = sequenceRef.getLength();
518
519     if (aSize == 0)
520     {
521       //Its been deleted
522       return;
523     }
524
525     int position;
526     Annotation[] temp = new Annotation[aSize];
527     Integer index;
528
529     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
530     {
531       index = new Integer(a);
532       if (sequenceMapping.containsKey(index))
533       {
534         position = sequenceRef.findIndex(a) - 1;
535
536         temp[position] = (Annotation) sequenceMapping.get(index);
537       }
538     }
539
540     annotations = temp;
541   }
542   /**
543    * remove any null entries in annotation row and return the
544    * number of non-null annotation elements.
545    * @return
546    */
547   private int compactAnnotationArray() {
548     int j=0;
549     for (int i=0;i<annotations.length; i++) {
550       if (annotations[i]!=null && j!=i) {
551         annotations[j++] = annotations[i];
552       }
553     }
554     Annotation[] ann = annotations;
555     annotations = new Annotation[j];
556     System.arraycopy(ann, 0, annotations, 0, j);
557     ann = null;
558     return j;
559   }
560
561   /**
562    * Associate this annotion with the aligned residues of a particular sequence.
563    * sequenceMapping will be updated in the following way:
564    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
565    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
566    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
567    * @param sequenceI
568    */
569   public void setSequenceRef(SequenceI sequenceI)
570   {
571     if (sequenceI != null)
572     {
573       if (sequenceRef != null)
574       {
575         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
576         {
577           // if sequenceRef isn't intersecting with sequenceI
578           // throw away old mapping and reconstruct.
579           sequenceRef = null;
580           if (sequenceMapping != null)
581           {
582             sequenceMapping = null;
583             // compactAnnotationArray();
584           }
585           createSequenceMapping(sequenceI, 1, true);
586           adjustForAlignment();
587         }
588         else
589         {
590           // Mapping carried over
591           sequenceRef = sequenceI;
592         }
593       }
594       else
595       {
596         // No mapping exists
597         createSequenceMapping(sequenceI, 1, true);
598         adjustForAlignment();
599       }
600     }
601     else
602     {
603       // throw away the mapping without compacting.
604       sequenceMapping = null;
605       sequenceRef = null;
606     }
607   }
608
609   /**
610    * @return the score
611    */
612   public float getScore()
613   {
614     return score;
615   }
616
617   /**
618    * @param score the score to set
619    */
620   public void setScore(float score)
621   {
622     this.score = score;
623   }
624   /**
625    *
626    * @return true if annotation has an associated score
627    */
628   public boolean hasScore()
629   {
630     return hasScore;
631   }
632 }