JAL-1542 script to show aligned positions of selected column(s)
[jalview.git] / examples / groovy / sitesForSelectedColumns.groovy
1 // Requested by Hari Jayaram 
2 // script to output residue positions and values for selected region
3
4 // thanks to this thread for cut'n'paste code
5 // http://comments.gmane.org/gmane.comp.lang.groovy.user/53010
6
7 // Jalview issue at http://issues.jalview.org/browse/JAL-1542
8
9 import java.awt.datatransfer.StringSelection
10 import static java.awt.Toolkit.*
11
12 def curviewport = Jalview.getAlignframes()[Jalview.getAlignframes().length-1].getViewport()
13
14 def debug = false
15
16 // TSV output by default.
17 // change "\t" to "," to output CSV file
18 def sep = "\t"
19 def gapChar = "-"
20
21 if (curviewport.getSelectionGroup()) {
22   // gets selection for topmost alignment
23   def selreg = curviewport.getSelectionGroup()
24   def groupStartCol = selreg.getStartRes()
25   def groupEndCol = selreg.getEndRes()
26
27     if (debug) {println "groupStartCol: " + groupStartCol + ", groupEndCol: " + groupEndCol}
28       
29   def csv=new StringBuilder(512)
30
31   // for each sequence in the current selection
32   selreg.getSequences().eachWithIndex{ seq, seqNo ->
33     csv.append(seq.getDisplayId(false).padRight(20,' '))
34     // get map of sequence sites to alignment positions 
35     def gaps = seq.gapMap()
36     if (debug) {println "gaps: " + gaps}
37
38     // initialise loop variable to 'not quite shown first column'    
39     def lastColShown = groupStartCol-1
40     
41     for (mapPos=0 ; ; mapPos++) {
42         def nextResiduePos = gaps[mapPos]
43         // skip over sites that precede selected columns
44         if (nextResiduePos < groupStartCol) {
45             continue;
46         }
47
48         if (debug) {println "mapPos: " + mapPos + ", lastColShown: " + lastColShown + ", nextResiduePos: " + nextResiduePos + ", csv: " + csv}
49
50         // fill in any gaps
51         while (lastColShown < groupEndCol && lastColShown+1 < nextResiduePos) {
52             csv.append(sep+gapChar)
53             lastColShown++
54         }
55         if (lastColShown >= groupEndCol) {
56             break
57         }
58         lastColShown = nextResiduePos
59         def residue = seq.getDatasetSequence().getCharAt(mapPos)
60         csv.append(sep+(mapPos+1) + " (" + residue + ")")    // user output is base 1
61     }
62     csv.append("\n")      
63   }
64   def result = csv.toString()
65   defaultToolkit.systemClipboard.setContents(new StringSelection(result), null)
66   print result
67   println "Sites for selected region copied to the clipboard"
68 } else {
69     "Select a region in the alignment window."
70 }