JAL-1516 handle null annotations
[jalview.git] / examples / groovy / annotationForSelectedSequence.groovy
1 // Requested by David M Garcia (v3)
2 // very messy script to output the scores in annotation rows
3 // for the first sequence in a selection on the topmost alignment
4
5 // thanks to this thread for cut'n'paste code
6 // http://comments.gmane.org/gmane.comp.lang.groovy.user/53010
7
8 // Jalview issue at http://issues.jalview.org/browse/JAL-1516
9
10 import java.awt.datatransfer.StringSelection
11 import static java.awt.Toolkit.*
12
13
14 def curviewport = Jalview.getAlignframes()[Jalview.getAlignframes().length-1].getViewport();
15
16 // TSV output by default.
17 // change "\t" to "," to output CSV file
18 def sep = "\t"; 
19
20 if (curviewport.getSelectionGroup()) {
21   // gets selection for topmost alignment
22   def selreg = curviewport.getSelectionGroup();
23   // get aligned positions of first sequence selected
24   def gaps = selreg.getSequenceAt(0).gapMap(); 
25   String csvfile="";
26   String sseq=""
27
28   curviewport.getAlignment().getAlignmentAnnotation().eachWithIndex{ aa, apos -> 
29     def count=1
30     String csv=""
31     gaps.eachWithIndex{col,spos -> if (col>=selreg.getStartRes() && col<=selreg.getEndRes()) { 
32       // add sequence for debugging
33       if (count>sseq.length()) { 
34           sseq+=sep+selreg.getSequenceAt(0).getCharAt(col); count=sseq.length()+1;
35       };
36       // output height of histogram
37       csv+=sep;
38       def annot = aa.annotations[col];
39       if (annot != null) {
40           csv+=aa.annotations[col].value; 
41       }
42       // Uncomment to output string shown in tooltip
43       // csv+=sep+aa.annotations[col].description; 
44     }}
45     if (csv.length()>0) {
46         csvfile+=aa.label+csv+"\n"
47     }
48   }
49   defaultToolkit.systemClipboard.setContents(new StringSelection(selreg.getSequenceAt(0).getName()+sseq+"\n"+csvfile), null)
50   print "Sequence"+sseq+"\n";
51   print csvfile;
52   print "\nAlignment Annotation for first selected sequence copied to the clipboard.\n"
53 } else {
54     "Select a region in the alignment window.";
55 }