'''
Copyleft Mar 26, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego,  Email: airanmehr@gmail.com
'''
import numpy as np;

np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;

pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import seaborn as sns
import pylab as plt;
import matplotlib as mpl
import os;
import Utils.Util as utl
import Utils.Plots as pplt
import Scripts.KyrgysHAPH.Util as kutl
import Scripts.KyrgysHAPH.Plot as kplt
from matplotlib.backends.backend_pdf import PdfPages
reload(utl)
path='/media/arya/d4565cf2-d44a-4b67-bf97-226a486c01681/Data/Human/Kyrgyz/scan/'
selscanPath='/media/arya/d4565cf2-d44a-4b67-bf97-226a486c01681/Data/Human/Kyrgyz/scan/selscan/'
def to_hg38(b):
    b=b.reset_index()
    b.CHROM=b.CHROM.apply(lambda x: 'chr{}'.format(x))
    chroms=map(lambda x: 'chr{}'.format(x),range(1,23))
    c=utl.BED.xmap_bed(b,19,38).dropna()
    c=pd.concat([c[38],c[19].score],1).loc[chroms].reset_index()
    c.CHROM=c.CHROM.apply(lambda x: int(x[3:]))
    c[['start','end']]=c[['start','end']].applymap(int)
    return utl.BED.getIntervals( c,50000).dropna()


def to_hg38_all():
    a=pd.read_pickle(selscanPath+'normalized.filtered.df').reset_index();a.CHROM=a.CHROM.apply(lambda x: 'chr{}'.format(x));a['start']=a.POS;a['end']=a.POS
    chroms=map(lambda x: 'chr{}'.format(x),range(1,23))

    c=utl.BED.xmap_bed(a[['CHROM','start','end']],19,38).dropna()
    c=c.groupby(level=0,axis=1).apply(lambda x: x[x.name].start).applymap(int).reset_index().rename(columns={19:'POS'});c.CHROM=c.CHROM.apply(lambda x: int(x[3:]));c=c.set_index(['CHROM','POS'])[38]
    aout=pd.read_pickle(selscanPath+'normalized.filtered.df').join(c)
    aout=aout[~aout[38].isnull()]
    aout[38]=aout[38].astype(int)
    aout=aout.reset_index().set_index(['CHROM',38])
    aout=aout[['ihs','nsl']]
    aout.index.names=['CHROM','POS']
    aout.to_pickle(selscanPath+'normalized.filtered.mapped.df')

def normalize():
    f=utl.normalizeIHS
    a=pd.concat([f(pd.read_pickle(selscanPath+'ihs.df')),f(pd.read_pickle(selscanPath+'nsl.df'))],1).apply(utl.pval.zpval);a.columns=['ihs','nsl']
    a.to_pickle(selscanPath+'normalized.df')
def saveIntervals():
    try:
        a=pd.read_pickle(selscanPath+'normalized.filtered.mapped.df')
    except:
        # pd.read_pickle(selscanPath+'normalized.df').apply(lambda x: utl.filterGap(x.dropna(),assempbly=19)).to_pickle(selscanPath+'normalized.filtered.df')
        a=pd.read_pickle(selscanPath+'normalized.filtered.mapped.df')