File size: 33,777 Bytes
356b18e
 
 
66ab79e
 
356b18e
 
66ab79e
 
50199cc
 
356b18e
 
 
 
 
 
 
 
 
 
 
66ab79e
 
 
 
 
 
 
 
 
 
 
356b18e
 
66ab79e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356b18e
66ab79e
 
356b18e
66ab79e
356b18e
66ab79e
 
 
 
356b18e
 
 
66ab79e
356b18e
 
66ab79e
356b18e
66ab79e
 
356b18e
66ab79e
 
356b18e
66ab79e
 
 
 
 
 
 
 
356b18e
66ab79e
 
356b18e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f8cc36
 
 
 
 
 
 
 
 
 
 
356b18e
9f8cc36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22bda93
9f8cc36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
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()