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