JAL-1355
[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 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashSet;
32 import java.util.Hashtable;
33 import java.util.Stack;
34 import java.util.Vector;
35
36 import jalview.analysis.SecStrConsensus.SimpleBP;
37 import jalview.datamodel.SequenceFeature;
38 import jalview.util.MessageManager;
39
40 public class Rna
41 {
42
43   static Hashtable<Integer, Integer> pairHash = new Hashtable();
44
45   private static final Character[] openingPars =
46   { '(', '[', '{', '<', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
47       'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
48       'Y', 'Z' };
49
50   private static final Character[] closingPars =
51   { ')', ']', '}', '>', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
52       'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
53       'y', 'z' };
54
55   private static HashSet<Character> openingParsSet = new HashSet<Character>(
56           Arrays.asList(openingPars));
57
58   private static HashSet<Character> closingParsSet = new HashSet<Character>(
59           Arrays.asList(closingPars));
60
61   private static Hashtable<Character, Character> closingToOpening = new Hashtable<Character, Character>()
62   // Initializing final data structure
63   {
64     private static final long serialVersionUID = 1L;
65     {
66       for (int i = 0; i < openingPars.length; i++)
67       {
68         System.out.println(closingPars[i] + "->" + openingPars[i]);
69         put(closingPars[i], openingPars[i]);
70       }
71     }
72   };
73
74   private static boolean isOpeningParenthesis(char c)
75   {
76     return openingParsSet.contains(c);
77   }
78
79   private static boolean isClosingParenthesis(char c)
80   {
81     return closingParsSet.contains(c);
82   }
83
84   private static char matchingOpeningParenthesis(char closingParenthesis)
85           throws WUSSParseException
86   {
87     if (!isClosingParenthesis(closingParenthesis))
88     {
89       throw new WUSSParseException(MessageManager.formatMessage("exception.querying_matching_opening_parenthesis_for_non_closing_parenthesis", new String[]{new StringBuffer(closingParenthesis).toString()}), -1);
90     }
91
92     return closingToOpening.get(closingParenthesis);
93   }
94
95   /**
96    * Based off of RALEE code ralee-get-base-pairs. Keeps track of open bracket
97    * positions in "stack" vector. When a close bracket is reached, pair this
98    * with the last element in the "stack" vector and store in "pairs" vector.
99    * Remove last element in the "stack" vector. Continue in this manner until
100    * the whole string is processed.
101    * 
102    * @param line
103    *          Secondary structure line of an RNA Stockholm file
104    * @return Array of SequenceFeature; type = RNA helix, begin is open base
105    *         pair, end is close base pair
106    */
107   public static Vector<SimpleBP> GetSimpleBPs(CharSequence line)
108           throws WUSSParseException
109   {
110     System.out.println(line);
111     Hashtable<Character, Stack<Integer>> stacks = new Hashtable<Character, Stack<Integer>>();
112     Vector<SimpleBP> pairs = new Vector<SimpleBP>();
113     int i = 0;
114     while (i < line.length())
115     {
116       char base = line.charAt(i);
117
118       if (isOpeningParenthesis(base))
119       {
120         if (!stacks.containsKey(base))
121         {
122           stacks.put(base, new Stack<Integer>());
123         }
124         stacks.get(base).push(i);
125
126       }
127       else if (isClosingParenthesis(base))
128       {
129
130         char opening = matchingOpeningParenthesis(base);
131
132         if (!stacks.containsKey(opening))
133         {
134           throw new WUSSParseException(MessageManager.formatMessage("exception.mismatched_unseen_closing_char", new String[]{new StringBuffer(base).toString()}), i);
135         }
136
137         Stack<Integer> stack = stacks.get(opening);
138         if (stack.isEmpty())
139         {
140           // error whilst parsing i'th position. pass back
141           throw new WUSSParseException(MessageManager.formatMessage("exception.mismatched_closing_char", new String[]{new StringBuffer(base).toString()}), i);
142         }
143         int temp = stack.pop();
144
145         pairs.add(new SimpleBP(temp, i));
146       }
147       i++;
148     }
149     for (char opening : stacks.keySet())
150     {
151       Stack<Integer> stack = stacks.get(opening);
152       if (!stack.empty())
153       {
154         throw new WUSSParseException(MessageManager.formatMessage("exception.mismatched_opening_char", new String[]{new StringBuffer(opening).toString(),Integer.valueOf(stack.pop()).toString()}), i);
155       }
156     }
157     return pairs;
158   }
159
160   public static SequenceFeature[] GetBasePairs(CharSequence line)
161           throws WUSSParseException
162   {
163     Vector<SimpleBP> bps = GetSimpleBPs(line);
164     SequenceFeature[] outPairs = new SequenceFeature[bps.size()];
165     for (int p = 0; p < bps.size(); p++)
166     {
167       SimpleBP bp = bps.elementAt(p);
168       outPairs[p] = new SequenceFeature("RNA helix", "", "", bp.getBP5(),
169               bp.getBP3(), "");
170     }
171     return outPairs;
172   }
173
174   public static ArrayList<SimpleBP> GetModeleBP(CharSequence line)
175           throws WUSSParseException
176   {
177     Vector<SimpleBP> bps = GetSimpleBPs(line);
178     return new ArrayList<SimpleBP>(bps);
179   }
180
181   /**
182    * Function to get the end position corresponding to a given start position
183    * 
184    * @param indice
185    *          - start position of a base pair
186    * @return - end position of a base pair
187    */
188   /*
189    * makes no sense at the moment :( public int findEnd(int indice){ //TODO:
190    * Probably extend this to find the start to a given end? //could be done by
191    * putting everything twice to the hash ArrayList<Integer> pair = new
192    * ArrayList<Integer>(); return pairHash.get(indice); }
193    */
194
195   /**
196    * Figures out which helix each position belongs to and stores the helix
197    * number in the 'featureGroup' member of a SequenceFeature Based off of RALEE
198    * code ralee-helix-map.
199    * 
200    * @param pairs
201    *          Array of SequenceFeature (output from Rna.GetBasePairs)
202    */
203   public static void HelixMap(SequenceFeature[] pairs)
204   {
205
206     int helix = 0; // Number of helices/current helix
207     int lastopen = 0; // Position of last open bracket reviewed
208     int lastclose = 9999999; // Position of last close bracket reviewed
209     int i = pairs.length; // Number of pairs
210
211     int open; // Position of an open bracket under review
212     int close; // Position of a close bracket under review
213     int j; // Counter
214
215     Hashtable helices = new Hashtable(); // Keep track of helix number for each
216                                          // position
217
218     // Go through each base pair and assign positions a helix
219     for (i = 0; i < pairs.length; i++)
220     {
221
222       open = pairs[i].getBegin();
223       close = pairs[i].getEnd();
224
225       // System.out.println("open " + open + " close " + close);
226       // System.out.println("lastclose " + lastclose + " lastopen " + lastopen);
227
228       // we're moving from right to left based on closing pair
229       /*
230        * catch things like <<..>>..<<..>> |
231        */
232       if (open > lastclose)
233       {
234         helix++;
235       }
236
237       /*
238        * catch things like <<..<<..>>..<<..>>>> |
239        */
240       j = pairs.length - 1;
241       while (j >= 0)
242       {
243         int popen = pairs[j].getBegin();
244
245         // System.out.println("j " + j + " popen " + popen + " lastopen "
246         // +lastopen + " open " + open);
247         if ((popen < lastopen) && (popen > open))
248         {
249           if (helices.containsValue(popen)
250                   && (((Integer) helices.get(popen)) == helix))
251           {
252             continue;
253           }
254           else
255           {
256             helix++;
257             break;
258           }
259         }
260
261         j -= 1;
262       }
263
264       // Put positions and helix information into the hashtable
265       helices.put(open, helix);
266       helices.put(close, helix);
267
268       // Record helix as featuregroup
269       pairs[i].setFeatureGroup(Integer.toString(helix));
270
271       lastopen = open;
272       lastclose = close;
273
274     }
275   }
276 }