Transcript Profile Report

This report details all of the profiles that have been collected and collapsed accross the transcript profile.



In [ ]:


In [5]:
from IPython.display import display, Markdown
from IPython.display import HTML
import IPython.core.display as di
import csv
import numpy as np
import zlib
import CGAT.IOTools as IOTools
import itertools as ITL
import os
import string
import pandas as pd
import sqlite3
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPages  # noqa: E402
#mpl.use('Agg')  # noqa: E402
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.font_manager as font_manager
import matplotlib.lines as mlines
from matplotlib.colors import ListedColormap
from matplotlib import cm
from matplotlib import rc, font_manager
import CGAT.Experiment as E
import math
from random import shuffle
import matplotlib as mpl
import datetime
import seaborn as sns
import nbformat
%matplotlib inline  


##################################################
#Plot customization
#plt.ioff()
plt.style.use('seaborn-white')
#plt.style.use('ggplot')
title_font = {'size':'20','color':'black', 'weight':'bold', 'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'size':'18', 'weight':'bold'}
#For summary page pdf
'''To add description page
plt.figure() 
plt.axis('off')
plt.text(0.5,0.5,"my title",ha='center',va='center')
pdf.savefig()
'''
#Panda data frame cutomization
pd.options.display.width = 80
pd.set_option('display.max_colwidth', -1)

def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

def y_fmt(y, pos):
    decades = [1e9, 1e6, 1e3, 1e0, 1e-3, 1e-6, 1e-9 ]
    suffix  = ["G", "M", "k", "" , "m" , "u", "n"  ]
    if y == 0:
        return str(0)
    for i, d in enumerate(decades):
        if np.abs(y) >=d:
            val = y/float(d)
            signf = len(str(val).split(".")[1])
            if signf == 0:
                return '{val:d} {suffix}'.format(val=int(val), suffix=suffix[i])
            else:
                if signf == 1:
                    #print(val, signf)
                    if str(val).split(".")[1] == "0":
                       return '{val:d} {suffix}'.format(val=int(round(val)), suffix=suffix[i]) 
                tx = "{"+"val:.{signf}f".format(signf = signf) +"} {suffix}"
                return tx.format(val=val, suffix=suffix[i])

                #return y
    return y

def getTables(dbname):
    '''
    Retrieves the names of all tables in the database.
    Groups tables into dictionaries by annotation
    '''
    dbh = sqlite3.connect(dbname)
    c = dbh.cursor()
    statement = "SELECT name FROM sqlite_master WHERE type='table'"
    c.execute(statement)
    tables = c.fetchall()
    print(tables)
    c.close()
    dbh.close()
    return 

def readDBTable(dbname, tablename):
    '''
    Reads the specified table from the specified database.
    Returns a list of tuples representing each row
    '''
    dbh = sqlite3.connect(dbname)
    c = dbh.cursor()
    statement = "SELECT * FROM %s" % tablename
    c.execute(statement)
    allresults = c.fetchall()
    c.close()
    dbh.close()
    return allresults

def getDBColumnNames(dbname, tablename):
    dbh = sqlite3.connect(dbname)
    res = pd.read_sql('SELECT * FROM %s' % tablename, dbh)
    dbh.close()
    return res.columns

        
def transcriptProfileReport(dbname, tablename):
    trans = pd.DataFrame(readDBTable(dbname,tablename))
    trans.columns = getDBColumnNames(dbname,tablename)
    df=trans
    grouped_df = df.groupby('region')
    colors =['#a80975','darkorange','yellowgreen','k']
    #pdf=PdfPages("Samples_transcript_profile_summary.pdf")
    for i in range(0,(len(trans.columns)-3)):
            print("\n\n\n\n")
            fig,ax = plt.subplots()
            index=[]
            label=[]
            for key, item in grouped_df:
                label.append(key.split("_")[0])
                index.append(grouped_df.get_group(key)[trans.columns[i]].keys()[len(grouped_df.get_group(key)[trans.columns[i]].keys())-1])
            ax.grid(which='major', linestyle='-', linewidth='0.25')
            ax.yaxis.set_major_formatter(FuncFormatter(y_fmt))
            plt.plot(df[trans.columns[i]],linewidth=3.5,color="blue",linestyle="-")        
            for ii in range(0,len(index)):
                plt.axvline(x=index[ii], linewidth=3, color=colors[ii],linestyle="--")
            plt.xticks(fontsize = 14,weight='bold')
            plt.ylabel('Frequency',**axis_font,labelpad=40)
            fig = plt.gcf()
            fig.set_size_inches(11,6)
            plt.yticks(fontsize = 14,weight='bold')
            plt.title("Transcript Profile", **title_font)
            legend_properties = {'weight':'bold','size':'14'}
            label.insert(0,trans.columns[i])
            plt.xlabel(''.join(["\n\n       (Sample:",trans.columns[i],")"]),size=14,color='black',weight='bold')
            leg = plt.legend(label,prop=legend_properties,bbox_to_anchor=(1.43,1.02),frameon=True)
            leg.get_frame().set_edgecolor('k')
            leg.get_frame().set_linewidth(2)
            leg.get_title().set_fontsize(16)
            leg.get_title().set_fontweight('bold')
            plt.tight_layout()
            #plt.savefig(''.join([trans.columns[i],'_transcript_profile.png']),bbox_inches='tight',pad_inches=0.6)
            plt.show()
            plt.close()
            #pdf.savefig(fig,bbox_inches='tight',pad_inches=0.6)
    #pdf.close()
    
#getTables("csvdb")#a80975
transcriptProfileReport("../csvdb","transcript_profile")














Created with Jupyter,by Reshma.