Repository navigation
Expand file tree
/
Copy pathgtseq.py
More file actions
809 lines (626 loc) · 26.3 KB
/
Copy pathgtseq.py
File metadata and controls
809 lines (626 loc) · 26.3 KB
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
from collections import Counter
from decimal import Decimal, ROUND_HALF_UP
from duplicates import Duplicates
from plots import GTPlots
from stats import GTStats
import os
import re
import sys
import pandas
class GTseq():
'Class for operating on GTseq genotype files'
def __init__(self, infile, identQuit, log):
self.gtFile = infile
self.logfile = log
self.plotDir = "plots"
self.identQuit = identQuit
# write command used to launch program
fh = open(self.logfile, 'a')
fh.write("#gtSeqConvert.py was launched with command:\n#")
comm = ' '.join(sys.argv)
fh.write(comm)
fh.write("\n\nAll filtering operations have been applied in the order they are presented in this log file.\n\n")
fh.close()
if os.path.exists(self.plotDir) == False:
os.mkdir(self.plotDir)
# prepare dict of lists to contain data for sankey diagrams
sankeyKeys = ['Source', 'Filter', 'Count']
self.sankeyIndDict = {key: [] for key in sankeyKeys}
self.sankeyLocDict = {key: [] for key in sankeyKeys}
self.discardStart = None # used to hold individuals discarded from beginning
def returnSankeyDicts(self):
return self.sankeyIndDict, self.sankeyLocDict
def heterozygosity(self, pdf, prepost):
hetVals = dict()
for ind, row in pdf.iterrows():
locCount = 0
hetCount = 0
ho = Decimal(0.0)
for locus, geno in row.items():
if str(geno) != "0":
locCount+=1
mid = len(geno) // 2
a1, a2 = geno[:mid], geno[mid:]
if a1 != a2:
hetCount+=1
if locCount != 0:
val = Decimal(hetCount/locCount)
ho = val.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
hetVals[ind] = ho
df = pandas.DataFrame.from_dict(hetVals, orient='index', columns=['Ho'])
self.plotHet(df, prepost)
def plotHet(self, df, prepost):
hetVals = df['Ho'].tolist() # extract as list for stats calculations
hetValsDict = df['Ho'].to_dict() # extract as dict for plotting
# calculate stats
hetStats = GTStats()
hetStats.calcStats(hetVals)
hetStats.printStats(self.logfile, "heterozygosity", prepost)
# make histogram and QQ plots
hetFn = "histogram.obsHet." + prepost + ".png"
hetQQfn = "qqplot.obsHet." + prepost + ".png"
hetHisto = os.path.join(self.plotDir, hetFn)
hetQQ = os.path.join(self.plotDir, hetQQfn)
hetValsPlot = GTPlots(hetValsDict)
hetValsPlot.printHistogram(hetHisto, 1.0, 50, "Obs. Het. Distribution", "Obs. Het. Values")
hetValsPlot.printQQplot(hetQQ, "Normal Q-Q Plot (Obs. Het.)", "Observed Heterozygosity")
# This function can only be run after the GTseq.remDupGenos() function because it will add an object of type Duplicates to this class as a member variable (self.dups)
def plotMismatches(self):
# mismatches is a list of numpy type np.int64
mismatches = self.dups.returnMismatches()
mismatchDict = dict(enumerate(mismatches)) # enumerate to add dummy key values for purpose of making dict to plot data
# calculate stats
mismatchStats = GTStats()
mismatchStats.calcStats(mismatches)
# make histogram and qq plots
print("\nMaking mismatch histogram and qq plots. This can take a while with large datafiles...\n")
histoFN = "histogram.mismatch.png"
qqFN = "qqplot.mismatch.png"
mismatchHisto = os.path.join(self.plotDir, histoFN)
mismatchQQ = os.path.join(self.plotDir, qqFN)
maxMismatch = max(int(v) for v in mismatchDict.values()) # get max mismatch score while ensuring values in dict are numeric
mismatchPlot = GTPlots(mismatchDict)
mismatchPlot.printHistogram(mismatchHisto, maxMismatch, maxMismatch, "Distribution of Genotype Mixmatches", "Mismatches") # number of bins = maxMismatch value
mismatchPlot.printQQplot(mismatchQQ, "Normal Q-Q Plot (Genotype Mismatch Counts)", "Number of Mismatching Loci")
def plotIFI(self, df, prepost):
ifiScores = df['IFI'].tolist() # extract as list for stats calculations
ifiScores = [Decimal(x) for x in ifiScores] # cast all list elements as Decimal
ifiScoresDict = df['IFI'].to_dict() # extract as dict for plotting
# calculate stats
ifiStats = GTStats()
ifiStats.calcStats(ifiScores)
ifiStats.printStats(self.logfile, "ifi scores", prepost)
# make histogram plot
ifiFn = "histogram.ifi." + prepost + ".png"
ifiHisto = os.path.join(self.plotDir, ifiFn)
maxIFI = max(float(v) for v in ifiScoresDict.values()) # get max IFI score while ensuring values in dict are numeric
binCount = int(maxIFI/0.125) # get about 40 bins per 5.0 IFI score units
ifiScoresPlot = GTPlots(ifiScoresDict)
ifiScoresPlot.printHistogram(ifiHisto, maxIFI, binCount, "IFI Score Distribution", "IFI Scores")
def makeHistos(self, df, prepost):
deepcopy = df.copy() # make deep copy of dataframe
print(f"\nCalculating {prepost} missing data statistics.")
# remove metadata columns so they are not potentially counted in missing data
metadataCols = ['Population ID', 'colony2', 'IFI', 'ZOPT', 'Sex', 'POPCOLUMN_SEX', 'POPCOLUMN_REPRO_YEARS', 'POPCOLUMN_SPAWN_GROUP', 'OFFSPRINGCOLUMN_BORN_YEAR', 'OFFSPRINGCOLUMN_SAMPLE_YEAR', 'OFFSPRINGCOLUMN_AGE_AT_SAMPLING'] # list of all possible metadata columns. All others will be treated as genotype data
remove = list() # track list of columns to be removed
metaCols = pandas.DataFrame() # make empty dataframe to hold removed columns
for col in metadataCols:
if col in deepcopy.columns:
remove.append(col)
if remove:
print(f"Ignoring metadata columns for {prepost} missing data calculations and plots.\n")
metaCols = self.removeColumns(deepcopy, remove)
# metadata removed; can now calculate number of loci and individuals
inds = str(len(deepcopy)) # number of individuals
loci = str(len(deepcopy.columns)) # number of loci
print(f"Printing {prepost} stats for {inds} individuals and {loci} loci.\n")
# convert the '0' character from .csv files to 0 integer (as read from .xlsx files)
deepcopy = deepcopy.replace('0', 0)
# calculate pre- or post-filter proportion of missing data in loci
missingDictLoci = self.calcMissingLoci(deepcopy)
lociMissVals = list(missingDictLoci.values()) # get missing data proportions as list
# calculate pre- or post-filter missing data statistics per locus
lociStats = GTStats()
lociStats.calcStats(lociMissVals)
lociStats.printStats(self.logfile, prepost, "loci")
# plot pre- or post-filter missing loci data here
lociFn = "histogram.loci." + prepost + ".png"
lociHisto = os.path.join(self.plotDir, lociFn)
missingLociPlot = GTPlots(missingDictLoci)
missingLociPlot.printHistogram(lociHisto, 1.0, 40, "Proportion of Missing GTseq Data (per Locus)", "Proportion Missing")
# calculate pre- or post-filter missing data per individual
missingDictInds = self.calcMissingInds(deepcopy)
indsMissVals = list(missingDictInds.values()) # get missing data proportions as list
# calculate pre- or post-filter missing data statistics per individual
indsStats = GTStats()
indsStats.calcStats(indsMissVals)
indsStats.printStats(self.logfile, prepost, "individuals")
# make plot of pre- or post-filter missing data per individual
indsFn = "histogram.individuals." + prepost + ".png"
indsHisto = os.path.join(self.plotDir, indsFn)
missingIndsPlot = GTPlots(missingDictInds)
missingIndsPlot.printHistogram(indsHisto, 1.0, 40, "Proportion of Missing GTseq Data (per Individual)", "Proportion Missing")
# calculate pre- or post-filter heterozygosity per individual
self.heterozygosity(deepcopy, prepost)
del metaCols # make sure memory used by removed columns is freed
del deepcopy # make sure memory used by the deep copy is freed
def printRetained(self, start, end, keepPops=None):
## start is a pandas series
## end is of type 'collections.Counter'
fh = open(self.logfile, 'a')
fh.write("The following table reports the number of individuals retained (Output) from each population.\n")
fh.write("The Output(expected) value assumes missing individuals are evenly distributed among sample groups.\n")
fh.write("Population\tInput\tOutput(observed)\tOutput(expected)\n")
print("The following table reports the number of individuals retained (Output) from each population.")
print("The Output(expected) value assumes missing individuals are evenly distributed among sample groups.")
print("Population\tInput\tOutput(observed)\tOutput(expected)")
start = start.sort_index() # sort start pandas series so table prints in consistent order
# check if keeppops (-P) option used
if keepPops is not None:
self.discardStart = start[~start.index.isin(keepPops)]
start = start[start.index.isin(keepPops)]
end = Counter({k: end[k] for k in keepPops if k in end})
totalIn = start.sum() # total samples input
totalOut = end.total() # total samples output
pctRetained = float(totalOut / totalIn) # percentage of retained individuals
# track retained individuals for sankey plot
self.sankeyIndDict["Source"].append("All")
self.sankeyIndDict["Filter"].append("Retained")
self.sankeyIndDict["Count"].append(str(totalOut))
fh.close()
return start, end
def printDiscard(self):
fh = open(self.logfile, 'a')
# print discarded populations
totalDiscardIn = self.discardStart.sum() # total samples input
print("These populations were discarded by the -P / --keeppops filter:")
print("Population\tInput\tOutput(observed)\tOutput(expected)")
fh.write("These populations were discarded by the -P / --keeppops filter:\n")
fh.write("Population\tInput\tOutput(observed)\tOutput(expected)\n")
# print / write to log counts for discarded populations
for k, v in self.discardStart.items():
print("{}\t{}\t{}\t{}".format(k, v, "0", "0.0"))
fh.write(str(k) + "\t" + str(v) + "\t" + str("0") + "\t" + "0.0\n")
print("{}\t{}\t{}\t{}".format("Total", str(totalDiscardIn), "0", "N/A"))
print("")
fh.write(str("Total\t") + str(totalDiscardIn) + "\t0\tN/A\n\n")
fh.close()
def parseFile(self):
print("Reading input file.")
print("")
# test if .xlsx file and read it into pandas dataframe
if self.gtFile.endswith(".xlsx"):
with pandas.ExcelFile(self.gtFile) as xlsx:
try:
data = pandas.read_excel(xlsx, 'Final Genotypes', index_col=0)
except ValueError as e:
print("ERROR:")
print(e)
print("Your GTseq data must be in a worksheet named exactly \"Final Genotypes\" (no quotes).")
print("Exiting program...")
print("")
raise SystemExit
# if not .xlsx, test if .csv file and read it into pandas dataframe
elif self.gtFile.endswith(".csv"):
try:
data = pandas.read_csv(self.gtFile, on_bad_lines="error", index_col=0, header=0, engine="python")
except pandas.errors.ParserError as e:
print(f"ERROR: Malformed CSV rows. Details: {e}")
print("Exiting program...")
print("")
raise SystemExit
# exit with error if not .xlsx or .csv
else:
print("Input file not .xlsx or .csv. How did you get here?\n")
raise SystemExit
# test for duplicate sample names
print("Checking for duplicate sample names...")
duplicateNames = data.index.duplicated().any()
if duplicateNames:
print("These sample names appeared multiple times in your input file:")
duplicateList = data.index[data.index.duplicated()].unique().tolist()
print(*duplicateList, sep='\n')
if self.identQuit:
print("ERROR: Your input .xlsx file contains duplicate sample names.")
print("Either fix this problem in your input file or try forcing duplicated names to be unique with the -Q / --identquit option.")
print("Exiting program...\n")
raise SystemExit
else:
print("\nForcing unique names for duplicates...")
print("The first occurrence of each name will be unmodified and subsequent occurrences will have suffixes appended (e.g., '_1', '_2', etc.)\n")
counts = data.index.to_series().groupby(level=0).cumcount()
data.index = data.index.where(counts == 0, data.index + '_' + counts.astype(str))
else:
print("None Found!\n")
return data
# remove duplicate individuals
def remDupGenos(self, df, dupThresh, keepDups):
dups = Duplicates(df, dupThresh, keepDups, self.logfile)
dups.findDups()
removeList = dups.removeDups() # get list of individuals to remove
removedDups = pandas.DataFrame() # initialize empty dataframe
if not removeList:
print("No duplicates to be removed.")
else:
# track removed individuals for sankey plot
self.sankeyIndDict["Source"].append("Discarded")
self.sankeyIndDict["Filter"].append("keepdups")
self.sankeyIndDict["Count"].append(str(len(removeList)))
removedDups = self.removeRows(df, removeList)
self.dups = dups # add Duplicates() object as member variable
return removedDups
def getPops(self, df):
pops = df.pop('Population ID').to_dict()
return pops
def filterFile(self, df, pMissLoci, pMissInd, fileName, discardDir, order):
# this converts the '0' character from .csv files to 0 integer (as read from .xlsx files)
df = df.replace('0', 0)
## REMOVE IN FUTURE REVISION - this is never being used again - why am I calculating this?
# also calculate missing data per individual before removing loci with high missingness
#missingDictTemp = self.calcMissingInds(df)
# initialize empty pandas dataframes
removedLoci = pandas.DataFrame()
removedInds = pandas.DataFrame()
if order == "loci":
# start by calculating proportion of missing data in loci
missingDictLoci = self.calcMissingLoci(df)
# remove loci
removedLoci = self.removeMissingLoci(missingDictLoci, df, pMissLoci)
# calculate proportion of missing data in individuals
missingDictInd = self.calcMissingInds(df)
# remove individuals and print discarded data to file
removedInds = self.removeMissingInds(missingDictInd, df, pMissInd)
elif order == "individuals":
# start by calculating proportion of missing data in individuals
missingDictInd = self.calcMissingInds(df)
# remove individuals
removedInds = self.removeMissingInds(missingDictInd, df, pMissInd)
# calculate proportion of missing data in loci
missingDictLoci = self.calcMissingLoci(df)
# remove loci and print discarded data to file
removedLoci = self.removeMissingLoci(missingDictLoci, df, pMissLoci)
else:
print(f"\nERROR: requested to filter {order} first (-o / --order option).")
print("Code should be unreachable - how did you get here?\n")
SystemExit(1)
# print discarded locus data to file
lociName = re.sub('.REPLACE.xlsx$', '.filteredLoci.xlsx', fileName)
lociName = os.path.join(discardDir, lociName)
removedLoci.to_excel(lociName, sheet_name="Final Genotypes")
# print discarded individual data to file
indsName = re.sub('.REPLACE.xlsx$', '.filteredIndividuals.xlsx', fileName)
indsName = os.path.join(discardDir, indsName)
removedInds.to_excel(indsName, sheet_name="Final Genotypes")
return df
def removeSpecial(self, df, snps, locfilter):
remove = list()
with open(snps, 'r') as fh:
for line in fh:
remove.append(line.strip())
# track number of loci being removed per filter
self.sankeyLocDict["Source"].append("Discarded")
self.sankeyLocDict["Filter"].append(locfilter)
self.sankeyLocDict["Count"].append(len(remove))
junk = self.removeColumns(df, remove)
return junk
def removeIFI(self, df):
print("Checking for presence of IFI score column.")
optionalCols = ['IFI']
remove = list()
ifiCols = pandas.DataFrame()
for col in optionalCols:
if col in df.columns:
remove.append(col)
if remove:
print("IFI score column is being removed.")
ifiCols = self.removeColumns(df, remove)
else:
print("IFI score column not detected in input file.\n")
return ifiCols
def removeColony(self, df):
print("Checking for presence of optional Colony2 column.")
optionalCols = ['colony2']
remove = list()
colonyCol = pandas.DataFrame()
for col in optionalCols:
if col in df.columns:
remove.append(col)
if remove:
print("Colony2 column is being removed.\n")
colonyCol = self.removeColumns(df, remove)
else:
print("Colony2 column not detected in input file.\n")
return colonyCol
def removeSnppit(self, df):
print("Checking for presence of optional SNPPIT columns.")
#list of all possible optional snppit columns
optionalCols = ['POPCOLUMN_SEX', 'POPCOLUMN_REPRO_YEARS', 'POPCOLUMN_SPAWN_GROUP', 'OFFSPRINGCOLUMN_BORN_YEAR', 'OFFSPRINGCOLUMN_SAMPLE_YEAR', 'OFFSPRINGCOLUMN_AGE_AT_SAMPLING']
remove = list() #will hold list of snppit columns that appear in pandas df
snppitCols = pandas.DataFrame() #declare empty dataframe to be returned even if no optional columns were used.
for col in optionalCols:
if col in df.columns:
remove.append(col) #add existing cols to remove list
if remove:
print("The following optional SNPPIT columns were detected in the input file:")
for col in remove:
print(col)
print("")
snppitCols = self.removeColumns(df, remove)
else:
print("No optional SNPPIT columns detected in input file.")
print("")
return snppitCols
def removeSex(self, df):
print("Checking for presence of optional column containing phenotypic sex data.")
optionalCols = ['Sex']
remove = list()
sexCols = pandas.DataFrame()
for col in optionalCols:
if col in df.columns:
remove.append(col)
if remove:
print("The phenotypic sex data column is being removed.")
for col in remove:
print(col)
print("")
sexCols = self.removeColumns(df, remove)
else:
print("Phenotypic sex column not detected in input file.")
print("")
return sexCols
def removeNewhyb(self, df):
print("Checking for presence of optional Newhybrids columns.")
optionalCols = ['ZOPT']
remove = list() #will hold list of snppit columns that appear in pandas df
newhybCols = pandas.DataFrame() #declare empty dataframe to be returned even if no optional columns were used.
for col in optionalCols:
if col in df.columns:
remove.append(col) #add existing cols to remove list
if remove:
print("The following optional NewHybrids columns were detected in the input file:")
for col in remove:
print(col)
print("")
newhybCols = self.removeColumns(df, remove)
else:
print("No optional NewHybrids columns detected in input file.")
print("")
return newhybCols
def calcMissingLoci(self, df):
print("Calculating missing data per locus.")
missingDict = dict()
numInds = len(df)
for (columnName, columnData) in df.items():
alleledict = df[columnName].value_counts().to_dict() #convert type pandas.Series to dict
# add a 0 key to the dict if there is no 0 key
if 0 not in alleledict.keys():
alleledict[0] = 0
try:
missing=Decimal(alleledict[0]/numInds)
except ZeroDivisionError as e:
print("ERROR at locus")
print(columnName)
print(e)
print("This error occurred when calculating the proportion of missing data per locus.")
print("Exiting program...")
print("")
raise SystemExit
missingDict[columnName] = missing
return missingDict
def removeMissingLoci(self, missingDict, df, pMissLoci):
fh = open(self.logfile, 'a')
print("Removing loci with missing data proportion >", pMissLoci)
fh.write("Removed loci with missing data proportion > ")
fh.write(str(pMissLoci))
fh.write("\n")
remove = list()
removeMiss = list()
keepMiss = list()
print("Loci removed from dataset:")
print("Locus\tMissing")
fh.write("Loci removed from dataset:\n")
fh.write("Locus\tMissing\n")
for (key, value) in missingDict.items():
if value > Decimal(pMissLoci):
print(key, "\t", format(value, ".3f"))
fh.write(key)
fh.write("\t")
fh.write(format(value, ".3f"))
fh.write("\n")
remove.append(key)
removeMiss.append(value)
else:
keepMiss.append(value)
fh.write("\n")
fh.close()
junk = pandas.DataFrame()
if remove:
# track number of loci removed for sankey plots
self.sankeyLocDict["Source"].append("Discarded")
self.sankeyLocDict["Filter"].append("pmissloc")
self.sankeyLocDict["Count"].append(len(remove))
junk = self.removeColumns(df, remove)
print("")
return junk
def removeMonomorphicLoci(self, df):
fh = open(self.logfile, 'a')
remove = list()
for columnName, columnData in df.items():
alleledict = df[columnName].value_counts().to_dict()
counter = 0
for key, value in alleledict.items():
if str(key) != "0":
counter+=1
if counter == 1:
remove.append(columnName)
if remove:
self.sankeyLocDict["Source"].append("Discarded")
self.sankeyLocDict["Filter"].append("monomorphic")
self.sankeyLocDict["Count"].append(len(remove))
junk = pandas.DataFrame()
if remove:
print(str(len(remove)) + " loci were removed because they were monomorphic:")
fh.write(str(len(remove)))
fh.write(" loci were removed because they were monomorphic:\n")
for loc in remove:
print(loc)
fh.write(loc)
fh.write("\n")
print("")
fh.write("\n")
junk = self.removeColumns(df, remove)
else:
print("No monomorphic loci detected.")
print("")
fh.write("No monomorphic loci detected.\n\n")
fh.close()
return junk
def calcMissingInds(self, df):
print("Calculating missing data per individual.")
missingInd = dict()
numLoci = len(df.columns)
for (rowName, rowData) in df.iterrows():
numMissing = 0
for (locus, genotype) in rowData.items():
if genotype == 0:
numMissing = numMissing+1
try:
missing = Decimal(numMissing/numLoci)
except ZeroDivisionError as e:
print("ERROR:")
print(e)
print("This error occurred when calculating the proportion of mising data per individual.")
print("This could result if all loci were discarded by missing data filter (option -l).")
print("Exiting program...")
print("")
raise SystemExit
missingInd[rowName] = missing
return missingInd
def removeMissingInds(self, missingDict, df, pMissInd):
fh = open(self.logfile, 'a')
fh.write("Removed individuals with missing data proportion > " + str(pMissInd) + "\n")
print("Removing individuals with missing data proportion >", pMissInd)
remove = list()
removeMiss = list() # list to hold missing data proportion of each removed individual
keepMiss = list() # list to hold missing data proportion of each kept individual
print("Individuals removed from dataset:")
print("Sample\tMissing")
fh.write("Individuals removed from dataset:\n")
fh.write("Sample\tMissing\n")
for (key, value) in missingDict.items():
if value > Decimal(pMissInd):
print(key, "\t", format(value, ".3f"))
fh.write(key)
fh.write("\t")
fh.write(format(value, ".3f"))
fh.write("\n")
remove.append(key)
removeMiss.append(value)
else:
keepMiss.append(value)
fh.write("\n")
fh.close()
junk = pandas.DataFrame()
if remove:
junk = self.removeRows(df, remove)
# track number of removed individuals for sankey plot
self.sankeyIndDict["Source"].append("Discarded")
self.sankeyIndDict["Filter"].append("pmissind")
self.sankeyIndDict["Count"].append(str(len(removeMiss)))
print("")
return junk
def removeIFIinds(self, df, ifiCols, ifiScore):
fh = open(self.logfile, 'a')
fh.write("Removed individuals with IFI score > " + str(ifiScore) + "\n")
remove = list()
# pull out columns greater than IFI score
toss = ifiCols[ifiCols['IFI'] > ifiScore]
junk = pandas.DataFrame()
# convert the 'toss' pandas dataframe to a list of samples to be removed
if not toss.empty:
# write to file
fh.write("Individuals removed from dataset:\n")
fh.write("Sample\tIFI\n")
# print to terminal
print("Individuals removed from dataset:")
print("Sample\tIFI")
for index, value in toss['IFI'].items():
fh.write(str(index) + "\t" + str(value) + "\n")
print(str(index), "\t", str(value))
remove = toss.index.tolist()
if remove:
junk = self.removeRows(df, remove)
print("\nRemoved "+ str(len(remove)) + " individuals with IFI score > " + str(ifiScore) + ".\n\n")
fh.write("\nRemoved "+ str(len(remove)) + " individuals with IFI score > " + str(ifiScore) + ".\n\n")
# track number of removed individuals for sankey plot
self.sankeyIndDict["Source"].append("Discarded")
self.sankeyIndDict["Filter"].append("ifi")
self.sankeyIndDict["Count"].append(str(len(remove)))
else:
print("No samples had IFI scores > " + str(ifiScore) + ".\n\n")
fh.write("\nNo samples had IFI scores > " + str(ifiScore) + ".\n\n")
fh.write("\n")
fh.close()
return junk
def removeInds(self, df, removeFile):
remove = list()
with open(removeFile, 'r') as fh:
for line in fh:
remove.append(line.strip())
junk = pandas.DataFrame()
if remove:
# track removed individuals for sankey plot
self.sankeyIndDict["Source"].append("Discarded")
self.sankeyIndDict["Filter"].append("removeinds")
self.sankeyIndDict["Count"].append(str(len(remove)))
try:
junk = self.removeRows(df, remove)
print("")
except KeyError as e:
print("ERROR: " + removeFile + " contains individuals not found in Excel file.")
print(e)
print("")
raise SystemExit
else:
print("WARNING: removelist option (-r) was invoked but file " + removeFile + " was empty.")
print("")
return junk
# moved this to its own function so I could pass the set of kept populations to other functions
def parseRemovePops(self, removeFile):
popSet = set(line.strip() for line in open(removeFile))
return popSet
def removePops(self, df, popSet):
junk = pandas.DataFrame()
if popSet:
remove = self.findInds(df, popSet)
# track removed individuals for sankey plot
self.sankeyIndDict["Source"].append("Discarded")
self.sankeyIndDict["Filter"].append("keeppops")
self.sankeyIndDict["Count"].append(str(len(remove)))
junk = self.removeRows(df, remove)
print("")
else:
print("WARNING: keeppops option (-P) was invoked but file " + removeFile + " was empty.")
print("")
return junk
def findInds(self, df, popSet):
removeSamples = list()
for (sampleName, pop) in df['Population ID'].items():
if str(pop) not in popSet:
removeSamples.append(sampleName)
return removeSamples
def removeColumns(self, df, removelist):
junk = pandas.concat([df.pop(x) for x in removelist], axis=1)
return junk
def removeRows(self, df, removelist):
junk = pandas.DataFrame()
try:
junk = pandas.concat([self.popRow(df, x) for x in removelist], axis=0)
except KeyError as e:
print(f"\nWARNING while removing pandas dataframe rows: {e}")
print("Check if this individual was in your input file. Final counts of removed individuals may be incorrect.")
return junk
def popRow(self, df, index):
row = df.loc[[index]] #double brackets returns row as type pandas.dataframe rather than type pandas.series
df.drop(index, inplace=True)
return row