/
cohort.py
1349 lines (1027 loc) · 33 KB
/
cohort.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
from .utils import *
import os
import numpy as np
import pandas as pd
import scipy.stats as sc
from sklearn.preprocessing import StandardScaler
import itertools as it
class Cohort(object):
"""
Patient cohort object for patient proteomics data.
Dataframes, variables, and functions facilitating the processing, analysis, and integration of the cohort data.
Parameters
----------
cohort: str
name of the patient cohort
file_dir: str
directory where replicate dataframe and
sample group membership dataframe file names are located
replicates_file: str
name of the replicates dataframe file
A proteins x B replicates
comma (*.csv) or tab (*.tsv) delimited
replicate = "SampleName" + "_Rep[0-9]"
sample_groups_file: str
name of the sample group file
comma (*.csv) or tab (*.tsv) delimited
N groups x M samples
sample = "SampleName"
data_dir: str
directory where extra data files are located
uniprot_file: str
name of the uniprot database flat file located in data_dir
Examples
--------
>>>c = cohorts.Cohort(cohort='cohort_name',
file_dir="path/to/files/"
replicates_file="file_name",
sample_groups_file="sample_groups_file_name",
data_dir="path/to/data/dir/",
uniprot_file="uniprot_flat_file"
)
>>>c.set_replicates_hq()
>>>c.set_trans_replicates_hq()
>>>c.set_samples_hq()
>>>c.set_trans_samples_hq()
"""
tests = [
( "t-test",sc.ttest_ind ),
("Wilcoxon_RankSum_test",sc.ranksums)
]
def __init__(self,cohort='cumc',
replicates_file=None,sample_groups_file=None,
uniprot_file=None,
file_dir="",data_dir="../../data/"):
self.cwd = os.getcwd()
self.data_dir = data_dir
self.file_dir = file_dir
self.cohort = cohort
self.replicates_file = replicates_file
self.sample_groups_file = sample_groups_file
self.uniprot_file = uniprot_file
self.raw_samples = None
self.raw_replicates = None
self.replicates_hq = None
self.trans_replicates_hq = None
self.samples_hq = None
self.trans_samples_hq = None
self.sample_replicate_dictionary = None
self.samples = None
self.replicates = None
self.proteins = None
self.replicate_groups = None
self.sample_groups = None
self.tidy_replicate_groups = None
self.tidy_sample_groups = None
self.groups = None
self.ref = None
self.treat = None
self.set_replicates_file()
self.set_sample_groups_file()
self.set_raw_replicates()
self.set_replicates()
self.set_sample_replicate_dictionary()
self.set_samples()
self.set_sample_groups()
self.set_replicate_groups()
self.set_raw_samples()
self.set_tidy_sample_groups()
self.set_tidy_replicate_groups()
self.set_proteins()
self.set_groups()
self.set_ref()
self.set_treat()
#extra parameters/data objects that can be
#attributed to an object instance
self.data = {}
self.params = {}
#SET FUNCTIONS
def set_replicates_file(self):
"""
Setting the replicates file string.
Combination of the file directory string and the replicates file string
A csv file is needed!
Parameters
----------
None
"""
self.replicates_file = str(self.file_dir) + str(self.replicates_file)
def set_sample_groups_file(self):
"""
Setting the replicate_groups string
Combination of the path string and the replicates file string
A csv file is needed!
Parameters
----------
None
"""
self.sample_groups_file = str(self.file_dir) + str(self.sample_groups_file)
def set_uniprot_file(self):
"""
Setting the path to the uniprot flat file
Parameters
----------
None
"""
self.uniprot_file = str(self.data_dir) + str(self.uniprot_file)
def set_raw_replicates(self):
"""
Setting raw replicate dataframe from files given to object
Parameters
----------
None
"""
#checking if tab separated (tsv) or comma separated (csv) format
splt = self.replicates_file.split(".")
format = splt[len(splt)-1][0]
if format is 'c':
self.raw_replicates = pd.read_csv(self.replicates_file,delimiter=",",index_col=0)
else:
self.raw_replicates = pd.read_csv(self.replicates_file,delimiter="\t",index_col=0)
def set_replicates(self):
"""
Setting replicate names
Depends on : raw_replicates
Parameters
----------
None
"""
self.replicates = self.raw_replicates.columns.tolist()
def set_sample_replicate_dictionary(self):
"""
Setting dictionary of samples (keys) to replicates (values)
Depends on : replicates
Parameters
----------
None
"""
#get replicates
replicates = self.replicates
#strip replicate indicator to get array of sample names for replicates
duplicate_samples = [y[0] for y in [x for x in np.chararray.split(replicates,"_")]]
#set previous to series for easy unique sample name retrieval
samples = pd.Series(duplicate_samples).unique()
#initialize dictionary
dictionary = {}
#loop through unique samples
for key in samples:
#get indice of replicates for sample
replicate_inds = pd.Series(duplicate_samples).isin([key])
#get replicates for sample
values = np.array(replicates)[replicate_inds.tolist()]
#set key:value pair (sample : replicates) in dictionary
dictionary[key] = values.tolist()
self.sample_replicate_dictionary = dictionary
def set_raw_samples(self,agg='mean'):
"""
Setting raw sample dataframe
Take statistic of replicates with particular sample membership
Depends on : raw_replicates and make_df_samples()
Parameters
----------
agg: {'mean','median', 'variance'}
statistic to apply to replicate values for sample membership
"""
df = self.raw_replicates.fillna(0)
self.raw_samples = self.make_df_samples(df,agg=agg)
def set_replicates_hq(self,
uniprot_annot=False,
annot_status='reviewed',
quant_least_reps_per_samps=False,
n_reps=1,
all_reps_quant=False,
threshold=88,
intrasamp_var=False,
higher=False):
"""
Setting proteins in raw dataframe to be reviewed by Uniprot
Depends on : raw_replicates, proteins_in_n_replicates_per_samples, proteins_quant_all_reps, proteins_with_uniprot_annot, proteins_by_intrasample_variability
Parameters
----------
uniprot_annot {True,False}
Subset proteins by annot=ation status in uniprot database
annot_status {'reviewed','unreviewed'}
Annotation status in uniprot
quant_least_reps_per_samps {True,False}
Subset proteins by the number of replicates quantified per sample
n_reps
Number of replicates quantified per sample. See above
all_reps_quant {True,False}
Subset proteins by only those quantified in every replicate per sample
intrasamp_var {True,False}
Subset proteins by the amount of replicate variance per sample
threshold
Quantile to subset variance from. See above
higher {True,False}
Indicates whether to subset by proteins with a high annotation score from Uniprot
"""
#get raw data
df = self.raw_replicates.fillna(0)
#subset to have proteins found in atleast sufficient_reps
#per sample for all samples
if quant_least_reps_per_samps:
prots = self.proteins_in_n_replicates_per_samples(df,n_reps=n_reps)
df = df.loc[prots]
#subset to have proteins found in atleast n_reps
#per sample for all samples
if all_reps_quant:
prots = self.proteins_quant_all_reps(df)
df = df.loc[prots]
#subset to have proteins with high annotation score
if uniprot_annot:
#set uniprot file if asked for, for protein filtering
self.set_uniprot_file()
prots = self.proteins_with_uniprot_annot(df,status=annot_status)
df = df.loc[prots]
# subset to have proteins with certain intrasample variability
if intrasamp_var:
prots = self.proteins_by_intrasample_variability(df,
higher=higher,
threshold=threshold)
df = df.loc[prots]
self.replicates_hq = df
def set_trans_replicates_hq(self,
trans='None',
add_small=False,
stat_thresh=False,
threshold=95,
higher=False,
statistic='variance'):
"""
Transforming hq values with different functions, by default log1p.
Depends on : replicates_hq, proteins_by_statistic_threshold
Parameters
----------
trans: numerical transformation. Default: scikitlearn's StandardScaler
Indicates how to transform the raw protein values
add_small
Add small value if any dataframe value is 0 - when log transforming
stat_threshold
Subsetting dataframe by a statistic threshold
threshold [0,100]
Quantile for statistic threshold
higher
Subset above or below statistic threshold
statistic {'mean','median','variance'}
Statistic to be applied
"""
#set hq dataframe; make sure there's no NaN values
df = self.replicates_hq
#instantiate/declare/set up Standard scaler model from
#scikitlearn on data
scaler = StandardScaler()
scaler.fit(df)
#list of name-function pairs
func = [('log1p', np.log1p),
('log2', np.log2),
('sklearn', scaler.transform),
('rank_normalize', rank_normalize),
('quantile_normalize', quantileNormalize),
('None', pd.DataFrame.copy)]
#get appropriate list index for function from trans string
m = [x for x in range(len(func)) if trans in func[x][0]][0]
#add small epsilon value to all protein values
if add_small:
eps = 0.0001
df = df.applymap(lambda x : x + eps)
#apply function from appropriate function list index
data = pd.DataFrame(func[m][1](df),
index=df.index,
columns=df.columns
)
#subset to have proteins that meet a certain statistical threshold
if stat_thresh:
prots = self.proteins_by_statistic_threshold(data,
statistic=statistic,
threshold=threshold,
higher=higher)
data = data.loc[prots]
self.trans_replicates_hq = data
def set_samples_hq(self,
agg='mean',
uniprot_annot=False,
annot_status='reviewed'):
"""
Setting sample dataframe from processed replicate dataframe
Depends on : trans_replicates_hq, make_df_samples
Parameters
----------
agg: {'mean','median', 'variance'}
statistic to apply to replicate values for sample membership
uniprot_annot {True,False}
Subset proteins by annot=ation status in uniprot database
annot_status {'reviewed','unreviewed'}
Annotation status in uniprot
"""
#get processed replicates
df = self.trans_replicates_hq
#subset to have proteins with high annotation score
if uniprot_annot:
#set uniprot file if asked for, for protein filtering
self.set_uniprot_file()
prots = self.proteins_with_uniprot_annot(df,status=annot_status)
df = df.loc[prots]
self.samples_hq = self.make_df_samples( df , agg = agg )
def set_trans_samples_hq(self,
trans='None',
add_small=False,
stat_thresh=False,
threshold=95,
higher=False,
statistic='variance'):
"""
Transforming hq values with different functions, by default log1p.
Depends on : samples_hq, proteins_by_statistic_threshold
Parameters
----------
trans: numerical transformation. Default: scikitlearn's StandardScaler
Indicates how to transform the raw protein values
add_small
Add small value if any dataframe value is 0 - when log transforming
stat_threshold
Subsetting dataframe by a statistic threshold
threshold [0,100]
Quantile for statistic threshold
higher
Subset above or below statistic threshold
statistic {'mean','median','variance'}
Statistic to be applied
"""
#set hq dataframe; make sure there's no NaN values
data = self.samples_hq
#instantiate/declare/set up Standard scaler model from
#scikitlearn on data
scaler = StandardScaler()
scaler.fit(data)
#only do log (other than log1p) transformations if values are
#all nonzero
if len(np.where(data.as_matrix().ravel()==0)[0])>0:
add_small = True
print('There are zero values in the sample dataframe, a small number epsilon must be added to the protein values when there are zero values. Adding small epsilon...')
#list of name-function pairs
func = [('log1p', np.log1p),
('log2', np.log2),
('sklearn', scaler.transform),
('rank_normalize', rank_normalize),
('quantile_normalize', quantileNormalize),
('None', pd.DataFrame.copy)]
#get appropriate list index for function from trans string
m = [x for x in range(len(func)) if trans in func[x][0]][0]
#add small epsilon value to all protein values
if add_small:
eps = 0.0001
data = data.applymap(lambda x : x + eps)
#apply function from appropriate function list index
data = pd.DataFrame(func[m][1](data),
index=data.index,
columns=data.columns
)
#subset to have proteins that meet a certain statistical threshold
if stat_thresh:
prots = self.proteins_by_statistic_threshold(data,
statistic=statistic,
threshold=threshold,
higher=higher)
data = data.loc[prots]
self.trans_samples_hq = data
def set_samples(self):
"""
Setting patient names from raw dataframe
Depends on : sample_replicate_dictionary
Parameters
----------
None
"""
self.samples = [x for x in self.sample_replicate_dictionary.keys()]
def set_proteins(self):
"""
Setting protein ids from raw dataframe
Depends on raw_replicates
Parameters
----------
None
"""
self.proteins = self.raw_replicates.index.values
def set_sample_groups(self,file=None):
"""
Setting group membership of samples dataframe where 1 indicates membership and 0 no membership.
Parameters
----------
file
file to read sample groups data. Defaults to parameters from cohorts instantiation
"""
#checking if tab separated (tsv) or comma separated (csv) format
splt = self.sample_groups_file.split(".")
format = splt[len(splt)-1][0]
if format is 'c':
self.sample_groups = pd.read_csv(self.sample_groups_file,delimiter=",",index_col=0)
else:
self.sample_groups = pd.read_csv(self.sample_groups_file,delimiter="\t",index_col=0)
def set_df_replicate_groups(self):
"""
Aggregating df_replicate_groups to derive sample group
membership
Parameters
----------
None
"""
mats = {}
for samp in self.samples:
single = self.sample_groups.loc[:,samp]
reps = self.sample_replicate_dictionary[samp]
for r in reps:
mats[r] = single
return pd.DataFrame.from_dict(mats)
def set_replicate_groups(self,file=None):
"""
Setting group membership of replicate dataframe where 1 indicates membership and 0 no membership.
Parameters
----------
file
file to read replicate groups data. Defaults to parameters from cohorts instantiation
"""
self.replicate_groups = self.set_df_replicate_groups()
def set_groups(self):
"""
Setting groups from sample groups dataframe
Parameters
----------
None
"""
self.groups = self.sample_groups.index.values
def set_ref(self,ref='NL'):
"""
Setting reference group (hard coded to be normal patients or 'NL', but can change this after declaration)
Parameters
----------
ref: string
Reference group name
"""
#get ref index
ind = np.where(self.groups==ref)[0]
#make sure there's only one trt name in all groups
if len(ind)==1:
self.ref = self.groups[ind]
else:
self.ref = np.asarray(self.groups[0],dtype='object')
def set_treat(self,trt='PGD'):
"""
Setting treatment group
Parameters
----------
trt: string
Treatment group name
"""
#get trt index
ind = np.where(self.groups==trt)[0]
#make sure there's only one trt name in all groups
if len(ind)==1:
self.treat = self.groups[ind]
else:
self.treat = np.asarray(self.groups[1],dtype='object')
def set_tidy_replicate_groups(self):
"""
Setting tidy group membership of replicates, where each replicate is the observation and group membership is an attribute (column)
Parameters
----------
None
"""
#copy sample groups dataframe
df = self.replicate_groups.T.copy()
#set Replicates as column in dataframe
df.loc[:,'Replicates'] = df.index
#melt to tidy dataframe
melted = pd.melt(df,
id_vars=['Replicates'],
value_vars=df.columns.tolist()[0:len(df.columns)-1],
var_name='Groups'
)
#filter for group membership to samples
melted_filtered = melted.query('value != 0')
#delete value {0,1} column-unnecessary since it now redundantly indicates membership
del melted_filtered['value']
#set Samples dtype as string
melted_filtered.loc[:,'Replicates'] = melted_filtered['Replicates'].astype(str)
self.tidy_replicate_groups = melted_filtered
def set_tidy_sample_groups(self):
"""
Setting tidy group membership of samples, where each sample is the observation and group membership is an attribute (column)
Parameters
----------
None
"""
#copy sample groups dataframe
df = self.sample_groups.copy()
#set Samples as column in dataframe
df.loc[:,'Samples'] = df.index
#melt to tidy dataframe
melted = pd.melt(df,
id_vars=['Samples'],
value_vars=df.columns.tolist()[0:len(df.columns)-1],
var_name='Groups'
)
#filter for group membership to samples
melted_filtered = melted.query('value != 0')
#delete value {0,1} column-unnecessary since it now redundantly indicates membership
del melted_filtered['value']
#set Samples dtype as string
melted_filtered.loc[:,'Samples'] = melted_filtered['Samples'].astype(str)
self.tidy_sample_groups = melted_filtered
def get_protein_annotations(self,string='hq'):
'''
Get Uniprot protein ontology data
Parameters
----------
string : string
Indicate ontology data for either uniprot expert-curated or 'reviewed' proteins or all proteins from raw
Output
-------
tab : Ontology dataframe
'''
#get uniprot ontology
tab = get_uniprot_table()
#subset ontology with proteins of interest
if string=='hq':
inds = tab.index.isin(self.proteins)
return tab[inds]
if string=='all':
return tab
def get_uniprot_table(self):
"""
Upload uniprot database flat file
Parameters
----------
None
"""
tab = pd.read_csv(self.data_dir+self.uniprot_file,delimiter="\t",index_col=0)
return tab
#ANALYSIS FUNCTIONS
def manual_feature_extraction(self,df):
"""
Query protein quantification between reference and other groups
Parameters
----------
df
dataframe to manually extract features
"""
#load raw and sample group dataframes
df_samples = df
df_sample_groups = self.sample_groups
#make rownames-presence/absence/mixed conditions of proteins amongst samples
val_grps = ('allq', 'allnotq', 'mixed')
tmp = list(it.product(val_grps,val_grps))
rownames = []
for i in tmp:
rownames.append("_".join(i))
#set column names-reference/indicator scenarios
x = self.groups != self.ref[0]
t = [ self.ref[0] + '/' + x for x in self.groups[x] ]
colnames = tuple(t)
#populate length and protein array dataframes
df_len = pd.DataFrame(index=rownames,columns=colnames)
df_arr = pd.DataFrame(index=rownames,columns=colnames)
#populate each element with an empty array or list
for i, j in it.product(range(df_len.shape[0]),range(df_len.shape[1])):
df_len.iloc[i][j] = ()
for i, j in it.product(range(df_arr.shape[0]),range(df_arr.shape[1])):
df_arr.iloc[i][j] = []
#make list of functions for assessing presence/absence/mixed protein status
singlefuncs = [ ( "allq", allq ) ,
("allnotq", allnotq ) ,
("mixed", mixed )
]
#set reference group
ref_grp = self.ref[0]
#loop through indicators to assess presense/absence/mixed proteins for each reference/indicator scenario and populate length/protein array dataframes
for i in self.groups[x]:
#set reference/indicator scenario
gr1 = ref_grp
gr2 = i
colname = gr1+"/"+gr2
print(colname)
#make arrays of proteins for reference samples for each assessment condition
gr1_arr = []
tmp = df_samples.T
arr1 = df_sample_groups.loc[gr1] == 1
X = tmp[arr1.values].transpose()
for l in range(len(val_grps)):
tmp = singlefuncs[l][1](X)#slow
gr1_arr.append(tmp)
#make arrays of proteins for reference samples for each assessment condition
gr2_arr = []
tmp = df_samples.T
arr2 = df_sample_groups.loc[gr2] == 1
X = tmp[arr2.values].transpose()
for k in range(len(val_grps)):
tmp = singlefuncs[k][1](X)
gr2_arr.append(tmp)
#for each combination of gr1_arr and gr2_arr, do intersection and append to corresponding row in column of data frame. This gives proteins in each condition for each reference/indicator scenario
for m,n in it.product( range( len(gr1_arr) ) , range( len(gr2_arr) ) ):
rowname = singlefuncs[m][0]+"_"+singlefuncs[n][0]
df_len.loc[ rowname , colname ] = len ( np.intersect1d( gr1_arr[m], gr2_arr[n] ) )
df_arr.loc[ rowname , colname ] = np.intersect1d( gr1_arr[m], gr2_arr[n] )
#dictionary of length and protein array dataframes
dictionary = { 'df_len' : df_len, 'df_arr' : df_arr}
helper_dictionary = self.make_protein_substraction(dictionary)
self.data['mfe'] = { 'main' : dictionary, 'helper' : helper_dictionary }
def make_protein_substraction(self,dictionary=None):
'''
Helper function only for manual_feature_extraction method to do set operations on protein results
Right now supports difference of proteins
Parameters
----------
dictionary
dictionary to fill in-fed from manual_feature_extraction
Output
------
Dictionary of protein array length band array from difference ofv manually extracted features between ref and treat groups
'''
#declare dictionary from manual feature extraction
mfe = dictionary
#set comparisons made in mfe
comps_grps = mfe['df_len'].columns.tolist()
#set protein feature comparisons from manual feature extraction
comps_prots = mfe['df_len'].index.tolist()
#make combination of comparisons-resulting dataframe rows and columns
combs = list(
it.product(
comps_grps,
comps_grps
)
)
#make dictionary of presence,absence, mixed. Values will be NxN dataframe labeled with combs above
protein_dict = dict.fromkeys(
comps_prots
)
#set dataframe to extract proteins from
df = mfe['df_arr']
#loop through dictionary keys which are the protein feature comparisons
for i in protein_dict.keys():
#make empty NxN dataframe to store protein lengths and arrays
empty_len = pd.DataFrame(
index = comps_grps,
columns = comps_grps
)
#make copied empty dataframe to store protein arrays
empty_diff = empty_len.copy()
#loopp through dataframe index, columns and store length of difference and proteins from difference of sets
for j in comps_grps:
for k in comps_grps:
diff_arr = set(df.loc[i,j]) - set(df.loc[i,k])
length = len(diff_arr)
empty_len.at[j,k] = length
empty_diff.at[j,k] = diff_arr
#store dictionary of dataframes as value in dictionary
protein_dict[i] = { 'df_len' : empty_len, 'df_arr' : empty_diff }
return protein_dict
def hypothesis_testing(self,df,df_groups):
"""
Hypothesis testing of reference sample proteins versus treatment sample proteins.
Parameters
----------
df
dataframe of values to test
df_groups
group membership of samples/replicates in df to test
Outputs
-------
df
hypothesis test results
"""
#get subset dataframes by reference and treatment groups
df1 = self.get_sub_df(df,df_groups,self.ref[0])
df2 = self.get_sub_df(df,df_groups,self.treat[0])
#List of hypothesis test names and functions
tests = self.tests
#set dataframe to fill
df = pd.DataFrame(columns=['Protein','Test','Pvalue','Statistic'])
#for each hypothesis test name and function
for i, hyp in enumerate(tests):
#set test name
test = hyp[0]
#for each protein
for j in range(0,df1.shape[0]):
#get protein location in dataframes
firstloc = df1.iloc[j]
secondloc = df2.iloc[j]
#make sure the arrays are filled with floats
a = firstloc.values.astype(float)
b = secondloc.values.astype(float)
#make sure the name of the protein is the same in each dataframe
if firstloc.name == secondloc.name:
#set protein name
protein = firstloc.name
else:
break
#set statistic from test
stat = hyp[1](a,b)[0]
#set pvalue from test
pval = hyp[1](a,b)[1]
#put data in pandas series
row = pd.Series([protein,test,pval,stat],index=df.columns)
#add row to dataframe
df = df.append(row,ignore_index=True)
#set correct object membership of dataframe columns
df = df.astype(dtype= {
"Protein":"str",
"Test":"str",
"Pvalue":"float64",
"Statistic":'float64'
}
)
return df
def get_sub_df(self,df,df_groups,grp):
'''
Helper function in class to get patient-subset dataframe.
Subset larger dataframe by reference and treatment groups
Used in hypothesis_testing()
Parameters
----------
df
proteomics data dataframe given to hypothesis_testing
df_groups
groups dataframe given to hypothesis testing
grp str
group name for subsetting
Output
------
subsetted dataset
'''
#get indices of replicates/samples in groups
inds = np.where(df_groups.loc[grp] == 1)
#get
return df.T.iloc[inds].T
#PROTEIN SUBSET FUNCTIONS
def proteins_with_uniprot_annot(self,df,status='reviewed'):