Rules99's picture
LF
22bda93
import numpy as np
import pickle
import pandas as pd
# import requests
# from selenium import webdriver
import matplotlib.pyplot as plt
#Simple assignment
# from selenium.webdriver import Firefox
# from selenium.webdriver.common.keys import Keys
# from selenium.common.exceptions import NoSuchElementException
# import requests
import os
import seaborn as sns
from collections import Counter
import plotly.express as px
import streamlit as st
### Scrap the cosmic id information
# ### FRAMEWORKS NEEDED
# def scrap():
# #### Setting options to the driver
# options = webdriver.FirefoxOptions()
# options.add_argument('--headless')
# options.add_argument('--no-sandbox')
# options.add_argument('--disable-dev-shm-usage')
# options.capabilities
# ### Setting options of webdriver
# # a) Setting the chromedriver
# browser = Firefox(options=options,executable_path=r"C:\Users\Pablo\OneDrive\Documents\Documentos\Escuela Politécnica Superior Leganés\4 AÑO\ASIGNATURAS\1 CUATRI\WEB ANALYTICS\PART 2\Milestone3\geckodriver.exe")
# ### Functions and execution to run the scrapping
# def getinfofromtable(oddrows:list,score:float,headertable)->list:
# rows = []
# for row in oddrows:
# cols = []
# for (i,col) in enumerate(row.find_elements_by_css_selector("td")):
# if i==headertable.index( 'Primary Tissue') or i==headertable.index('Primary Histology') or i==headertable.index('Zygosity'):
# cols.append(col.text)
# cols.append(score)
# rows.append(cols)
# return rows
# def getinfocosmic(mutationid):
# import time
# search = browser.find_element_by_id('search-field')
# search = search.find_element_by_class_name("text_def")
# search.send_keys(mutationid)
# search.send_keys(Keys.RETURN)
# time.sleep(5)
# try:
# container = browser.find_element_by_id("section-list")
# except NoSuchElementException:
# return []
# try:
# subq1 = container.text[container.text.find("score")+len("score"):]
# score = float(subq1[:subq1.find(")")].strip())
# except ValueError:
# score = 0
# section = browser.find_element_by_id("DataTables_Table_0")
# headertable = [header.text for header in section.find_element_by_tag_name("thead").find_elements_by_tag_name("th")]
# oddrows = section.find_elements_by_class_name("odd")
# evenrows = section.find_elements_by_class_name("even")
# l1 = getinfofromtable(oddrows,score,headertable)
# l1.extend(getinfofromtable(evenrows,score,headertable))
# # browser.close()
# return l1
# ## Looking for cosmic id info
# cosl = []
# browser.get("https://cancer.sanger.ac.uk/cosmic")
# for cos in cosmicinfo.reset_index()["COSMIC_ID"].iloc[20:]:
# if cos.find(",")!=-1:
# cos = cos.split(",")[0]
# cosl.append(getinfocosmic(cos))
# browser.get("https://cancer.sanger.ac.uk/cosmic")
### Pieplots
def pieplot(merging,id=0):
genecount = merging.groupby(by=["gene_name","UV_exposure_tissue","sampleID"]).count().reset_index()
if id==0:
gtype = genecount[genecount.UV_exposure_tissue=="Intermittently-photoexposed"]
if id ==1 :
gtype = genecount[genecount.UV_exposure_tissue=="Chronically-photoexposed"]
else:
gtype = genecount
gtype = gtype.groupby("gene_name").count()["sampleID"].reset_index()
gtype.sort_values(by="sampleID",ascending=False,inplace=True)
#define Seaborn color palette to use
colors = sns.color_palette('pastel')[0:len(gtype)]
#create pie chart
# plt.suptitle("Gene Occuring for different genes")
plt.pie(gtype.sampleID, labels =gtype.gene_name, colors = colors, autopct='%.0f%%',radius=2,textprops={"fontsize":9})
plt.show()
### Depending on what result you want you return one or another
def filterp4(dfgenes,id=0):
if id==0 or id==1:
if id==0:
chexposed= dfgenes[dfgenes.UV_exposure_tissue=="Intermittently-photoexposed"].sort_values(by=["mean_mut"],ascending=False)
if id==1:
chexposed= dfgenes[dfgenes.UV_exposure_tissue=="Chronically-photoexposed"].sort_values(by=["mean_mut"],ascending=False)
return px.bar(chexposed,x="gene_name",y="mean_mut",error_y="std")
if id==2:
return px.bar(dfgenes,x="gene_name",y="mean_mut",color="UV_exposure_tissue",barmode='group',error_y="std")
### Read scrapping done with cosmic ids
def read_scrap()->list:
with open('my_pickle_file.pickle', 'rb') as f :
cosbase = pickle.load(f)
return cosbase
### GendfClean
def gendfclean(cosbase,cid)->pd.DataFrame:
dfd = {"tissue": None , "histology": None,"zygosity": None, "score": None }
for i,key in enumerate(list(dfd.keys())):
dfd[key] = list(map(lambda x : np.array(x)[:,i].tolist() if x!=[] else [] ,cosbase))
dfd["cosmic_id"] = cid.tolist()
cosmicdb = pd.DataFrame(dfd)
cosmicdb = cosmicdb[(cosmicdb['tissue'].map(lambda d: len(d)) > 0) & (cosmicdb['histology'].map(lambda d: len(d)) > 0) & (cosmicdb['zygosity'].map(lambda d: len(d)) > 0) & (cosmicdb['score'].map(lambda d: len(d)) > 0) ]
cosmicdb["score"] = cosmicdb.score.apply(lambda x: float(x[0]))
return cosmicdb
### Look for stats of a gene
def inputgene(lookforgene,merging,id =0)->dict:
### id = 0--> Intermittently exposed
### id = 1--> Continuously exposed
genecount = merging.groupby(by=["gene_name","UV_exposure_tissue","sampleID"]).count().reset_index()
tgene = genecount[genecount.gene_name==lookforgene]
if id==0:
ph_gene = tgene[tgene.UV_exposure_tissue=='Intermittently-photoexposed']
else:
ph_gene = tgene[tgene.UV_exposure_tissue=="Chronically-photoexposed"]
### Statistiacs about gene|samples
stats = ph_gene.chr.describe()
dc = dict(stats)
dc["gene_name"] = lookforgene
if id==0:
dc["UV_exposure_tissue"] = 'Intermittently-photoexposed'
else:
dc["UV_exposure_tissue"] = 'Chronically-photoexposed'
return dc
### Look for stats of all genes
def gene_exposed(merging,id=0):
return pd.DataFrame(list(map(lambda gene: inputgene(gene,merging,id),merging.gene_name.unique())))
### Merge stats for continuous and intermittently exposed
def mergecontintinfo(merging):
### Continuously Exposed
cont_exposed_info = gene_exposed(merging,1)
### Intermittently Exposed
int_exposed_info = gene_exposed(merging,0)
return pd.concat([cont_exposed_info,int_exposed_info],axis=0)
#### Common tissues, zygosities and histologies
def explodecommon(bd,N,col):
return Counter(bd[col].apply(lambda x: list(x.keys())).explode()).most_common(N)
def pdcommon(db,col,uv:str)->pd.DataFrame:
df = pd.DataFrame(db).rename(columns={0:col,1:"Times_{}".format(col)})
df["UV_exposure_tissue"] = uv
return df
def get_N_common(df,col,N=10)->pd.DataFrame:
cosm = df.copy(True)
cosm[col] = cosm[col].apply(lambda x: Counter(x))
intcosm = cosm[cosm.UV_exposure_tissue=="Intermittently-photoexposed"]
contcosm = cosm[cosm.UV_exposure_tissue=="Chronically-photoexposed"]
infotissues = explodecommon(cosm,N,col)
inttissues = explodecommon(intcosm,N,col)
contissues = explodecommon(contcosm,N,col)
df1 = pdcommon(infotissues,col,"Total")
df2 = pdcommon(inttissues,col,"Intermittently-photoexposed")
df3 = pdcommon(contissues,col,"Chronically-photoexposed")
return pd.concat([df1,df2,df3],axis=0)
### Deatiled information of mutation type
def mut_type(x):
if x.mut_type=="Indel":
if len(x.ref)>len(x.mut):
return "Del"
elif len(x.mut)>len(x.ref):
return "In"
# if len(x.ref)>1 and len(x.mut)>1:
return x.ref+">"+x.mut
return x.mut_type
def distribution_gene(df,hue):
plot4 = df.groupby([hue,"mut_type_cus"]).count().reset_index().iloc[:,:3]
plot4 = plot4.rename(columns={"sampleID":"n_mut"})
plot4 = plot4.sort_values(by="mut_type_cus",ascending=True)
fig = px.bar(plot4,x="mut_type_cus",y="n_mut",color=hue,barmode="group")
return fig
directory = os.path.abspath("")
# from EDA_IMDb_functions import *
st.set_page_config(layout="wide")
st.set_option('deprecation.showPyplotGlobalUse', False)
dw,col1,wl = st.columns((1,0.5,1))
col1.image('img/descarga.jfif')
st.markdown("<h1 style='text-align:center;'>Somatic Mutations Analysis in skin</h1>",unsafe_allow_html=True)
st.sidebar.markdown("<h2 style='text-align:center;'>Index</h2>",unsafe_allow_html=True)
menu = st.sidebar.radio(
"",
("1. Intro", "2. Analysis of somatic mutations" ,'3. Sample Analysis (IGV)'),
)
# Pone el radio-button en horizontal. Afecta a todos los radio button de una página.
# Por eso está puesto en este que es general a todo
# st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True)
st.sidebar.markdown('---')
st.sidebar.markdown("<h2 style='text-align:center;'>Authors</h2>",unsafe_allow_html=True)
st.sidebar.markdown("<p style='text-align:center;'>Claudio Sotillos Peceroso</p>",unsafe_allow_html=True)
st.sidebar.markdown("<p style='text-align:center;'>Pablo Reyes Martin</p>",unsafe_allow_html=True)
@st.cache(allow_output_mutation=True)
def read_csv():
return pd.ExcelFile('Study Results.xlsx')
### Merge two dataframes
def definemerging(df1,df2):
merging = df1.merge(df2,on="sampleID",how="inner")
return merging
#### Reading the data
df = read_csv()
df1 = pd.read_excel(df, 'Dataset_S1').copy(deep=True)
df2 = pd.read_excel(df, 'Dataset_S2').copy(deep=True)
merging = None
### functions indexed
def wrt(text,tag="h1",align="center"):
return st.markdown(f"""
<{tag} style='text-align:{align};'>{text}</{tag}>
""",unsafe_allow_html=True)
def writetxt(text,tag="h1",align="center",container=st):
return container.markdown(f"""
<{tag} style='text-align:{align};'>{text}</{tag}>
""",unsafe_allow_html=True)
def space(tag="h1"):
return wrt("\n",tag=tag)
### 1. Introduciton
def set_home():
wrt("1. Introduction to the problem",tag="h2")
par1 = """
In this project, we have focus our study on the research paper as well as on
getting some conclusion by ourselves. Therefore there will be some contrast we will do in relation to the paper
as well as other plots not related with the paper. Also, we will perform the analysis of two samples that are
from quite opposite individuals."""
### 1.1
wrt(par1,tag="p style='font-size:21px;'",align="justify")
tit1 = """
1.1 Cancers arise as a result of somatic mutations
"""
wrt(tit1,tag="h4",align="left")
___,col1,_,col2,___ = st.columns((0.4,1,0.7,1,0.4))
cap1 = "Fig 1 : Types of Genomic Alterations"
col1.image("img/base.png",caption=cap1,width=500,use_column_width=True)
cap2 = "Fig 2 : Skin Risk Factors"
col2.image("img/risk_factors.png",caption=cap2,width=500,use_column_width=True)
with col2:
col2_par = """
The proportion of somatic mutations in normal cells is quite similar to the mutations of tumours in the same tissue cell.
Only a small fraction are the ones which provokes cancer.
"""
wrt(col2_par,tag="p style='font-size:20px;'",align="justify")
space()
### 1.2
tit1 = """
1.2 State of the art of the research
"""
wrt(tit1,tag="h4",align="left")
___,col1,_,col2,___ = st.columns((0.4,1.4,0.3,0.6,0.4))
cap1 = "Fig 1 : Types of Genomic Alterations"
col1.image("img/comboskin.JPG",caption="Fig 3 : Cutaneous Sensitivity",width=600,use_column_width=True)
# cap2 = "Fig 2 : Skin Risk Factors"
col2.image("img/s_exposure.JPG",width=600,use_column_width=True)
# col1,middle,col2 = st.columns((0.2,3,0.2))
with col2:
col2_par = """
- About 25,50% of the normal skins acquires one driver mutation.
- Chronic sun exposure tends to proliferate keratinocytes (cutaneous squamous cell carcinoma)
- Melanomas appears more in sporadic skin sun exposure (attributable to intermittent pattern of sun exposure with recreational activities)
"""
st.markdown(col2_par)
# wrt(col2_par,tag="p",align="center")
space()
par2= """
The research studies which are the main factors that causes somatic mutations in skin. The research analyzes 46 genes per sample.
Skin samples were collected from different body areas, classified according to the pattern of sunlight exposure as
chronically-photoexposed (n = 44) and intermittently photoexposed (n = 79).
"""
wrt("1.3 Skin samples analysis",tag="h4",align="left")
wrt(par2,tag="p style='font-size:21px;'",align="justify")
import plotly.graph_objects as go
set = ["Chronically Sun Exposure","Inttermittently Sun Exposure"]
n = [44,79]
fig = go.Figure(data=[go.Pie(labels=set, values=n,textinfo=f'label+percent',
insidetextorientation='radial',hole=.3)])
fig.update_layout(title_text ="Samples of the dataset depending on the sun exposure",annotations=[dict(text="46 genes per sample",font_size=20, showarrow=False)])
__,col1,__,col2,__ = st.columns((0.2,1,0.5,0.5,0.2))
col1.plotly_chart(fig,use_container_width=True)
val = round(df1.groupby("sampleID").count()["chr"].mean(),2)
pnt = round(val/46,2)
col2.header("\n\n\n")
col2.header("\n\n\n")
col2.header("\n\n\n")
col2.metric("Average of mutations per sample",val)
col2.metric("Average Percentage of genes that mutate per sample",pnt)
#### 2. Plots Dataframe visualization Conclusion
def set_chintp():
global merging
wrt("2. Analysis of somatic mutations",tag="h3")
par1 = """
We are going to discuss some plots related to the paper. Moreover, we are going to explore mutations of genes that occured within our samples as well as go beyond our data base, exploring
mutations that have cosmic ids so that we can show more detailed information about the mutation. We often face samples that are intermittently photoexposed to sunlight against the ones which are continuously exposed
to contrast two distinct populations.
"""
wrt(par1,tag="p style='font-size:21px;",align="justify")
wrt("2.1 Description of the dataset",tag="h4",align="left")
par1 = """
They focused on sequencing 123 samples of healthy skin (from different areas,permanently or intermittently photo-exposed) of cancer-free
individuals. It was taken just one skin sample per individual.
From each of these samples, a deep sequencing of 46 genes (which are implicated in skin cancer) is carried out.
This means that they had to analyze 5658 genes. Out of these amount of genes they found 5214 somatic mutations, which are the ones
which we have in our dataset.
"""
wrt(par1,tag="p style='font-size:21px;",align="justify")
st.image("img/dataset.png",width=600,use_column_width=True)
st.image("img/skin.png",width=600,use_column_width=True)
wrt("2.2 Average and Standard deviation of mutations",tag="h4",align="left")
par3 ="""
The research tells that if the skin were exposed more to the skin, it will be more likely to suffer somatic mutations.
The first plot represent the average and sd of mutations that have samples which are intermittently and continuously exposed to sunlight.
"""
wrt(par3,tag="p style='font-size:21px;",align="justify")
#### CODE PLOT 1
merging = definemerging(df1,df2)
plot = merging.groupby("sampleID").agg({"gene_name":"count"}).merge(df2[["sampleID","UV_exposure_tissue"]],on="sampleID",how="inner")
plot = plot.rename(columns={"gene_name":"n_of_mutations"})
fig = plt.figure(figsize=(5,3))
sns.barplot(data=plot,x="UV_exposure_tissue",y="n_of_mutations")
plt.suptitle("Average and standard deviation of mutations per type tissue photoexposed")
st.pyplot(fig,clear_figure=True)
wrt("\n")
### Plot 3
# """Number of samples that has a mutation at least one time per gene"""
wrt("2.3 Number of samples per gene captured at least one time",tag="h4",align="left")
par = """
This takes the number of times that a gene appears at least once time in the samples intermittently and continuously exposed.
The first plots is used for the samples that are intermittently exposed and the second plot is used for the ones which are continously exposed
"""
print( merging.UV_exposure_tissue.unique())
wrt(par,tag="p style='font-size:21px;",align="justify")
wrt("Select the exposure tissue you want",tag="h6",align="left")
box = st.selectbox("", merging.UV_exposure_tissue.unique().tolist()+["Total"],key="key1")
if box==merging.UV_exposure_tissue.unique()[0]:
wrt("Gene proportion (Intermittently Exposed)",tag="h5",align="center")
pieplot(merging,0)
st.pyplot()
if box==merging.UV_exposure_tissue.unique()[1]:
wrt("Gene proportion (Continuously Exposed)",tag="h5",align="center")
pieplot(merging,1)
st.pyplot()
if box=="Total":
wrt("Gene proportion (Total)",tag="h5",align="center")
pieplot(merging,2)
st.pyplot()
### Plot 4
dfgenes = mergecontintinfo(merging)
dfgenes["mean_mut"] = dfgenes["mean"]
wrt("2.4 Average and standard deviation of mutations per gene",tag="h4",align="left")
par = """
In this graph we will visualize the average and standard deviation of mutation per gene
"""
wrt(par,tag="p style='font-size:21px;",align="justify")
wrt("Select the exposure tissue you want",tag="h6",align="left")
box2 = st.selectbox("", merging.UV_exposure_tissue.unique().tolist()+["Total"],key="key2")
if box2==merging.UV_exposure_tissue.unique()[0]:
fig = filterp4(dfgenes)
if box2==merging.UV_exposure_tissue.unique()[1]:
fig = filterp4(dfgenes,1)
if box2=="Total":
fig = filterp4(dfgenes,2)
st.plotly_chart(fig,use_container_width=True)
#### SECTION 2.2
wrt("2.5 Number of mutations per gene and skin phototype",tag="h4",align="left")
par ="""
These visualizations reflectas the average of mutations that are per age of samples and is divided per skin_phototype
"""
wrt(par,tag="p style='font-size:21px;",align="justify")
#### CODE PLOT 2
col1,col2 = st.columns((1,1))
plot2= df2.merge(merging.groupby("sampleID").agg({"gene_name":"count"}).reset_index(),on="sampleID",how="inner")
plot2 =plot2.rename(columns={"gene_name":"n_mutations"})
plot2.n_mutations = plot2.n_mutations.astype(int)
### plot 2.1
sns.set()
plt.figure()
sns.lmplot(data=plot2.sort_values(by="skin_phototype"),x="age",y="n_mutations",col="skin_phototype",lowess=True,col_wrap=2)
col1.pyplot()
### plot 2.2
sns.set()
plt.figure()
sns.lmplot(data=plot2,x="age",y="n_mutations",hue="skin_phototype",lowess=True)
plt.title("Regression of number of mutations per skin phototype")
col2.pyplot()
writetxt("""Fig 4:Number of mutations per gene and skin phototype""",tag="h6",container=col2 )
wrt("2.6 Number of mutations per exposure tissue condition and sun damage tissue",tag="h4",align="left")
par ="""
We take the average of mutations that we have per type of sample (exposure_tissue type) and if it presents sun damage tissue a priori or not
"""
wrt(par,tag="p style='font-size:21px;",align="justify")
fig = plt.figure(figsize=(5,1))
p = sns.displot(df2, x="UV_exposure_tissue", hue="sun_damage_tissue", multiple="dodge",height=3,aspect=4)
p.fig.set_dpi(100)
st.pyplot(clear_figure=True)
wrt("2.7 Influence of sun damage tissue",tag="h4",align="left")
par ="""
We can see that the sun damage tissue influence generally on the number of mutations in the gene.
"""
wrt(par,tag="p style='font-size:21px;",align="justify")
fig = plt.figure(figsize=(5,1))
p=sns.displot(df2, x="age", hue="sun_damage_tissue", multiple="dodge",height=3,aspect=4).set(title='Age VS Sun Damage')
p.fig.set_dpi(100)
st.pyplot(clear_figure=True)
#### Age vs uv photexposure
wrt("2.8 Number of mutations per year and UV_exposure tissue",tag="h4",align="left")
par =""" We can distinguish between two sample the average of mutations that are got per year"""
wrt(par,tag="p style='font-size:21px;",align="justify")
fig = plt.figure(figsize=(5,2))
# sns.set(rc={'figure.figsize':(3,1),"figure.height":2})
ax = sns.kdeplot(data=df2, x="age", hue="UV_exposure_tissue")
plt.setp(ax.get_legend().get_texts(), fontsize='5') # for legend text
plt.setp(ax.get_legend().get_title(), fontsize='8') # for legend title
st.pyplot()
### Mut type cus plot
wrt("2.9 How is the mutation in comparison with the reference base ?",tag="h4",align="left")
par ="""
We want to know between all the mutations occured (with and without cosmic id) what are the most common mutation type occured
"""
wrt(par,tag="p style='font-size:21px;",align="justify")
merging["mut_type_cus"] = merging.apply(mut_type,axis=1)
hue = st.selectbox("Select label for you want to color: ",['sex', 'UV_exposure_tissue', 'sun_damage_tissue',
'sun_history', 'skin_phototype'],index=1)
fig = distribution_gene(merging,hue)
# plot4 = merging.groupby(["UV_exposure_tissue","mut_type_cus"]).count().reset_index().iloc[:,:3]
# plot4 = plot4.rename(columns={"sampleID":"n_mut"})
# plot4 = plot4.sort_values(by="mut_type_cus",ascending=True)
# fig = px.bar(plot4,x="mut_type_cus",y="n_mut",color="UV_exposure_tissue",barmode="group")
st.plotly_chart(fig,use_container_width=True)
### Muations cosmic and non cosmic id
wrt("2.10 Where does mutations usually occur ?",tag="h4",align="left")
par = "In this section we visualize where the mutations usually occurs as well as tumours that may be caused these mutations. Note that we can get this information just for all the samples that contains cosmic id."
wrt(par,tag="p style='font-size:21px;",align="justify")
# merging = definemerging(df1,df2)
#### Cosmicinformation
cosmicinfo = merging[merging.COSMIC_ID.isna()==False].groupby(["gene_name","COSMIC_ID"]).count()
#### Cosmic ids
cinfo = cosmicinfo.reset_index()
cid = cinfo["COSMIC_ID"]
### Read info scrapped
cosbase = read_scrap()
cosmicdb = gendfclean(cosbase,cid)
cosmerge = merging.merge(cosmicdb,left_on="COSMIC_ID",right_on="cosmic_id",how="inner")
cols = ["tissue","histology"]
p1,p2 = st.columns((1,1))
for col,p in zip(cols,[p1,p2]):
dtemp = get_N_common(cosmerge,col)
#### Intermittently exposed
#### Continuously exposed
fig = px.bar(dtemp,x=dtemp.columns[0],y=dtemp.columns[1],color=dtemp.columns[2],barmode="group")
p.plotly_chart(fig)
### Percentage of VAF
wrt("2.11 Percentage of VAF captured in all mutations and its distribution. Depth Coverage distribution",tag="h4",align="left")
par=""" We want to proof that somatic mutations are tough to capture . To do that we have plot the variant allele frequency
distribution of the mutations to proof that the majority of them have a low score VAF
"""
wrt(par,tag="p style='font-size:21px;'",align="justify")
res = str(round(((df1.shape[0]-sum(df1['VAF']>0.05))/df1.shape[0])*100,2))+'%'
# plt.figure(figsize=(5,3))
fig = px.box(df1,y="VAF")
fig2 = px.box(df1,y="DP")
__,col1,__,col2,__ = st.columns((0.3,1,0.3,1,0.3))
# plt.text('Those outliers are the ones higher than 5%. There are',str(df1.shape[0]-sum(df1['VAF']<0.05)),'mutations higher than 5%.')
col1.plotly_chart(fig,clear_figure=True,use_container_width=True)
col2.plotly_chart(fig2,clear_figure=True,use_container_width=True)
par =f"""
Those outliers are the ones higher than 5%. There are {str(df1.shape[0]-sum(df1['VAF']<0.05))} mutations higher than 5%.
"""
wrt(par,tag="p",align="center")
wrt("2.12 Evolution of the C>T mutations with the age",tag="h4",align="left")
par =f"""
The plot shows us that the number of C>T (a UV associated mutation) mutations increases with the evolution of the age.
"""
wrt(par,tag="p style='font-size:21px;'",align="center")
plts = merging[merging.mut_type=="C>T"].groupby("age").count().reset_index()[["age","VAF"]]
plts.rename(columns={"VAF":"C>T"},inplace=True)
__,col1,__ = st.columns((1,3,1))
fig = plt.figure(5,2)
sns.lmplot(
data=plts,
x="C>T",
y="age",
logx=True,
height=3, aspect=3
).set(title="Logarithmic increase of number of C>T")
col1.pyplot()
wrt("2.13 Mean of pathogenic score in different genes",tag="h4",align="left")
# par =f"""
# The plot shows us that the number of C>T (a UV associated mutation) mutations increases with the evolution of the age.
# """
# wrt(par,tag="p style='font-size:21px;'",align="center")
# plts = merging[merging.mut_type=="C>T"].groupby("age").count().reset_index()[["age","VAF"]]
# plts.rename(columns={"VAF":"C>T"},inplace=True)
# __,col1,__ = st.columns((1,3,1))
# fig = plt.figure(5,2)
# sns.lmplot(data=plts,x="C>T",y="age",logx=True,height=3,aspect=3).set(title="Logarithmic increase of number of C>T")
# col1.pyplot()
dbinfo = merging.merge(cosmicdb,left_on="COSMIC_ID",right_on="cosmic_id",how="left")
df12 = dbinfo[dbinfo.cosmic_id.isna()==False].groupby("gene_name").mean().reset_index()[["gene_name","score"]].sort_values(by="score",ascending=False)
___,col,___ = st.columns((2,1,2))
with col:
st.dataframe(df12)
return None
def cidvars():
wrt("3. Individual gene information",tag="h2")
par1 = """
We are going to explore mutations of genes that occured within our samples as well as go beyond our data base, exploring
mutations that have cosmic ids so that we can show more detailed information about the mutation.
"""
wrt(par1,tag="p",align="center")
wrt("3.1 Where does mutations usually occur ?",tag="h3",align="left")
par = "In this section we visualize where the mutations usually occurs as well as tumours that may be caused these mutations. Note that we can get this information just for all the samples that contains cosmic id"
wrt(par,tag="p",align="justify")
merging = definemerging(df1,df2)
#### Cosmicinformation
cosmicinfo = merging[merging.COSMIC_ID.isna()==False].groupby(["gene_name","COSMIC_ID"]).count()
#### Cosmic ids
cinfo = cosmicinfo.reset_index()
cid = cinfo["COSMIC_ID"]
### Read info scrapped
cosbase = read_scrap()
cosmicdb = gendfclean(cosbase,cid)
cosmerge = merging.merge(cosmicdb,left_on="COSMIC_ID",right_on="cosmic_id",how="inner")
cols = ["tissue","histology"]
p1,p2 = st.columns((1,1))
for col,p in zip(cols,[p1,p2]):
dtemp = get_N_common(cosmerge,col)
#### Intermittently exposed
#### Continuously exposed
fig = px.bar(dtemp,x=dtemp.columns[0],y=dtemp.columns[1],color=dtemp.columns[2],barmode="group")
p.plotly_chart(fig)
### Mut type cus plot
wrt("3.2 How is the mutation in comparison with the reference base ?",tag="h3",align="left")
par ="""
We want to know between all the mutations occured (with and without cosmic id) what are the most common mutation type occured
"""
wrt(par,tag="p",align="justify")
merging["mut_type_cus"] = merging.apply(mut_type,axis=1)
plot4 = merging.groupby(["UV_exposure_tissue","mut_type_cus"]).count().reset_index().iloc[:,:3]
plot4 = plot4.rename(columns={"sampleID":"n_mut"})
fig = px.bar(plot4,x="mut_type_cus",y="n_mut",color="UV_exposure_tissue",barmode="group")
col1.plotly_chart(fig,use_container_width=True)
col2.plotly_chart()
return None
## Slide in which we will explain the pipeline followed in order to analyze the two samples we have.
def set_igv():
wrt("3. Sample Analysis (IGV)",tag="h2")
par1 = """
Explanation of the steps followed to process our raw samples into files which can be interpreted with the IGV program (VCF files).
"""
wrt(par1,tag="p style='font-size:21px;'",align="center")
wrt("3.1 Which Samples do we have?",tag="h4",align="left")
par2 = """
We wanted two samples of very oposite individuals, with the goal of being able to appreciate noticable differences when sequencing
the genes.
- AG0312: Sample of a Male individual of 70 years old, whose skin sample is Intermittently-photoexposed, and it has a skin phototype of I.
- AG0322: Sample of a Female individual of 38 years old, whose skin sample is Chronically-photoexposed, and it has a skin phototype of IV.
"""
wrt(par2,tag="p style='font-size:21px;'",align="justify")
wrt("3.2 Processing Steps",tag="h4",align="left")
par3 = """
- 1. Quality Control and Alignment
Initially, both samples were in bam format, thus are samples of good quality (since they passed the quality step) and also are aligned.
Thus we started our preprocessing by refinning the Alignment.
"""
par4 = """
- 2. Refinement of Alignment
Since for performing Variant Calling we need to have our samples sorted by genomic positions. Once sorted we mark
the duplicates (in these exist) so that the these are ignored in the Variant Calling step.
Finally we just index the resulting bam files for its future visualization.
"""
par5 = """
- 3. Variant Calling
Once we arrived to this section we had to solve an error which initially we didn't knew why it happend. The error ocurred when
we tried to identify the active regions (error shown on the below image).
The problem consited on that, in the refined bam the chromosomes were represented just with their number, and in the reference
genome (hg19) chromosomes were represented as "chr N". Thus just by eliminating the "chr" part in the reference genome, the
variant calling could be accomplished.
"""
par6 = """
- 4. Visualization with IGV
With the variant calling files computed, we are ready now to display the variants in our Alignments.
We tried to do a simple task, which was just to try to find the mutations which the researchers of the paper found for our samples.
For doing this we used the chromosome and position indicators of their dataset.
Near the positions idicated we found the mentioned mutation in the dataset, however not in the exact position.
"""
wrt(par3,tag="p style='font-size:21px;'",align="justify")
wrt(par4,tag="p style='font-size:21px;'",align="justify")
wrt(par5,tag="p style='font-size:21px;'",align="justify")
st.image("img/error.png",use_column_width=True)
wrt(par6,tag="p style='font-size:21px;'",align="justify")
st.image("img/chartc.png",use_column_width=True)
st.header("\n")
st.header("\n")
st.header("\n")
wrt("Igv Images",tag="h1",align="center")
st.header("\n")
st.header("\n")
st.header("\n")
__,col1,__,col2,__ = st.columns((0.2,1.5,0.3,1,0.2))
with col1:
st.image("img/col1igv.png",use_column_width=True,caption="Fig 5: Igv rep AG0312")
with col2:
st.image("img/col2igv.png",use_column_width=True,caption="Fig 6: Igv representation AG0322")
return None
if menu == '1. Intro':
set_home()
elif menu == '2. Analysis of somatic mutations':
set_chintp()
# elif menu == '3. Individual sample information':
# cidvars()
elif menu == '3. Sample Analysis (IGV)':
set_igv()
# elif menu == 'Otras variables':
# set_otras_variables()
# elif menu == 'Relaciones entre variables':
# set_relations()
# elif menu == 'Matrices de correlación':
# set_arrays()