-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathanalysis.py
5749 lines (4685 loc) · 279 KB
/
analysis.py
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import BatchEffects
import BiomartFunctions
import CCLETools
import Cellosaurus
import ENSEMBLTools
import GeneSetScoring
import GeneOntology
import HGNCFunctions
import LMMelTools
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.patheffects as PathEffects
import numpy as np
import os
import pandas as pd
import scipy.cluster.hierarchy as SciPyClus
import scipy.stats
from scipy.stats import gaussian_kde
from lifelines import CoxPHFitter
from lifelines.estimation import KaplanMeierFitter
from lifelines.statistics import logrank_test as KMlogRankTest
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Python script for the analysis and figures in the manuscript:
# Cursons et al (2019), Cancer Immunology Research.
# DOI: not-yet-known
#
# This script uses a collection of python libraries as well as a set of custom libraries generated by Joe Cursons. These
# dependencies will be uploaded over the coming weeks, but for priority access to my private repository please feel
# free to contact me directly: cursons.j (at) wehi.edu.au
# joe.cursons (at) gmail.com
#
# NB: file paths for data are hard coded below and users will be required to update these paths as appropriate for
# their filesystem and data locations
#
# Single cell RNA-seq analyses were performed by Sepideh (Momeneh) Foroutan: momeneh.foroutan (at) unimelb.edu.au
# Associated R scripts will be uploaded over the coming weeks (e.g. for the generation of UMAP plots in Fig. 3).
#
# For The Cancer Genome Atlas (TCGA) skin cutaneous melanoma (SKCM) data, users are directed towards the NIH/NCI genomic
# data commons (GDC): https://portal.gdc.cancer.gov/projects/TCGA-SKCM
# Data can be downloaded directly using the genomic data commons client (gdc-client), with a manifest generated from the
# GDC website
# The authors thank TCGA for making these data freely available, and in particular we would like to acknowledge the
# patients who generously donated samples for this project.
# For further details please refer to the original TCGA SKCM manuscript:
# Genomic Classification of Cutaneous Melanoma. Cell. (2015). 161(7): pp. 1681-1696
# https://www.cell.com/cell/fulltext/S0092-8674(15)00634-0
# doi: 10.1016/j.cell.2015.05.044
#
# This script also uses data from a number of other studies:
# The LM-MEL melanoma cell line panel
# GSE60424
# GSE24759
#
# This script has dependencies for a number of python libraries. Unfortunately due to space/reference limitations we
# were unable to include the full set of citations within our manuscript, but we would like to acknowledge the
# developers who work on these open source tools:
# matplotlib: https://matplotlib.org/
# scipy: https://www.scipy.org/
# numpy: https://www.numpy.org/
# lifelines: https://lifelines.readthedocs.io/en/latest/
# pandas: https://pandas.pydata.org/
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# This script has been split into three classes with corresponding functions:
# PreProc: a series of functions which performs pre-processing on different data sets to make sample accession easier
# for corresponding subsets of samples etc
# * split_tcga_met_vs_pri()
# * tcga_skcm_rna_data()
# * tcga_skcm_data()
# * tcga_skcm_classifications()
# * tcga_skcm_met_sites()
# * lm_mel_data()
# * gse60424_data()
# * gse24759_data()
# * gse24759_subsets()
# * tcga_histology()
# * density_scatters()
# * refine_NK_signature()
# Analyse:
# * split_one_marker_three_partitions()
# * split_two_markers_four_partitions()
# Plot:
# * fig_one_and_supp_table_one()
# * fig_two()
# * fig_four()
# * fig_five()
# * supp_fig_one()
# * supp_fig_three()
# * supp_fig_four()
# * supp_fig_five()
# * supp_fig_six()
# * supp_fig_seven()
# * supp_fig_eight()
# * supp_fig_nine()
# * NB: figure 3 (UMAP plots of single cell RNA-seq data) were generated using associated R scripts
# * NB: Supplementary Figure S2 (workflow figure) was created using a graphical editor
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# DATA PRE-PROCESSING FUNCTIONS
class PreProc:
strDataBaseLoc=os.getcwd()
strExtraAnalysisPath = os.getcwd()
listClinDataOfInt = ['gender',
'age_at_diagnosis',
'vital_status',
'days_to_death',
'days_to_last_follow_up',
'site_of_resection_or_biopsy']
# As part of the supplementary material we investigated survival effects associated with metastatic tumour site; to facilitate a statistical analysis a number of different regions were grouped based on similar locations according to this dictionary:
dictMetSiteGroupings = {
'Brain, NOS': 'CNS',
'Frontal lobe':'CNS',
'Spinal cord':'CNS',
'Parietal lobe':'CNS',
'Connective, subcutaneous and other soft tissues':'Connective',
'Connective, subcutaneous and other soft tissues, NOS':'Connective',
'Connective, subcutaneous and other soft tissues of lower limb and hip':'Connective',
'Connective, subcutaneous and other soft tissues of upper limb and shoulder':'Connective',
'Connective, subcutaneous and other soft tissues of thorax': 'Connective',
'Connective, subcutaneous and other soft tissues of pelvis': 'Connective',
'Connective, subcutaneous and other soft tissues of abdomen': 'Connective',
'Connective, subcutaneous and other soft tissues of trunk, NOS': 'Connective',
'Connective, subcutaneous and other soft tissues of head, face, and neck': 'Connective',
'Peritoneum, NOS': 'Internal, other',
'Thorax, NOS': 'Internal, other',
'Abdomen, NOS': 'Internal, other',
'Pelvis, NOS': 'Internal, other',
'Liver': 'Internal organ',
'Spleen': 'Internal organ',
'Adrenal gland, NOS': 'Internal organ',
'Parotid gland': 'Internal organ',
'Pelvic lymph nodes': 'Lymph nodes of inguinal region or leg',
'Intra-abdominal lymph nodes': 'Lymph node, NOS',
'Small intestine, NOS': 'Epithelial tissue',
'Vagina, NOS': 'Epithelial tissue',
'Colon, NOS': 'Epithelial tissue',
'Vulva, NOS': 'Epithelial tissue',
'Skin of trunk': 'Skin',
'Skin of lower limb and hip':'Skin',
'Skin of upper limb and shoulder':'Skin',
'Skin of scalp and neck':'Skin',
'Skin, NOS':'Skin',
'Upper lobe, lung':'Lung',
'Lower lobe, lung':'Lung',
'Lung, NOS':'Lung'}
def split_tcga_met_vs_pri(flagResult=False):
"""Process the GDC sample sheet & clinical metadata file to label samples and split primary/metastatic tumours"""
# This function processes the NIH/NCI genomic data commons (GDC) sample sheet for the TCGA SKCM cohort, together
# with the clinical metadata file to identify samples split by the presence of primary/metastatic tumour
# samples and the availability of data on patient age.
#
# As outlined within the corresponding manuscript there are unexpected survival differences between patients
# with primary and metastatic tumours, and thus this analysis has focussed on the larger set of metastatic
# samples. Furthermore to examine age-associated survival effects we have dropped samples where patient age
# and/or survival data are unavailable.
#
# The TCGA SKCM sample sheet and clinical data can be downloaded directly from the genomic data commons website
# (i.e. the gdc-client is not required):
# https://portal.gdc.cancer.gov/projects/TCGA-SKCM
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Load the required TCGA SKCM meta-data
dfSampMap = pd.read_table(os.path.join(PreProc.strDataBaseLoc, 'gdc_sample_sheet.2018-03-26.tsv'), sep='\t',
header=0, index_col=None)
dfClinData = pd.read_table(
os.path.join(PreProc.strDataBaseLoc, 'clinical.tsv'),
sep='\t', header=0, index_col=None)
dfClinData.set_index('submitter_id', inplace=True)
# identify samples with valid survival data; note that 'survival time' are split into two columns depending on
# whether the patient was deceased (days_to_death) or alive (days_to_last_follow_up) at data release
arrayDeathDataAreClean = np.bitwise_and((dfClinData['vital_status'] == 'dead').values.astype(np.bool),
~(dfClinData['days_to_death'] == '--').values.astype(np.bool))
arrayAliveDataAreClean = np.bitwise_and((dfClinData['vital_status'] == 'alive').values.astype(np.bool),
~(dfClinData['days_to_last_follow_up'] == '--').values.astype(np.bool))
arraySurvDataAreClean = np.bitwise_or(arrayDeathDataAreClean,arrayAliveDataAreClean)
# extract the index labels corresponding to these rows
listSurvDataAreClean = [dfClinData.index.tolist()[i] for i in np.where(arraySurvDataAreClean)[0]]
# Identify target sample subsets with metastatic/primary tumours
listPatsPriTum = dfSampMap['Case ID'][dfSampMap['Sample Type'] == 'Primary Tumor'].values.tolist()
listPatsMetTum = dfSampMap['Case ID'][dfSampMap['Sample Type'] == 'Metastatic'].values.tolist()
# identify the corresponding patient subsets
listPatsMetTumOnly = [strPatient
for strPatient in listPatsMetTum
if np.bitwise_and(strPatient not in listPatsPriTum,
strPatient in listSurvDataAreClean)]
listPatsPriTumOnly = [strPatient
for strPatient in listPatsPriTum
if np.bitwise_and(strPatient not in listPatsMetTum,
strPatient in listSurvDataAreClean)]
listPatsWithMetTumAndAge = [strPatient
for strPatient in listPatsMetTumOnly
if not dfClinData['age_at_diagnosis'].loc[strPatient] == '--']
# output as a dictionary
return {'MetOnlyPat':listPatsMetTumOnly,
'PriOnlyPat':listPatsPriTumOnly,
'MetOnlyPatWithAge':listPatsWithMetTumAndAge}
def tcga_skcm_rna_data(flagResult=False,
strMessRNADataFolder='mRNAseq_preproc',
strMessRNADataFilename='SKCM.uncv2.mRNAseq_RSEM_all.txt'):
"""Process the TCGA SKCM RSEM normalised RNA-seq data into a dataframe"""
pathMessRNAData = os.path.join(PreProc.strDataBaseLoc, strMessRNADataFolder)
dfRSEMData = pd.read_table(
os.path.join(pathMessRNAData, strMessRNADataFilename),
sep='\t', header=0, index_col=None)
listGeneAndEntrez = dfRSEMData['HYBRIDIZATION R'].values.tolist()
# For some reason there exists 2 entries of the gene SLC35E2 which has subsequently been split into SLC35E2A and
# SLC35E2B - the Entrez ID is corrected for this accordingly
numRowMisLabelled = listGeneAndEntrez.index('SLC35E2|728661')
listGeneAndEntrez[numRowMisLabelled] = 'SLC35E2B|728661'
dfRSEMData['HYBRIDIZATION R'] = pd.Series(listGeneAndEntrez, index=dfRSEMData.index.tolist())
# Drop all entries/rows where the HGNC identifier as unknown as I match on HGNC symbol
arrayRowsWithCleanGenes = np.where([not strGene[0:2] == '?|' for strGene in listGeneAndEntrez])[0]
dfOut = dfRSEMData.iloc[arrayRowsWithCleanGenes,:].copy(deep=True)
# Split the identifier column to extract the HGNC symbols and set this as the index
listHGNC = [strRow.split('|')[0] for strRow in dfOut['HYBRIDIZATION R'].values.tolist()]
dfOut['HGNC'] = pd.Series(listHGNC, index=dfOut.index.tolist())
dfOut.set_index('HGNC', inplace=True)
dfOut.drop(columns=['HYBRIDIZATION R'],
inplace=True)
return dfOut
def tcga_skcm_data(flagResult=False,
flagPerformExtraction=False,
strMergedFileName='merged_tcga_skcm.pickle',
listClinDataToMerge=listClinDataOfInt):
"""Combine the various TCGA SKCM data sets and perform gene set scoring"""
# specify gene lists used for analysis
listBottcherNKGenes = ['NCR3', 'KLRB1', 'PRF1', 'CD160', 'NCR1']
listBottchercDC1Genes = ['XCR1', 'CLEC9A', 'CLNK', 'BATF3']
if not os.path.exists(strMergedFileName):
flagPerformExtraction = True
if flagPerformExtraction:
# Load a processed dictionary with the original TCGA 'Immune' gene set and classifications for immune high/low
dictTCGAClassifications = PreProc.tcga_skcm_classifications()
# # # # # # # # # # # # # # # # # # # # # # # # #
# Load molecular (RNA-seq) data
dfRSEMData = PreProc.tcga_skcm_rna_data()
# Process the sample names as a list
listColumns = dfRSEMData.columns.tolist()
listSamples = [strCol for strCol in listColumns if strCol[0:4]=='TCGA']
numTotSamples = len(listSamples)
# Pull out the genes within these data and create a set for later comparisons
listTCGAGenes = dfRSEMData.index.tolist()
setTCGAGenes = set(listTCGAGenes)
# # # # # # # # # # # # # # # # # # # # # # # # #
# Extract and curate clinical data
dfClinData = pd.read_table(
os.path.join(PreProc.strDataBaseLoc, 'clinical.tsv'),
sep='\t', header=0, index_col=None)
dfClinData.set_index('submitter_id', inplace=True)
listSampleCaseID = [strSample.rpartition('-')[0] for strSample in listSamples]
dfClinDataOut = dfClinData[listClinDataToMerge].loc[listSampleCaseID]
dfClinDataOut['SampleID'] = listSamples
dfClinDataOut.set_index('SampleID', inplace=True)
# identify samples which are dead (i.e. where a death event as happened)
arrayPatientIsDead = np.array([strStatus == 'dead'
for strStatus in dfClinDataOut['vital_status'].tolist()],
dtype=np.bool)
# find entries for dead patients where days_to_death is specified, and entries for living patients where
# days_to_last_follow_up is specified
arrayDeathDataAreClean = np.bitwise_and((dfClinDataOut['vital_status'] == 'dead').values.astype(np.bool),
~(dfClinDataOut['days_to_death'] == '--').values.astype(np.bool))
arrayAliveDataAreClean = np.bitwise_and((dfClinDataOut['vital_status'] == 'alive').values.astype(np.bool),
~(dfClinDataOut['days_to_last_follow_up'] == '--').values.astype(np.bool))
# create a single vector of survival times which merges days to death/days to last follow up as required
arraySurvivalTimes = np.nan*np.ones(len(arrayPatientIsDead), dtype=np.float)
for iRow in range(len(arrayPatientIsDead)):
if arrayDeathDataAreClean[iRow]:
arraySurvivalTimes[iRow] = np.float(dfClinDataOut['days_to_death'].iloc[iRow])
elif arrayAliveDataAreClean[iRow]:
arraySurvivalTimes[iRow] = np.float(dfClinDataOut['days_to_last_follow_up'].iloc[iRow])
# output within the clinical data dataframe with survival time converted to months
dfClinDataOut['death_event'] = arrayPatientIsDead
dfClinDataOut.drop(labels=['vital_status', 'days_to_death', 'days_to_last_follow_up'],
axis=1,
inplace=True)
dfClinDataOut['surv_time'] = pd.Series(arraySurvivalTimes/30.5, index=dfClinDataOut.index.tolist())
dfClinDataOut.rename(columns={'age_at_diagnosis':'Age'},
inplace=True)
# # # # # # # # # # # # # # # # # # # # # # # # #
# Process molecular (RNA-seq) data and perform gene set scoring
arrayRSEMData = dfRSEMData[listSamples].values.astype(np.float)
arrayFlatCleanData = np.ravel(np.nan_to_num(arrayRSEMData))
numMinNonZeroVal = np.min(arrayFlatCleanData[arrayFlatCleanData > 0])
dfRSEMOut = pd.DataFrame(data=np.log10(arrayRSEMData + numMinNonZeroVal),
index=listTCGAGenes,
columns=listSamples)
dfRSEMOut = dfRSEMOut.transpose()
# Extract the T cell signature and identify genes overlapping with the TCGA data
dictTCellSig = GeneSetScoring.CuratedList.t_cells_in_tumour()
listTCellUpGenesInTCGA = list(set(dictTCellSig['T cells']['UpGenes']).intersection(setTCGAGenes))
# Extract the NK cell signature and identify genes overlapping with the TCGA data
dfNKSigCuration = pd.read_table(os.path.join(Plot.strOutputFolder, 'NK_genes_curated.tsv'),
sep='\t', header=0, index_col=0)
# Specifically select the genes which have passed our filtering criteria (Fig. S2 of the manuscript)
listLocalNKSigGenes = dfNKSigCuration[dfNKSigCuration['CursonsGuimaraes_sigGene']==True].index.tolist()
listNKUpGenesInTCGA = list(set(listLocalNKSigGenes).intersection(setTCGAGenes))
# Extract the Foroutan TGF-B EMT signature and identify genes overlapping with the TCGA data
dictTGFBEMTScore = GeneSetScoring.ExtractList.foroutan2016_tgfb_mes_score()
listTGFBEMTUp = list(set(dictTGFBEMTScore['Up']).intersection(setTCGAGenes))
listTGFBEMTDn = list(set(dictTGFBEMTScore['Down']).intersection(setTCGAGenes))
# Extract the Tan Epithelial & Mesenchymal signatures and identify genes overlapping with the TCGA data
dictTanEMTSigs = GeneSetScoring.ExtractList.tan2012_tumour_genes()
listEpiGenes = list(set(dictTanEMTSigs['epi_genes']).intersection(setTCGAGenes))
listMesGenes = list(set(dictTanEMTSigs['mes_genes']).intersection(setTCGAGenes))
# For Fig. S9 we compare signatures across the TCGA and LM-MEL data sets; to facilitate this we must first
# find the set of consistent genes
# --> extract the LM-MEL data and create a set of genes
dfLMMEL = PreProc.lm_mel_data()
setLMMELGenes = set(dfLMMEL.columns.tolist())
listTCGAImmuneGenes = dictTCGAClassifications['listGenesToScore']
# identify the intersection of the LM-MEL gene list with all other genes
listTCGAGenesVsLMMEL = list(setTCGAGenes.intersection(setLMMELGenes))
listEpiGenesVsLMMEL = list(set(listEpiGenes).intersection(setLMMELGenes))
listMesGenesVsLMMEL = list(set(listMesGenes).intersection(setLMMELGenes))
listTGFBEMTUpVsLMMEL = list(set(listTGFBEMTUp).intersection(setLMMELGenes))
listTGFBEMTDnVsLMMEL = list(set(listTGFBEMTDn).intersection(setLMMELGenes))
# Create a set of arrays for the output data;
# NB: to avoid a number of pandas allocation warnings this is done as arrays which are later loaded into the
# output dataframe
arrayBottcherNKScore = np.zeros(numTotSamples,
dtype=np.float)
arrayBottcherDCScore = np.zeros(numTotSamples,
dtype=np.float)
arrayTCellScore = np.zeros(numTotSamples,
dtype=np.float)
arrayImmuneScore = np.zeros(numTotSamples,
dtype=np.float)
arrayNKScore = np.zeros(numTotSamples,
dtype=np.float)
arrayEpiScore = np.zeros(numTotSamples,
dtype=np.float)
arrayMesScore = np.zeros(numTotSamples,
dtype=np.float)
arrayTGFBEMTScore = np.zeros(numTotSamples,
dtype=np.float)
arrayEpiScoreVsLMMEL = np.zeros(numTotSamples,
dtype=np.float)
arrayMesScoreVsLMMEL = np.zeros(numTotSamples,
dtype=np.float)
arrayTGFBEMTScoreVsLMMEL = np.zeros(numTotSamples,
dtype=np.float)
# step through each sample and perform scoring for the appropriate gene sets
print('Scoring TCGA samples for various gene sets/signatures')
for iSample in range(numTotSamples):
print('Sample ' + '{}'.format(iSample+1) + ' of ' + '{}'.format(numTotSamples))
arrayNKScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listNKUpGenesInTCGA,
flagApplyNorm=True)
arrayBottcherNKScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listBottcherNKGenes,
flagApplyNorm=True)
arrayBottcherDCScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listBottchercDC1Genes,
flagApplyNorm=True)
arrayTCellScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listTCellUpGenesInTCGA,
flagApplyNorm=True)
arrayImmuneScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listTCGAImmuneGenes,
flagApplyNorm=True)
arrayEpiScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listEpiGenes,
flagApplyNorm=True)
arrayMesScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listMesGenes,
flagApplyNorm=True)
arrayTGFBEMTScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenes,
arrayTranscriptAbundance=dfRSEMOut.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listTGFBEMTUp,
listDownGenesToScore=listTGFBEMTDn,
flagApplyNorm=True)
arrayEpiScoreVsLMMEL[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenesVsLMMEL,
arrayTranscriptAbundance=dfRSEMOut[listTCGAGenesVsLMMEL].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listEpiGenesVsLMMEL,
flagApplyNorm=True)
arrayMesScoreVsLMMEL[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenesVsLMMEL,
arrayTranscriptAbundance=dfRSEMOut[listTCGAGenesVsLMMEL].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listMesGenesVsLMMEL,
flagApplyNorm=True)
arrayTGFBEMTScoreVsLMMEL[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listTCGAGenesVsLMMEL,
arrayTranscriptAbundance=dfRSEMOut[listTCGAGenesVsLMMEL].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listTGFBEMTUpVsLMMEL,
listDownGenesToScore=listTGFBEMTDnVsLMMEL,
flagApplyNorm=True)
# Load the numpy arrays into the appropriate columns within the output dataframe
dfRSEMOut['NK Score'] = arrayNKScore
dfRSEMOut['NK-Cytokine Score'] = arrayNKScore
dfRSEMOut['NK-Cytotoxic Score'] = arrayNKScore
dfRSEMOut['Bottcher NK Score'] = arrayBottcherNKScore
dfRSEMOut['Bottcher cDC1 Score'] = arrayBottcherDCScore
dfRSEMOut['T cell Score'] = arrayTCellScore
dfRSEMOut['TCGA Immune Score'] = arrayImmuneScore
dfRSEMOut['TGF-B EMT Score'] = arrayTGFBEMTScore
dfRSEMOut['Epithelial Score'] = arrayEpiScore
dfRSEMOut['Mesenchymal Score'] = arrayMesScore
dfRSEMOut['TGF-B EMT Score (vs. LM-MEL)'] = arrayTGFBEMTScoreVsLMMEL
dfRSEMOut['Epithelial Score (vs. LM-MEL)'] = arrayEpiScoreVsLMMEL
dfRSEMOut['Mesenchymal Score (vs. LM-MEL)'] = arrayMesScoreVsLMMEL
# join the RNA & gene set score data to the clinical data
dfMerged = dfRSEMOut.join(dfClinDataOut)
# save the resulting dataframe for re-loading
dfMerged.to_pickle(strMergedFileName)
else:
# load the pre-processed dataframe
dfMerged = pd.read_pickle(strMergedFileName)
# extract required information
dfRSEMData = PreProc.tcga_skcm_rna_data()
listTCGAGenes = dfRSEMData.index.tolist()
listClinDataOut = ['gender',
'age_at_diagnosis',
'death_event',
'surv_time']
# return a dictionary with the required information
return {'df':dfMerged,
'listGenes':listTCGAGenes,
'listClin':listClinDataOut}
def tcga_skcm_classifications(flagResult=False,
strGeneListFolder=os.getcwd()):
"""Load supplementary data tables from the original TCGA SKCM manuscript including the immune gene signature and
classifications of immune high/immune low samples"""
strTCGAGeneListFileName = 'TCGA_SKCM_SuppTable4.xlsx'
strTCGASampleClassificationFileName = 'TCGA_SKCM_SuppTable1.xlsx'
# load the TCGA data as a merged pandas dataframe
dictTCGASKCM = PreProc.tcga_skcm_data()
listTCGAGenes = dictTCGASKCM['listGenes']
# load a dictionary which maps between HGNC synonyms using the downloadable HGNC database
dictHGNCSynonyms = HGNCFunctions.Mapping.create_synonym_dict()
# unfortunately I need to hard code a couple of synonyms which aren't being picked up from the database export
dictHGNCSynonyms['TNFRSF14B'] = 'TNFRSF13B'
# there are several synonyms for CT12.1: XAGE1A-XAGE1E; XAGE1D is the only one present within the TCGA SKCM data
dictHGNCSynonyms['CT12.1'] = 'XAGE1D'
# it seems that FDCSP is the accepted HGNC symbol now, but this is absent in the TCGA data, whereas a previous
# synonym C4orf7 is present
dictHGNCSynonyms['FDCSP'] = 'C4orf7'
# similar CT55 is the HGNC symbol but CXorf48 is present
dictHGNCSynonyms['CT55'] = 'CXorf48'
# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #
# SPLIT SAMPLES ON IMMUNE SCORE AND EXAMINE SURVIVAL
# there are a number of published immune signatures associated with survival in melanoma patients, here we use
# the genes which classify the 'immune' genes within the original TCGA SKCM paper:
# The Cancer Genome Atlas Network (2015). Genomic Classification of Cutaneous Melanoma. Cell, 161: 1681-1696
# doi: 10.1016/j.cell.2015.05.044
dfTCGASampleClasses = pd.read_excel(os.path.join(strGeneListFolder, strTCGASampleClassificationFileName),
sheet_name='Supplemental Table S1D', header=1,
index_col=None)
listTCGAClassifiedImmune = dfTCGASampleClasses['Name'][dfTCGASampleClasses['RNASEQ-CLUSTER_CONSENHIER']=='immune'].tolist()
listOrigTCGASamples = dfTCGASampleClasses['Name'].tolist()
dfTCGAGeneLists = pd.read_excel(os.path.join(strGeneListFolder, strTCGAGeneListFileName),
sheet_name='Supplemental Table S4A', header=1,
index_col=None)
listClusterLabels = dfTCGAGeneLists['RNA Cluster'].tolist()
# the original Excel table used merged rows which pandas doesn't like; replace NaNs with an appropriate 'fill down'
# --> begin by finding all of the rows where there are NaNs
arrayNaNClusterLabel = dfTCGAGeneLists['RNA Cluster'].isnull()
# and extracting the indices which are not NaN
arrayNotNaNClusterLabelIndices = np.where(dfTCGAGeneLists['RNA Cluster'].notnull())[0]
# step through each row with a NaN cluster label
for iRow in np.where(arrayNaNClusterLabel)[0]:
# find the lowest non-NaN row (maximum index) which is above this
numLabelIndex = arrayNotNaNClusterLabelIndices[np.max(np.where(iRow > arrayNotNaNClusterLabelIndices)[0])]
# extract the string corresponding to this row
strLabel = listClusterLabels[numLabelIndex]
# and fill as necessary
dfTCGAGeneLists['RNA Cluster'].iloc[iRow] = strLabel
# identify all rows corresponding to the 'Immune' RNA cluster
arrayRowsOfInt = np.where(dfTCGAGeneLists['RNA Cluster'] == 'Immune')[0]
listImmuneGenesClean = []
for iRow in arrayRowsOfInt:
strGenes = dfTCGAGeneLists['Individual Genes'].iloc[iRow]
# check that the entry is not NaN (one of the rows contains NaN..?!?)
if strGenes == strGenes:
# there are a few random semi-colons in place of commas as separators..
strGenes = strGenes.replace(';', ',')
# split on the commas
arrayGenes = strGenes.split(', ')
for strGene in arrayGenes:
if not '/' in strGene:
if len(strGene) > 0:
# ensure that the gene name is fully upper case; there is a 'CD1c' instead of 'CD1C'
listImmuneGenesClean.append(strGene.upper())
else:
# '79A/B' is listed in the B-cells row; I think it's a fair assumption that this is meant to be
# 'CD79A/B', i.e. components of the B-cell receptor
if strGene == '79A/B':
strGene = 'CD79A/B'
# a slightly different text pattern is used for showing synonyms of TBX21..
if strGene == 'TBX21/TBET':
strGene = 'TBX21(TBET)'
arraySplitGenes = strGene.split('/')
strFirstGene = arraySplitGenes[0]
if strFirstGene[0:2] == 'CD':
# I'm going to work on the assumption that all prefixes end at the last number
arrayIsNumeric = np.zeros(len(strFirstGene),
dtype=np.bool)
for iLetter in range(len(strFirstGene)):
arrayIsNumeric[iLetter] = strFirstGene[iLetter].isnumeric()
numLastNumberPos = np.max(np.where(arrayIsNumeric)[0])
strPrefix = strFirstGene[0:(numLastNumberPos+1)]
elif np.any([strFirstGene[0:2] == 'CT',
strFirstGene[0:3] == 'CCL',
strFirstGene[0:3] == 'XCL',
strFirstGene[0:3] == 'CCR',
strFirstGene[0:4] == 'CXCL',
strFirstGene[0:4] == 'CXCR']):
# I'm going to work on the assumption that all prefixes end one prior to the first number
arrayIsNumeric = np.zeros(len(strFirstGene),
dtype=np.bool)
for iLetter in range(len(strFirstGene)):
arrayIsNumeric[iLetter] = strFirstGene[iLetter].isnumeric()
numLastNumberPos = np.min(np.where(arrayIsNumeric)[0])
strPrefix = strFirstGene[0:(numLastNumberPos)]
elif strFirstGene[0:3] == 'GZM':
# I'm just going to hard code this one..
strPrefix = 'GZM'
elif strFirstGene[0:4] == 'MAGE':
# I'm just going to hard code this one..
strPrefix = 'MAGE'
listImmuneGenesClean.append(strFirstGene)
for iSplit in range(1, len(arraySplitGenes)):
strCleanOut = strPrefix + arraySplitGenes[iSplit]
listImmuneGenesClean.append(strCleanOut)
arrayHasSynonymIndices = np.where(['(' in strGene for strGene in listImmuneGenesClean])[0]
for iRow in arrayHasSynonymIndices:
strGene = listImmuneGenesClean[iRow]
strGeneClean = strGene.partition('(')[0]
listImmuneGenesClean[iRow] = strGeneClean
# perform gene set scoring over this set of immune genes
# NB: in 'Genomic Classification of Cutaneous Melanoma' from which this gene list is derived, the authors state
# "A significant number of genes overexpressed in this subclass were associated with immune cell subsets
# (T cells, B cells and NK cells), immune signaling molecules, co-stimulatory and co-inhibitory immune
# checkpoint proteins, cytokines, chemokine, and corresponding receptors (Table S4A-S4B)."
# Accordingly, this gene set is simply being used as an 'expected up-regulated' gene list and I have not
# attempted to further refine this gene list
listImmuneGenesMatched = []
for strGene in listImmuneGenesClean:
if strGene in listTCGAGenes:
listImmuneGenesMatched.append(strGene)
else:
print('warning: ' + strGene + ' cannot be found in the TCGA SKCM mRNA abundance data')
if strGene in dictHGNCSynonyms.keys():
strAlias = dictHGNCSynonyms[strGene]
print('\t\t\tmapping via ' + strAlias)
listImmuneGenesMatched.append(strAlias)
elif strGene=='DC247':
print('\t\t\tmanually mapping to CD247, assuming this is typographical error;')
print('\t\t\tCD247 is also known as TCRzeta')
listImmuneGenesMatched.append('CD247')
else:
print('\t\t\tcannot map to alias, please check for typographical errors')
print('\tWARNING: ' + strGene + ' is being discarded from the analysis')
# convert to a unique list by creating a set (I know MS4A1 is present twice as 'CD20' was listed in the gene list
# together with MS4A1)
listGenesToScore = list(set(listImmuneGenesMatched))
return {'listGenesToScore': listGenesToScore,
'listImmuneGenesClean': listImmuneGenesClean,
'listTCGAClassifiedImmune': listTCGAClassifiedImmune,
'listOrigTCGASamples': listOrigTCGASamples}
def tcga_skcm_met_sites(flagResult=False,
flagProduceOutputTable=False):
"""Load detailed metastatic tumour sites from the TCGA SKCM data"""
# load the TCGA data as a merged pandas dataframe
dictTCGASKCM = PreProc.tcga_skcm_data(flagPerformExtraction=False)
dfTCGA = dictTCGASKCM['df']
listTCGAGenes = dictTCGASKCM['listGenes']
numTranscripts = len(listTCGAGenes)
dictPatGroups = PreProc.split_tcga_met_vs_pri()
listMetOnlyPatientsWithAge = dictPatGroups['MetOnlyPatWithAge']
# append the '-06' suffix indicative of metastatic samples
listMetOnlySamplesWithAge = [strPat + '-06' for strPat in listMetOnlyPatientsWithAge]
dfTCGAMets = dfTCGA.loc[listMetOnlySamplesWithAge]
listMetSites = dfTCGAMets['site_of_resection_or_biopsy'].tolist()
for iPatient in range(len(listMetSites)):
strMetSite = listMetSites[iPatient]
if strMetSite in PreProc.dictMetSiteGroupings.keys():
listMetSites[iPatient] = PreProc.dictMetSiteGroupings[strMetSite]
# convert to a set to get a unique list
listUniqueMetSites = list(set(listMetSites))
# Output the site groupings in a format that can easily be converted to a table for the final manuscript
listUniqueInputMetSites = dfTCGAMets['site_of_resection_or_biopsy'].unique().tolist()
listGroupedMetSiteForQuant = []
listOrigMetSiteForQuant = []
listNumAtOrigMetSite = []
for strMetSite in listUniqueInputMetSites:
numSamplesInOrigMetSite = np.sum([strMetSite == strObsSite
for strObsSite in dfTCGAMets['site_of_resection_or_biopsy'].tolist()])
listNumAtOrigMetSite.append(numSamplesInOrigMetSite)
listOrigMetSiteForQuant.append(strMetSite)
if strMetSite in PreProc.dictMetSiteGroupings.keys():
listGroupedMetSiteForQuant.append(PreProc.dictMetSiteGroupings[strMetSite])
else:
listGroupedMetSiteForQuant.append(strMetSite)
if flagProduceOutputTable:
with open(os.path.join(Plot.strOutputFolder, 'MetSiteGroupings.tsv'), 'w+') as handFile:
for strGroupedSite in listUniqueMetSites:
arrayRowIsForGroupedSite = np.array([strGroupedSite == strTestSite
for strTestSite in listGroupedMetSiteForQuant],
dtype=np.bool)
arrayRowsForGroupedSite = np.where(arrayRowIsForGroupedSite)[0]
strForSubsets = ''
numTotalForSubset = 0
for iRow in range(len(arrayRowsForGroupedSite)):
numRow = arrayRowsForGroupedSite[iRow]
strOrigSite = listOrigMetSiteForQuant[numRow]
numInOrigSite = listNumAtOrigMetSite[numRow]
numTotalForSubset = numTotalForSubset + numInOrigSite
strForOrigSite = '"' + strOrigSite + '" (n=' + '{}'.format(numInOrigSite) + ')'
if iRow == 0:
strForSubsets = strForOrigSite
else:
strForSubsets = strForSubsets + ', ' + strForOrigSite
print(strGroupedSite + ' (n=' + '{}'.format(numTotalForSubset) + ')\t' + strForSubsets, file=handFile)
# As we are examining metastatic melanoma we will use the 'Lymph node, NOS' corresponding to unspecified lymph
# nodes for the baseline hazard --> remove this from listUniqueMetSites which is used to generate the dataframe
# used in fitting the Cox proportional hazards model
listUniqueMetSites.remove('Lymph node, NOS')
# create a binary table which flags whether a tumor corresponds to a specific metastatic site
arrayMetSiteAnnot = np.zeros((np.shape(dfTCGAMets)[0],len(listUniqueMetSites)),
dtype=np.float)
for iMetSite in range(len(listUniqueMetSites)):
strMetSite = listUniqueMetSites[iMetSite]
arrayPatientMetIsAtSite = [strPatientSite == strMetSite
for strPatientSite in listMetSites]
arrayMetSiteAnnot[np.where(arrayPatientMetIsAtSite), iMetSite] = 1.0
dfMetSites = pd.DataFrame(data=arrayMetSiteAnnot,
columns=listUniqueMetSites,
index=dfTCGAMets.index.tolist())
return dfMetSites
def lm_mel_data(flagResult=False,
flagPerformExtraction=False,
strTempFileName='proc_LMMEL.pickle'):
"""Process the LM-MEL microarray data and return a dataframe for later indexing"""
# specify some thresholds used for pre-processing of the LM-MEL data
numLMMelDynValueThresh = 4.5
numFractReqAboveThresh = 0.15
if not os.path.exists(strTempFileName):
flagPerformExtraction = True
if flagPerformExtraction:
# load the LM-MEL mRNA abundance data
dfLMMELIn = LMMelTools.LMMelData.mrna_abundance()
# identify the cell lines
listLMMELIndex = dfLMMELIn.index.tolist()
listLMMELLines = [strIndex for strIndex in listLMMELIndex if strIndex[0:len('LM-MEL')] == 'LM-MEL']
arraySampleRows = np.where([strRow in listLMMELLines for strRow in listLMMELIndex])[0]
numCellLines = len(arraySampleRows)
# identify the genes
listLMMELGenes = dfLMMELIn.loc['Symbol'].tolist()
# retain only genes which have a good dynamic range (range of abundances), and genes where expression exceeds a
# specified threshold within a certain subset of cells (numLMMelDynValueThresh & numFractReqAboveThresh,
# specified above)
print('Cleaning LM-MEL mRNA transcript abundance data.. this may take some time')
arrayNumLinesHaveGeneAboveThresh = \
np.sum(dfLMMELIn.loc[listLMMELLines].values.astype(np.float) > numLMMelDynValueThresh,
axis=0)
arrayGeneHasGoodDynRange = arrayNumLinesHaveGeneAboveThresh >= numFractReqAboveThresh*len(listLMMELLines)
arrayGeneIndicesGoodDynRange = np.where(arrayGeneHasGoodDynRange)[0]
# drop all columns which have low quality probes with a poor signal
listUniqueOutputGenes = dfLMMELIn.loc['Symbol', arrayGeneIndicesGoodDynRange].unique().tolist()
listUniqueOutputGenes.remove(np.nan)
setUniqueOutputGenes = set(listUniqueOutputGenes)
# produce an output dataframe
dfLMMEL = pd.DataFrame(data=np.zeros((len(listLMMELLines),len(listUniqueOutputGenes)),
dtype=np.float),
index=listLMMELLines,
columns=listUniqueOutputGenes)
# In Fig. S9 the TCGA and LM-MEL data are compared through gene set scoring thus a consistent set of shared genes
# must first be identified
dictTCGASKCM = PreProc.tcga_skcm_data(flagPerformExtraction=False)
listTCGAGenes = dictTCGASKCM['listGenes']
setTCGAGenes = set(listTCGAGenes)
listUniqueOutputGenesVsTCGA = list(setUniqueOutputGenes.intersection(setTCGAGenes))
# As there is some multimapping in the LM-MEL microarray data (multiple probes -> one gene), take the median value
# across any probes that passed earlier filtering
for strGene in listUniqueOutputGenes:
arrayColIndicesForGene = \
np.where(
np.bitwise_and([strGene == strGeneToCheck for strGeneToCheck in listLMMELGenes],
arrayGeneHasGoodDynRange))[0]
dfLMMEL[strGene] =\
np.median(dfLMMELIn.iloc[arraySampleRows,arrayColIndicesForGene].values.astype(np.float), axis=1)
# Extract the Foroutan TGF-B EMT gene signature
dictTGFBEMTScore = GeneSetScoring.ExtractList.foroutan2016_tgfb_mes_score()
listTGFBEMTUp = list(set(dictTGFBEMTScore['Up']).intersection(set(listUniqueOutputGenes)))
listTGFBEMTDn = list(set(dictTGFBEMTScore['Down']).intersection(set(listUniqueOutputGenes)))
listTGFBEMTUpVsTCGA = list(set(listTGFBEMTUp).intersection(setTCGAGenes))
listTGFBEMTDnVsTCGA = list(set(listTGFBEMTDn).intersection(setTCGAGenes))
# Extract the Tan Epithelial & Mesenchymal gene signatures
dictTanEMTSigs = GeneSetScoring.ExtractList.tan2012_cell_line_genes()
listEpiGenes = list(set(dictTanEMTSigs['epi_genes']).intersection(set(listUniqueOutputGenes)))
listMesGenes = list(set(dictTanEMTSigs['mes_genes']).intersection(set(listUniqueOutputGenes)))
listEpiGenesVsTCGA = list(set(listEpiGenes).intersection(setTCGAGenes))
listMesGenesVsTCGA = list(set(listMesGenes).intersection(setTCGAGenes))
# create arrays for the initial scoring to avoid a number of warnings from pandas
arrayEpiScore = np.zeros(numCellLines,
dtype=np.float)
arrayMesScore = np.zeros(numCellLines,
dtype=np.float)
arrayTGFBEMTScore = np.zeros(numCellLines,
dtype=np.float)
arrayEpiScoreVsTCGA = np.zeros(numCellLines,
dtype=np.float)
arrayMesScoreVsTCGA = np.zeros(numCellLines,
dtype=np.float)
arrayTGFBEMTScoreVsTCGA = np.zeros(numCellLines,
dtype=np.float)
# step through each cell line and score for the required gene sets
print('Scoring TCGA samples for various gene sets/signatures')
for iSample in range(numCellLines):
print('Sample ' + '{}'.format(iSample+1) + ' of ' + '{}'.format(numCellLines))
arrayEpiScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenes,
arrayTranscriptAbundance=dfLMMEL.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listEpiGenes,
flagApplyNorm=True)
arrayMesScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenes,
arrayTranscriptAbundance=dfLMMEL.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listMesGenes,
flagApplyNorm=True)
arrayTGFBEMTScore[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenes,
arrayTranscriptAbundance=dfLMMEL.iloc[iSample, :].values.astype(np.float),
listUpGenesToScore=listTGFBEMTUp,
listDownGenesToScore=listTGFBEMTDn,
flagApplyNorm=True)
arrayEpiScoreVsTCGA[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenesVsTCGA,
arrayTranscriptAbundance=dfLMMEL[listUniqueOutputGenesVsTCGA].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listEpiGenesVsTCGA,
flagApplyNorm=True)
arrayMesScoreVsTCGA[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenesVsTCGA,
arrayTranscriptAbundance=dfLMMEL[listUniqueOutputGenesVsTCGA].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listMesGenesVsTCGA,
flagApplyNorm=True)
arrayTGFBEMTScoreVsTCGA[iSample] = GeneSetScoring.FromInput.single_sample_rank_score(
listAllGenes=listUniqueOutputGenesVsTCGA,
arrayTranscriptAbundance=dfLMMEL[listUniqueOutputGenesVsTCGA].iloc[iSample].values.astype(np.float),
listUpGenesToScore=listTGFBEMTUpVsTCGA,
listDownGenesToScore=listTGFBEMTDnVsTCGA,
flagApplyNorm=True)
# map gene set scores to the appropriate columns within the output dataframe
dfLMMEL['TGF-B EMT Score'] = arrayTGFBEMTScore
dfLMMEL['Epithelial Score'] = arrayEpiScore
dfLMMEL['Mesenchymal Score'] = arrayMesScore
dfLMMEL['TGF-B EMT Score (vs. TCGA)'] = arrayTGFBEMTScoreVsTCGA
dfLMMEL['Epithelial Score (vs. TCGA)'] = arrayEpiScoreVsTCGA
dfLMMEL['Mesenchymal Score (vs. TCGA)'] = arrayMesScoreVsTCGA
# save as a pickle for later re-use
dfLMMEL.to_pickle(strTempFileName)
else:
# load the pre-processed pickle
dfLMMEL = pd.read_pickle(strTempFileName)
return dfLMMEL
def gse60424_data(flagResult=False,
strDataLoc=os.getcwd(),
strDataFile='bldCells_TPM.tsv',
strMetaDataFile='SraRunTable.txt'):
"""Process the Linsley et al data and return a dataframe for later indexing."""
# Linsley PS, et al. (2014). Copy number loss of the interferon gene cluster in melanomas is
# linked to reduced T cell infiltrate and poor patient prognosis. PLoS One. 9(10):e109760.
# DOI: 10.1371/journal.pone.0109760
# A TPM normalised version of the data from GSE60424 (Linsley et al) was prepared by M Foroutan (see corresponding R data)
# --> load the gene expression data
dfData = pd.read_table(os.path.join(strDataLoc, strDataFile), sep='\t', header=0, index_col=0)
listGenesEntrez = dfData.index.tolist()
listSamples = dfData.columns.tolist()
# load a sample metadata table which maps sample IDs to labels
dfMetaData = pd.read_table(os.path.join(strDataLoc, strMetaDataFile), sep='\t', header=0, index_col=None)
# load a dictionary for mapping HGNC symbols to Entrez gene IDs and invert it
dictHGNZToEntrez = BiomartFunctions.IdentMappers.defineHGNCSymbolToEntrezIDDict()
dictEntrezToHGNC = dict(zip(dictHGNZToEntrez.values(),dictHGNZToEntrez.keys()))
# step through all genes in the data and convert to HGNC symbols where available (if absent retain the Entrez number as
# a string with the 'Entrez:' prefix)
listGenesHGNC = []
for numEntrez in listGenesEntrez:
strHGNC = 'Entrez:' + '{}'.format(numEntrez)
if numEntrez in dictEntrezToHGNC.keys():
if dictEntrezToHGNC[numEntrez] == dictEntrezToHGNC[numEntrez]:
strHGNC = dictEntrezToHGNC[numEntrez]
listGenesHGNC.append(strHGNC)
# map sample cell types from the metadata table and use this to create a dictionary for later mapping
listSamplesCellType = [dfMetaData['celltype_s'][dfMetaData['Run_s'] == strSample].values[0]
for strSample in listSamples]
dictSampleIDToType = dict(zip(listSamples, listSamplesCellType))
# create an output dataframe
dfOut=pd.DataFrame(data=dfData.values,
index=listGenesHGNC,
columns=listSamples)
# return the dataframe together with a dictionary for mapping samples
return dfOut, dictSampleIDToType
def gse24759_data(flagResult=False,
strDataLoc=os.getcwd(),
strDataFile='GSE24759_series_matrix.txt',
strProbeMapFile='GPL4685-15513.txt',
flagPerformExtraction=False,
strProcDataFilename='GSE24759_proc.pickle',
strProcMetaDataFilename='GSE24759_metadata_proc.pickle'):
"""Process the Novershtern et al data and return a dataframe for later indexing."""
# Novershtern N, et al. (2011). Densely interconnected transcriptional circuits control cell states
# in human hematopoiesis. Cell. 144(2): 296-309.
# DOI: 10.1016/j.cell.2011.01.004
if not np.bitwise_and(os.path.exists(os.path.join(strDataLoc, strProcDataFilename)),
os.path.exists(os.path.join(strDataLoc, strProcMetaDataFilename))):
flagPerformExtraction = True
if flagPerformExtraction:
# extract the first 56 lines from the metadata file; due to the formatting this file has issues
# when trying to parse with pandas
listMetaData = []
with open(os.path.join(strDataLoc, strDataFile), 'r+') as handFile:
counter = 0
for line in handFile:
listMetaData.append(line)
counter += 1
if counter == 56: break
# step through the resulting list and identify specific rows
numSampleIDRow = np.where(['!Series_sample_id' in strRow for strRow in listMetaData])[0][0]
numSampleTitleRow = np.where(['!Sample_title' in strRow for strRow in listMetaData])[0][0]
numSampleSourceRow = np.where(['!Sample_source_name' in strRow for strRow in listMetaData])[0][0]
# Process the row containing sample IDs and produce a new list (listSampleIDs)
strSampleIDsIn = listMetaData[numSampleIDRow]
strIDsClean = strSampleIDsIn.split('!Series_sample_id\t"')[1]
strIDsCleaner = strIDsClean.split(' "\n')[0]
listSampleIDs = strIDsCleaner.split(' ')
# Process the row containing sample titles and produce a new list (listSampleTitles)
strSampleTitlesIn = listMetaData[numSampleTitleRow]
strTitlesClean = strSampleTitlesIn.split('!Sample_title\t"')[1]
strTitlesCleaner = strTitlesClean.split('"\n')[0]
listSampleTitles = strTitlesCleaner.split('"\t"')
# Process the row containing sample sources and produce a new list (listSampleSources)
strSampleSourcesIn = listMetaData[numSampleSourceRow]
strSourcesClean = strSampleSourcesIn.split('!Sample_source_name_ch1\t"')[1]
strSourcesCleaner = strSourcesClean.split('"\n')[0]
listSampleSources = strSourcesCleaner.split('"\t"')
# read in the expression/microarray data
dfData = pd.read_table(os.path.join(strDataLoc, strDataFile), sep='\t', header=0, index_col=0,
comment='!')
listProbes = dfData.index.tolist()
# create an output dataframe for the metadata
dfMetaData = pd.DataFrame(data=[listSampleTitles,listSampleSources],
index=['Title','Source'],
columns=listSampleIDs)
# read in the table which maps probes to genes
dfProbeMap = pd.read_table(os.path.join(strDataLoc, strProbeMapFile),
sep='\t', header=0, index_col=0,
comment='#')
# map probes to gene symbols if possible
listProbesToGenes = []
for strProbe in listProbes: