#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
utilities
@author: boyangzhao
"""

import pandas as pd
import re

def int2ordinal(n):
    # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement
    if (type(n) is int) or n.isdigit():
        if type(n) is not int:
            n = int(n)
        return "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n if n<20 else n%10,"th"))
    else:
        return n
    
def getFeatGene(x, firstOnly = False):
    # get gene
    if pd.isnull(x):
        return ''
    
    r = re.findall('([^,\()]*)\s(\(([^,]*)\)\s)*\[([^,]*)\]',x)
    
    if firstOnly:
        return r[0][0]
    else:
        return [n[0] for n in r]

def getFeatSource(x, firstOnly = False):
    # get the data source
    if(pd.isnull(x)):
        return ''
    r = re.findall('[^,\()]*\s(\([^,]*\)\s)*\[([^,]*)\]',x)
    
    if firstOnly:
        return [n[1] for n in r][0]
    else:
        return [n[1] for n in r]

def pd_filter(df, idx):
    # filters a pandas data frame, given idx
    # this is a safe filter such that if one of the idx is not found, they are ignored
    if idx is None:
        return df
    if type(idx) is not list:
        idx = [idx]
    idx = [n for n in idx if n in df.index]

    return df.loc[idx, :]

[((22, 7, 22, 19), 'pandas.isnull', 'pd.isnull', ({(22, 17, 22, 18): 'x'}, {}), '(x)', True, 'import pandas as pd\n'), ((25, 8, 25, 63), 're.findall', 're.findall', ({(25, 19, 25, 60): '"""([^,\\\\()]*)\\\\s(\\\\(([^,]*)\\\\)\\\\s)*\\\\[([^,]*)\\\\]"""', (25, 61, 25, 62): 'x'}, {}), "('([^,\\\\()]*)\\\\s(\\\\(([^,]*)\\\\)\\\\s)*\\\\[([^,]*)\\\\]', x)", False, 'import re\n'), ((34, 7, 34, 19), 'pandas.isnull', 'pd.isnull', ({(34, 17, 34, 18): 'x'}, {}), '(x)', True, 'import pandas as pd\n'), ((36, 8, 36, 59), 're.findall', 're.findall', ({(36, 19, 36, 56): '"""[^,\\\\()]*\\\\s(\\\\([^,]*\\\\)\\\\s)*\\\\[([^,]*)\\\\]"""', (36, 57, 36, 58): 'x'}, {}), "('[^,\\\\()]*\\\\s(\\\\([^,]*\\\\)\\\\s)*\\\\[([^,]*)\\\\]', x)", False, 'import re\n')]