Exercise 1.6: RNA secondary structure validator


RNA secondary structure validator

In this problem, we will write a function that takes an RNA sequence and an RNA secondary structure and decides if the secondary structure is possible given the sequence. Remember, single stranded RNA can fold back on itself and form base pairs. An RNA secondary structure is simply the list of base pairs that are present. We will represent the base pairs in dot-parentheses notation. For example, a sequence/secondary structure pair would be

0123456789
GCAUCUAUGC
(((....)))

For convenience of discussion, I have labeled the indices of the bases on the top row. In this case, base 0, a G, pairs with base 9, a C. Base 1 pairs with base 8, and base 2 pairs with base 7. Bases 3, 4, 5, and 6 are unpaired. (This structure is aptly called a “hairpin.”)

I hope the dot-parentheses notation is clear. An open parenthesis is paired with the parenthesis that closes it. Dots are unpaired.

So, the goal of our function is to check all base pairs present in a secondary structure and see if they are with G-C, A-U, or (optionally) G-U.

a) Write a function to make sure that the number of closed parentheses is equal to the number of open parentheses, a requirement for a valid secondary structure. It should return True if the parentheses are valid and False otherwise.

b) Write a function that converts the dot-parens notation to a tuple of 2-tuples representing the base pairs. We’ll call this function dotparen_to_bp(). An example input/output of this function would be:

dotparen_to_bp('(((....)))')

((0, 9), (1, 8), (2, 7))

Hint: You should look at methods that are available for lists. You might find the append() and pop() methods useful.

c) Because of sterics, the minimal length of a hairpin loop is three bases. A hairpin loop is a series of unpaired bases that are closed by a base pair. For example, the secondary structure (.(....).) has a single hairpin loop of length 4. So, the structure ((((..)))) is not valid because it has a hairpin loop of only two bases.

Write a function that verifies that a list of base pairs (as outputted by dotparen_to_bp()) satisfies the minimal hairpin length requirement.

d) Now write your validator function. The function definition should look like this:

def rna_ss_validator(seq, sec_struc, wobble=True):

It should return True if the sequence is commensurate with a valid secondary structure and False otherwise. The wobble keyword argument is True if we allow wobble pairs (G paired with U). Here are some expected results:

Returns True:

rna_ss_validator('GCAUCUAUGC', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(.(....).)')

Returns False:

rna_ss_validator('GCAUCUACGC', '(((....)))')
rna_ss_validator('GCAUCUAUGU', '(((....)))', wobble=False)
rna_ss_validator('GCAUCUAUGU', '(.(....)).')
rna_ss_validator('GCCCUUGGCA', '(.((..))).')

Solution


a) This part of the validation is simple. We just need to make sure the number of open and closed parentheses are equal.

[1]:
def parens_count(struc):
    """
    Ensures there are equal number of open and closed parentheses
    in structure.
    """
    return struc.count('(') == struc.count(')')

Let’s give it a try.

[2]:
print(parens_count('(((..(((...)).))))'))
print(parens_count('(((..(((...)).)))'))
True
False

b) As we scan a dot-parens structure from left to right, we can keep a list of the positions of open parentheses. Whenever we encounter a closed one, we have closed the last open one we added. So, we can just scan through the dot-parens string and pop out base pairs. If this procedure fails, we know that there was an error in the input structure (i.e., a closed parenthesis appeared without a corresponding open one before it).

[3]:
def dot_parens_to_bp(struc):
    """
    Convert a dot-parens structure to a list of base pairs.
    Return False if the structure is invalid.
    """
    if not parens_count(struc):
        print('Error in input structure.')
        return False

    # Initialize list of open parens and list of base pairs
    open_parens = []
    bps = []

    # Scan through string
    for i, x in enumerate(struc):
        if x == '(':
            open_parens.append(i)
        elif x == ')':
            if len(open_parens) > 0:
                bps.append((open_parens.pop(), i))
            else:
                print('Error in input structure.')
                return False

    # Return the result as a tuple
    return tuple(sorted(bps))

