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