JAL-1517 update copyright to version 2.8.2
[jalview.git] / src / jalview / analysis / Rna.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 /* Author: Lauren Michelle Lui 
20  * Methods are based on RALEE methods http://personalpages.manchester.ac.uk/staff/sam.griffiths-jones/software/ralee/
21  * Additional Author: Jan Engelhart (2011) - Structure consensus and bug fixing
22  * Additional Author: Anne Menard (2012) - Pseudoknot support and secondary structure consensus
23  * */
24
25 package jalview.analysis;
26
27
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.HashSet;
31 import java.util.Hashtable;
32 import java.util.Stack;
33 import java.util.Vector;
34
35
36 import jalview.analysis.SecStrConsensus.SimpleBP;
37 import jalview.datamodel.SequenceFeature;
38
39 public class Rna
40 {
41         
42         static Hashtable<Integer, Integer> pairHash = new Hashtable();
43         
44   private static final Character[] openingPars = {'(','[','{','<','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; 
45   private static final Character[] closingPars = {')',']','}','>','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; 
46   
47   private static HashSet<Character> openingParsSet = new HashSet<Character>(Arrays.asList(openingPars)); 
48   private static HashSet<Character> closingParsSet = new HashSet<Character>(Arrays.asList(closingPars));
49   private static Hashtable<Character,Character> closingToOpening = new Hashtable<Character,Character>()
50   // Initializing final data structure
51   {
52         private static final long serialVersionUID = 1L;
53         {
54           for(int i=0;i<openingPars.length;i++)
55           {
56                   System.out.println(closingPars[i]+"->"+openingPars[i]);
57                   put(closingPars[i],openingPars[i]);             
58           }
59   }};
60         
61   private static boolean isOpeningParenthesis(char c)
62   {
63           return openingParsSet.contains(c);
64   }
65         
66   private static boolean isClosingParenthesis(char c)
67   {
68           return closingParsSet.contains(c);
69   }
70
71   private static char matchingOpeningParenthesis(char closingParenthesis) throws WUSSParseException
72   {
73           if (!isClosingParenthesis(closingParenthesis))
74           {
75                   throw new WUSSParseException("Querying matching opening parenthesis for non-closing parenthesis character "+closingParenthesis, -1);
76           }
77         
78           return closingToOpening.get(closingParenthesis);
79   }
80   
81   /**
82    * Based off of RALEE code ralee-get-base-pairs. Keeps track of open bracket
83    * positions in "stack" vector. When a close bracket is reached, pair this
84    * with the last element in the "stack" vector and store in "pairs" vector.
85    * Remove last element in the "stack" vector. Continue in this manner until
86    * the whole string is processed.
87    * 
88    * @param line
89    *          Secondary structure line of an RNA Stockholm file
90    * @return Array of SequenceFeature; type = RNA helix, begin is open base
91    *         pair, end is close base pair
92    */
93   public static Vector<SimpleBP> GetSimpleBPs(CharSequence line) throws WUSSParseException
94   {
95     System.out.println(line);
96         Hashtable<Character,Stack<Integer>> stacks = new Hashtable<Character,Stack<Integer>>();
97     Vector<SimpleBP> pairs = new Vector<SimpleBP>();
98     int i = 0;
99     while (i < line.length())
100     {
101       char base = line.charAt(i);
102      
103       if (isOpeningParenthesis(base))
104       {
105           if (!stacks.containsKey(base)){
106                   stacks.put(base, new Stack<Integer>());
107           }
108         stacks.get(base).push(i);
109        
110       }
111       else if (isClosingParenthesis(base))
112       {
113         
114           char opening = matchingOpeningParenthesis(base);
115           
116           if (!stacks.containsKey(opening)){
117                   throw new WUSSParseException("Mismatched (unseen) closing character "+base, i);
118           }
119           
120          Stack<Integer> stack = stacks.get(opening);
121         if (stack.isEmpty())
122         {
123           // error whilst parsing i'th position. pass back
124                   throw new WUSSParseException("Mismatched closing character "+base, i);
125         }
126         int temp = stack.pop();
127         
128         pairs.add(new SimpleBP(temp,i));
129       }
130       i++;
131     }
132     for(char opening: stacks.keySet())
133     {
134         Stack<Integer> stack = stacks.get(opening);
135         if (!stack.empty())
136         {
137                   throw new WUSSParseException("Mismatched opening character "+opening+" at "+stack.pop(), i);                  
138         }
139     }
140     return pairs;
141   }
142   
143   public static SequenceFeature[] GetBasePairs(CharSequence line) throws WUSSParseException
144   {
145           Vector<SimpleBP> bps = GetSimpleBPs(line);
146           SequenceFeature[] outPairs = new SequenceFeature[bps.size()];
147     for (int p = 0; p < bps.size(); p++)
148     {
149         SimpleBP bp = bps.elementAt(p);
150         outPairs[p] = new SequenceFeature("RNA helix", "", "", bp.getBP5(),bp.getBP3(), "");
151     }
152     return outPairs;
153   }
154   
155   
156   public static  ArrayList<SimpleBP> GetModeleBP(CharSequence line) throws WUSSParseException
157   {
158           Vector<SimpleBP> bps = GetSimpleBPs(line);
159           return new ArrayList<SimpleBP>(bps);
160   }
161   
162   
163   /**
164    * Function to get the end position corresponding to a given start position
165    * @param indice - start position of a base pair
166    * @return - end position of a base pair
167    */
168   /*makes no sense at the moment :(
169   public int findEnd(int indice){
170           //TODO: Probably extend this to find the start to a given end?
171           //could be done by putting everything twice to the hash
172           ArrayList<Integer> pair = new ArrayList<Integer>();
173           return pairHash.get(indice);
174   }*/
175   
176
177   /**
178    * Figures out which helix each position belongs to and stores the helix
179    * number in the 'featureGroup' member of a SequenceFeature Based off of RALEE
180    * code ralee-helix-map.
181    * 
182    * @param pairs
183    *          Array of SequenceFeature (output from Rna.GetBasePairs)
184    */
185   public static void HelixMap(SequenceFeature[] pairs)
186   {
187
188     int helix = 0; // Number of helices/current helix
189     int lastopen = 0; // Position of last open bracket reviewed
190     int lastclose = 9999999; // Position of last close bracket reviewed
191     int i = pairs.length; // Number of pairs
192
193     int open; // Position of an open bracket under review
194     int close; // Position of a close bracket under review
195     int j; // Counter
196
197     Hashtable helices = new Hashtable(); // Keep track of helix number for each
198                                          // position
199
200     // Go through each base pair and assign positions a helix
201     for (i = 0; i < pairs.length; i++)
202     {
203
204       open = pairs[i].getBegin();
205       close = pairs[i].getEnd();
206
207       // System.out.println("open " + open + " close " + close);
208       // System.out.println("lastclose " + lastclose + " lastopen " + lastopen);
209
210       // we're moving from right to left based on closing pair
211       /*
212        * catch things like <<..>>..<<..>> |
213        */
214       if (open > lastclose)
215       {
216         helix++;
217       }
218
219       /*
220        * catch things like <<..<<..>>..<<..>>>> |
221        */
222       j = pairs.length - 1;
223       while (j >= 0)
224       {
225         int popen = pairs[j].getBegin();
226
227         // System.out.println("j " + j + " popen " + popen + " lastopen "
228         // +lastopen + " open " + open);
229         if ((popen < lastopen) && (popen > open))
230         {
231           if (helices.containsValue(popen)
232                   && (((Integer) helices.get(popen)) == helix))
233           {
234             continue;
235           }
236           else
237           {
238             helix++;
239             break;
240           }
241         }
242
243         j -= 1;
244       }
245
246       // Put positions and helix information into the hashtable
247       helices.put(open, helix);
248       helices.put(close, helix);
249
250       // Record helix as featuregroup
251       pairs[i].setFeatureGroup(Integer.toString(helix));
252
253       lastopen = open;
254       lastclose = close;
255
256     }
257   }
258 }
259