Let’s try it on some legitimate sequences and on some bad ones.

[4]:
# Good structure
dot_parens_to_bp('..(((...)))(((((....)))).)..')
[4]:
((2, 10), (3, 9), (4, 8), (11, 25), (12, 23), (13, 22), (14, 21), (15, 20))
[5]:
# Good structure
dot_parens_to_bp('(((..(((...)).))))')
[5]:
((0, 17), (1, 16), (2, 15), (5, 14), (6, 12), (7, 11))
[6]:
# Bad structure
dot_parens_to_bp('((....)))(')
Error in input structure.
[6]:
False
[7]:
dot_parens_to_bp('())....))))')
Error in input structure.
[7]:
False

c) It is quite easy to detect short hairpins once we have a list of base pairs. We just need to make sure the difference in index of any pair of paired bases is not less than three.

[8]:
def hairpin_check(bps):
    """Check to make sure no hairpins are too short."""
    for bp in bps:
        if bp[1] - bp[0] < 4:
            print('A hairpin is too short.')
            return False

    # Everything checks out
    return True

d) Most everything is in place. We just need to check the sequence.

[9]:
def rna_ss_validator(seq, sec_struc, wobble=True):
    """Validate and RNA structure"""
    # Convert structure to base pairs
    bps = dot_parens_to_bp(sec_struc)

    # If this failed, the structure was invalid
    if not bps:
        return False

    # Do the hairpin check
    if not hairpin_check(bps):
        return False

    # Possible base pairs
    if wobble:
        ok_bps = ('gc', 'cg', 'au', 'ua', 'gu', 'ug')
    else:
        ok_bps = ('gc', 'cg', 'au', 'ua')

    # Check complementarity
    for bp in bps:
        bp_str = (seq[bp[0]] + seq[bp[1]]).lower()
        if bp_str not in ok_bps:
            print('Invalid base pair.')
            return False

    # Everything passed
    return True

Let’s test it on the test cases from the problem statement.

[10]:
print('Should be True:')
print(rna_ss_validator('GCAUCUAUGC', '(((....)))'))
print(rna_ss_validator('GCAUCUAUGU', '(((....)))'))
print(rna_ss_validator('GCAUCUAUGU', '(.(....).)'))
print(rna_ss_validator('AUUGAUGCACGUGCAUCCCCAGCGGGUCCCGCGAGCUCACCCCCUUCCAAAAGCACCACGUGCCAGGCCUCGCCCCCGGAAGUAUACCUGUGAGCCAGA',
                       '...(((((....)))))....((((...))))..((((((...(((((....((((...))))..(((...)))...))))).......))))))....'))

print('\nShould be False:')
print(rna_ss_validator('GCAUCUACGC', '(((....)))'), '\n')
print(rna_ss_validator('GCAUCUAUGU', '(((....)))', wobble=False), '\n')
print(rna_ss_validator('GCAUCUAUGU', '(.(....)).'), '\n')
print(rna_ss_validator('GCCCUUGGCA', '(.((..))).'),'\n')
print(rna_ss_validator('AUUGAUGCACGUGCAUCCCCAGCGGGUCCCGCGAGCCCACCCCCUUCCAAAAGCACCACGUGCCAGGCCUCGCCCCCGGAAGUAUACCUGUGAGCCAGA',
                       '...(((((....)))))....((((...))))..((((((...(((((....((((...))))..(((...)))...))))).......))))))....'))
Should be True:
True
True
True
True

Should be False:
Invalid base pair.
False

Invalid base pair.
False

Invalid base pair.
False

A hairpin is too short.
False

Invalid base pair.
False

Looks good!

Computing environment

[11]:
%load_ext watermark
%watermark -v -p jupyterlab
Python implementation: CPython
Python version       : 3.11.3
IPython version      : 8.12.0

jupyterlab: 3.6.3