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