-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_beelinetools.py
3878 lines (3423 loc) · 143 KB
/
test_beelinetools.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
"""Tests the beelinetools script."""
from __future__ import print_function
import os
import shutil
import random
import logging
import platform
import unittest
import collections
from argparse import Namespace
from collections import defaultdict
from subprocess import check_call, PIPE
from tempfile import mkdtemp, NamedTemporaryFile
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from pyplink.tests.test_pyplink import get_plink
import beelinetools
_possible_nuc = ("A", "C", "G", "T")
class TestBeelineTools(unittest.TestCase):
def setUp(self):
"""Setup the tests."""
self.tmp_dir = mkdtemp(prefix="beelinetools_test_")
def tearDown(self):
"""Finishes the tests."""
# Cleaning the temporary directory
shutil.rmtree(self.tmp_dir)
def _my_compatibility_assertLogs(self, logger=None, level=None):
"""Compatibility 'assertLogs' function for Python < 3.4."""
if hasattr(self, "assertLogs"):
return self.assertLogs(logger, level)
else:
return AssertLogsContext_Compatibility(self, logger, level)
def test_encode_chromosome(self):
"""Tests the 'encode_chromosome' function."""
# Testing all valid chromosome
for chrom in range(1, 27):
observed = beelinetools.encode_chromosome(str(chrom))
self.assertEqual(chrom, observed)
# Testing X chromosome
for chrom in ("x", "X", "23"):
observed = beelinetools.encode_chromosome(chrom)
self.assertEqual(23, observed)
# Testing the Y chromosome
for chrom in ("y", "Y", "24"):
observed = beelinetools.encode_chromosome(chrom)
self.assertEqual(24, observed)
# Testing the pseudo autosomal region
for chrom in ("XY", "YX", "25"):
observed = beelinetools.encode_chromosome(chrom)
self.assertEqual(25, observed)
# Testing the mitochondrial chromosome
for chrom in ("M", "MT", "26"):
observed = beelinetools.encode_chromosome(chrom)
self.assertEqual(26, observed)
def test_encode_chromosome_invalid(self):
"""Tests the 'encode_chromosome' function for invalid chromosome."""
# Testing invalid chromosome
for chrom in ("-9", "0", "27"):
observed = beelinetools.encode_chromosome(chrom)
self.assertEqual(0, observed)
def test_get_header(self):
"""Tests the 'get_header' function."""
# Creating a temporary file
tmp_filename = None
with NamedTemporaryFile("w", dir=self.tmp_dir, delete=False) as f:
tmp_filename = f.name
print(*range(6), sep="\n", file=f)
print("[Data],,,", file=f)
print("header_1,header_2,header_3", file=f)
for j in range(6):
print(*["data_{}_{}".format(i+1, j) for i in range(3)],
sep=",", file=f)
# Reading until the header (with good separator)
expected = {"header_{}".format(i+1): i for i in range(3)}
with open(tmp_filename, "r") as i_file:
observed = beelinetools.get_header(i_file)
self.assertEqual(expected, observed)
# Reading until the header (with bas separator)
expected = {"header_1,header_2,header_3": 0}
with open(tmp_filename, "r") as i_file:
observed = beelinetools.get_header(i_file, delim="\t")
self.assertEqual(expected, observed)
def test_get_header_error(self):
"""Tests the 'get_header' function with errors."""
# Creating a temporary file
tmp_filename = None
with NamedTemporaryFile("w", dir=self.tmp_dir, delete=False) as f:
tmp_filename = f.name
print(*range(6), sep="\n", file=f)
print("[Data],,,", file=f)
print("header_1,header_2,header_3", file=f)
for j in range(6):
print(*["data_{}_{}".format(i+1, j) for i in range(3)],
sep=",", file=f)
# This should raise an exception
with open(tmp_filename, "r") as i_file:
with self.assertRaises(beelinetools.ProgramError) as e:
beelinetools.get_header(i_file, data_delim="[Assay]")
self.assertEqual("{}: no data in file".format(tmp_filename),
e.exception.message)
# Writing a long file without data
with open(tmp_filename, "w") as o_file:
for i in range(1001):
print(i, file=o_file)
# This should raise an exception
with open(tmp_filename, "r") as i_file:
with self.assertRaises(beelinetools.ProgramError) as e:
beelinetools.get_header(i_file)
self.assertEqual(
"{}: no data after 1000 lines".format(tmp_filename),
e.exception.message,
)
def test_read_mapping_info(self):
"""Tests the 'read_mapping_info' function."""
tmp_filename = None
expected = {}
with NamedTemporaryFile("w", dir=self.tmp_dir, delete=False) as f:
tmp_filename = f.name
print(*range(6), sep="\n", file=f)
print("[Assay]", file=f)
print("Name,Chr,MapInfo,SNP,Strand", file=f)
for i in range(100):
marker_name = "marker_{}".format(i + 1)
chrom = random.randint(1, 26)
pos = random.randint(1, 3000000)
alleles = random.sample(_possible_nuc, 2)
snp = "[{}]".format("/".join(alleles))
strand = random.choice(("TOP", "BOT"))
# Printing the mapping information
print(marker_name, chrom, pos, snp, strand, sep=",", file=f)
# The expected alleles
a1 = alleles[0]
a2 = alleles[1]
if strand == "BOT":
a1 = beelinetools._complement[a1]
a2 = beelinetools._complement[a2]
# The expected data
expected[marker_name] = beelinetools._Location(
chrom=chrom, pos=pos, alleles={a1: "A", a2: "B"},
)
# Adding some INDELs
for i in range(10):
marker_name = "indel_{}".format(i + 1)
chrom = random.randint(1, 26)
pos = random.randint(1, 3000000)
alleles = random.sample(["I", "D"], 2)
snp = "[{}]".format("/".join(alleles))
strand = random.choice(("PLUS", "MINUS"))
# Printing the mapping information
print(marker_name, chrom, pos, snp, strand, sep=",", file=f)
# The expected data
expected[marker_name] = beelinetools._Location(
chrom=chrom, pos=pos,
alleles={alleles[0]: "A", alleles[1]: "B"},
)
# Getting the expected data
observed = beelinetools.read_mapping_info(
i_filename=tmp_filename,
delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
allele_strand="top",
strand_col="Strand",
)
self.assertEqual(expected, observed)
# Adding a '[Controls]' line, everything below should be excluded
with open(tmp_filename, "a") as o_file:
print("added_marker,1,1,[A/G],TOP", file=o_file)
print("[Controls],,,", file=o_file)
print("skipped_line", file=o_file)
expected["added_marker"] = beelinetools._Location(
chrom=1,
pos=1,
alleles={"A": "A", "G": "B"},
)
# Getting the expected data
observed = beelinetools.read_mapping_info(
i_filename=tmp_filename,
delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
allele_strand="top",
strand_col="Strand",
)
self.assertEqual(expected, observed)
def test_read_list(self):
"""Tests the 'read_list' function."""
# Giving None should return an empty set
self.assertEqual(set(), beelinetools.read_list(None))
# Writing a file containing 10 elements (9 unique ones)
list_filename = os.path.join(self.tmp_dir, "elements.txt")
elements = ["Sample_{}".format(i) for i in range(9)] + ["Sample_3"]
with open(list_filename, "w") as o_file:
print(*elements, sep="\n", file=o_file)
# Comparing
self.assertEqual(set(elements), beelinetools.read_list(list_filename))
def test_encode_genotype(self):
"""Tests the 'encode_genotypes' function."""
# The data
genotypes = ["A A", "A G", "G A", "G G", "- -"]
expected_genotypes = [0, 1, 1, 2, -1]
encoding = {"A": "A", "G": "B"}
# Testing
for expected_geno, geno in zip(expected_genotypes, genotypes):
self.assertEqual(
expected_geno,
beelinetools.encode_genotype(*geno.split(" "),
encoding=encoding),
)
def test_encode_allele(self):
"""Tests the 'encode_allele' function."""
alleles = ["A", "G", "-"]
encoding = {"G": "A", "A": "B"}
expected_alleles = ["B", "A", "-"]
for expected_allele, allele in zip(expected_alleles, alleles):
self.assertEqual(
expected_allele,
beelinetools.encode_allele(allele, encoding),
)
def test_need_complement_forward_strand(self):
"""Tests the 'need_complement' function for 'Forward' strand."""
self.assertTrue(beelinetools.need_complement("m1_T_R_23", "forward"))
self.assertFalse(beelinetools.need_complement("m1_T_F_23", "forward"))
def test_need_complement_forward_strand_invalid(self):
"""Tests 'need_complement' function for invalid 'Forward' strand."""
with self.assertRaises(ValueError) as e:
beelinetools.need_complement("m1_T_X_23", "forward")
self.assertEqual("m1_T_X_23: invalid forward value", str(e.exception))
def test_need_complement_plus_strand(self):
"""Tests the 'need_complement' function for 'Plus' strand."""
self.assertTrue(beelinetools.need_complement("-", "plus"))
self.assertFalse(beelinetools.need_complement("+", "plus"))
def test_need_complement_plus_strand_invalid(self):
"""Tests the 'need_complement' function for invalid 'Plus' strand."""
with self.assertRaises(ValueError) as e:
beelinetools.need_complement("/", "plus")
self.assertEqual("/: invalid plus value", str(e.exception))
def test_need_complement_top_strand(self):
"""Tests the 'need_complement' function for 'Top' strand."""
self.assertTrue(beelinetools.need_complement("BOT", "top"))
self.assertFalse(beelinetools.need_complement("TOP", "top"))
def test_need_complement_top_strand_invalid(self):
"""Tests the 'need_complement' function for invalid 'Top' strand."""
with self.assertRaises(ValueError) as e:
beelinetools.need_complement("foo", "top")
self.assertEqual("foo: invalid top value", str(e.exception))
def test_need_complement_invalid_strand(self):
"""Tests the 'need_complement' function."""
with self.assertRaises(ValueError) as e:
beelinetools.need_complement("foo", "foo")
self.assertEqual("foo: invalid strand", str(e.exception))
def test_check_args_strand_forward(self):
"""Tests the 'check_args' for strand 'forward' logic."""
# Creating dummy Beeline reports
beeline_reports = [
os.path.join(self.tmp_dir, "file_{}.csv".format(i + 1))
for i in range(10)
]
for filename in beeline_reports:
with open(filename, "w") as o_file:
pass
# Creating a dummy map file
map_filename = os.path.join(self.tmp_dir, "map_file.csv")
with open(map_filename, "w") as o_file:
print(
"Illumina, Inc.\n"
"[Heading]\n"
"Descriptor File Name,HumanOmni25Exome-8v1-1_A.bpm\n"
"Assay Format,Infinium LCG\n"
"Date Manufactured,4/22/2014\n"
"Loci Count ,2583651\n"
"[Assay]\n"
"IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,"
"AddressB_ID,AlleleB_ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,"
"Species,Source,SourceVersion,SourceStrand,SourceSeq,"
"TopGenomicSeq,BeadSetID,Exp_Clusters,RefStrand\n"
"Dummy_data",
file=o_file,
)
# Creating the namespace for the function
args = Namespace(
i_filenames=beeline_reports,
map_filename=map_filename,
map_delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
output_dir=self.tmp_dir,
nb_snps_kw="Num Used SNPs",
analysis_type="extract",
samples_to_keep=None,
chrom=["1", "2", "X"],
beeline_strand=None,
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
map_illumina_id="IlmnID",
map_illumina_strand="IlmnStrand",
map_ref_strand="RefStrand",
)
# Checking
beelinetools.check_args(args)
self.assertEqual("forward", args.beeline_strand)
def test_check_args_strand_top(self):
"""Tests the 'check_args' for strand 'top' logic."""
# Creating dummy Beeline reports
beeline_reports = [
os.path.join(self.tmp_dir, "file_{}.csv".format(i + 1))
for i in range(10)
]
for filename in beeline_reports:
with open(filename, "w") as o_file:
pass
# Creating a dummy map file
map_filename = os.path.join(self.tmp_dir, "map_file.csv")
with open(map_filename, "w") as o_file:
print(
"Illumina, Inc.\n"
"[Heading]\n"
"Descriptor File Name,HumanOmni25Exome-8v1-1_A.bpm\n"
"Assay Format,Infinium LCG\n"
"Date Manufactured,4/22/2014\n"
"Loci Count ,2583651\n"
"[Assay]\n"
"IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,"
"AddressB_ID,AlleleB_ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,"
"Species,Source,SourceVersion,SourceStrand,SourceSeq,"
"TopGenomicSeq,BeadSetID,Exp_Clusters,RefStrand\n"
"Dummy_data",
file=o_file,
)
# Creating the namespace for the function
args = Namespace(
i_filenames=beeline_reports,
map_filename=map_filename,
map_delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
output_dir=self.tmp_dir,
nb_snps_kw="Num Used SNPs",
analysis_type="extract",
samples_to_keep=None,
chrom=["1", "2", "X"],
beeline_strand=None,
beeline_a1="Allele1 - Top",
beeline_a2="Allele2 - Top",
map_illumina_id="IlmnID",
map_illumina_strand="IlmnStrand",
map_ref_strand="RefStrand",
)
# Checking
beelinetools.check_args(args)
self.assertEqual("top", args.beeline_strand)
def test_check_args_strand_plus(self):
"""Tests the 'check_args' for strand 'plus' logic."""
# Creating dummy Beeline reports
beeline_reports = [
os.path.join(self.tmp_dir, "file_{}.csv".format(i + 1))
for i in range(10)
]
for filename in beeline_reports:
with open(filename, "w") as o_file:
pass
# Creating a dummy map file
map_filename = os.path.join(self.tmp_dir, "map_file.csv")
with open(map_filename, "w") as o_file:
print(
"Illumina, Inc.\n"
"[Heading]\n"
"Descriptor File Name,HumanOmni25Exome-8v1-1_A.bpm\n"
"Assay Format,Infinium LCG\n"
"Date Manufactured,4/22/2014\n"
"Loci Count ,2583651\n"
"[Assay]\n"
"IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,"
"AddressB_ID,AlleleB_ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,"
"Species,Source,SourceVersion,SourceStrand,SourceSeq,"
"TopGenomicSeq,BeadSetID,Exp_Clusters,RefStrand\n"
"Dummy_data",
file=o_file,
)
# Creating the namespace for the function
args = Namespace(
i_filenames=beeline_reports,
map_filename=map_filename,
map_delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
output_dir=self.tmp_dir,
nb_snps_kw="Num Used SNPs",
analysis_type="extract",
samples_to_keep=None,
chrom=["1", "2", "X"],
beeline_strand=None,
beeline_a1="Allele1 - Plus",
beeline_a2="Allele2 - Plus",
map_illumina_id="IlmnID",
map_illumina_strand="IlmnStrand",
map_ref_strand="RefStrand",
)
# Checking
beelinetools.check_args(args)
self.assertEqual("plus", args.beeline_strand)
def test_check_args_strand_invalid(self):
"""Tests the 'check_args' for strand 'invalid' logic."""
# Creating dummy Beeline reports
beeline_reports = [
os.path.join(self.tmp_dir, "file_{}.csv".format(i + 1))
for i in range(10)
]
for filename in beeline_reports:
with open(filename, "w") as o_file:
pass
# Creating a dummy map file
map_filename = os.path.join(self.tmp_dir, "map_file.csv")
with open(map_filename, "w") as o_file:
print(
"Illumina, Inc.\n"
"[Heading]\n"
"Descriptor File Name,HumanOmni25Exome-8v1-1_A.bpm\n"
"Assay Format,Infinium LCG\n"
"Date Manufactured,4/22/2014\n"
"Loci Count ,2583651\n"
"[Assay]\n"
"IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,"
"AddressB_ID,AlleleB_ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,"
"Species,Source,SourceVersion,SourceStrand,SourceSeq,"
"TopGenomicSeq,BeadSetID,Exp_Clusters,RefStrand\n"
"Dummy_data",
file=o_file,
)
# Creating the namespace for the function
args = Namespace(
i_filenames=beeline_reports,
map_filename=map_filename,
map_delim=",",
map_id="Name",
map_chr="Chr",
map_pos="MapInfo",
map_allele="SNP",
output_dir=self.tmp_dir,
nb_snps_kw="Num Used SNPs",
analysis_type="extract",
samples_to_keep=None,
chrom=["1", "2", "X"],
beeline_strand=None,
beeline_a1="Allele1 - Plus",
beeline_a2="Allele2 - Forward",
map_illumina_id="IlmnID",
map_illumina_strand="IlmnStrand",
map_ref_strand="RefStrand",
)
# Checking
with self.assertRaises(beelinetools.ProgramError) as e:
beelinetools.check_args(args)
self.assertEqual(
"Impossible to infer the allele strand from the column names",
e.exception.message,
)
class TestBeelineToolsConvertPED(unittest.TestCase):
def setUp(self):
"""Setup the tests."""
self.tmp_dir = mkdtemp(prefix="beelinetools_test_")
# Creating the dataset
self.namespace = generate_dataset(
nb_samples=3, nb_markers=10, tmp_dir=self.tmp_dir,
)
def tearDown(self):
"""Finishes the tests."""
# Cleaning the temporary directory
shutil.rmtree(self.tmp_dir)
def _my_compatibility_assertLogs(self, logger=None, level=None):
"""Compatibility 'assertLogs' function for Python < 3.4."""
if hasattr(self, "assertLogs"):
return self.assertLogs(logger, level)
else:
return AssertLogsContext_Compatibility(self, logger, level)
def test_convert_beeline_ped(self):
"""Tests the 'convert_beeline' function."""
# Retrieving the values for the test
nb_samples = self.namespace.nb_samples
nb_markers = self.namespace.nb_markers
tmp_filename = self.namespace.tmp_filename
tmp_filename_2 = self.namespace.tmp_filename_2
mapping_info = self.namespace.mapping_info
sample_genotype = self.namespace.sample_genotype
sample_genotype_2 = self.namespace.sample_genotype_2
# Creating the namespace for the function
other_options = Namespace(
beeline_id="SNP Name",
beeline_sample="Sample ID",
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
nb_snps_kw="Num Used SNPs",
o_format="ped",
)
# Executing the function
beelinetools.convert_beeline(
i_filenames=[tmp_filename, tmp_filename_2],
out_dir=self.tmp_dir,
locations=mapping_info,
other_opts=other_options,
)
# Checking the two map files
for map_filename in (tmp_filename, tmp_filename_2):
map_filename = os.path.splitext(map_filename)[0] + ".map"
self.assertTrue(os.path.isfile(map_filename))
# Checking the first map file content
seen_markers = set()
with open(map_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
marker = "marker_{}".format(i + 1)
row = line.rstrip("\n").split("\t")
# Comparing the content of the file
self.assertTrue(marker in mapping_info)
self.assertEqual(4, len(row))
self.assertEqual(mapping_info[marker].chrom, int(row[0]))
self.assertEqual(marker, row[1])
self.assertEqual("0", row[2])
self.assertEqual(mapping_info[marker].pos, int(row[3]))
# We have compared this marker
seen_markers.add(marker)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# Checking the two ped files
zipped = zip(
(1, nb_samples + 1),
(tmp_filename, tmp_filename_2),
(sample_genotype, sample_genotype_2),
)
for sample_id_add, ped_filename, sample_geno in zipped:
ped_filename = os.path.splitext(ped_filename)[0] + ".ped"
self.assertTrue(os.path.isfile(ped_filename))
# Checking the ped file content
seen_samples = set()
with open(ped_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
sample_id = "sample_{}".format(i + sample_id_add)
row = line.rstrip("\n").split("\t")
# Checking the sample information
self.assertEqual(6 + nb_markers, len(row))
sample_info = row[:6]
self.assertEqual(
[sample_id, sample_id, "0", "0", "0", "-9"],
sample_info,
)
# Checking the genotypes
seen_markers = set()
genotypes = row[6:]
self.assertEqual(nb_markers, len(genotypes))
for j, genotype in enumerate(genotypes):
marker_id = "marker_{}".format(j + 1)
self.assertEqual(
sample_geno[i][marker_id],
genotype,
)
seen_markers.add(marker_id)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# We've seen this sample now
seen_samples.add(sample_id)
expected = {
"sample_{}".format(i + sample_id_add) for i in
range(nb_samples)
}
self.assertEqual(expected, seen_samples)
def test_convert_beeline_ped_dup_samples(self):
"""Tests the 'convert_beeline' function with duplicated samples."""
# Retrieving the values for the test
nb_samples = self.namespace.nb_samples
nb_markers = self.namespace.nb_markers
tmp_filename = self.namespace.tmp_filename
tmp_filename_2 = self.namespace.tmp_filename_2
mapping_info = self.namespace.mapping_info
sample_genotype = self.namespace.sample_genotype
sample_genotype_2 = self.namespace.sample_genotype_2
# We rename sample_2 to sample_1 in the first file
with open(tmp_filename) as f:
content = f.read()
with open(tmp_filename, "w") as f:
f.write(content.replace("sample_2", "sample_1"))
# We rename all the samples in the second file
with open(tmp_filename_2) as f:
content = f.read()
for sample in range(nb_samples):
content = content.replace(
"sample_{}".format(sample + nb_samples + 1),
"sample_{}".format(sample + 1),
)
with open(tmp_filename_2, "w") as f:
f.write(content)
# Creating the namespace for the function
other_options = Namespace(
beeline_id="SNP Name",
beeline_sample="Sample ID",
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
nb_snps_kw="Num Used SNPs",
o_format="ped",
)
# Executing the function
with self._my_compatibility_assertLogs(level="WARNING") as cm:
beelinetools.convert_beeline(
i_filenames=[tmp_filename, tmp_filename_2],
out_dir=self.tmp_dir,
locations=mapping_info,
other_opts=other_options,
)
self.assertEqual(
["WARNING:root:sample_1: duplicate sample found",
"WARNING:root:sample_1: duplicate sample found",
"WARNING:root:sample_3: duplicate sample found"],
cm.output,
)
# Checking the two map files
for map_filename in (tmp_filename, tmp_filename_2):
map_filename = os.path.splitext(map_filename)[0] + ".map"
self.assertTrue(os.path.isfile(map_filename))
# Checking the first map file content
seen_markers = set()
with open(map_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
marker = "marker_{}".format(i + 1)
row = line.rstrip("\n").split("\t")
# Comparing the content of the file
self.assertTrue(marker in mapping_info)
self.assertEqual(4, len(row))
self.assertEqual(mapping_info[marker].chrom, int(row[0]))
self.assertEqual(marker, row[1])
self.assertEqual("0", row[2])
self.assertEqual(mapping_info[marker].pos, int(row[3]))
# We have compared this marker
seen_markers.add(marker)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# Checking the two ped files
zipped = zip(
(tmp_filename, tmp_filename_2),
(sample_genotype, sample_genotype_2),
)
for file_i, (ped_filename, sample_geno) in enumerate(zipped):
ped_filename = os.path.splitext(ped_filename)[0] + ".ped"
self.assertTrue(os.path.isfile(ped_filename))
# Checking the ped file content
seen_samples = set()
with open(ped_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
sample_id = "sample_{}".format(i + 1)
if file_i == 0 and sample_id == "sample_2":
sample_id = "sample_1"
row = line.rstrip("\n").split("\t")
# Checking the sample information
self.assertEqual(6 + nb_markers, len(row))
sample_info = row[:6]
self.assertEqual(
[sample_id, sample_id, "0", "0", "0", "-9"],
sample_info,
)
# Checking the genotypes
seen_markers = set()
genotypes = row[6:]
self.assertEqual(nb_markers, len(genotypes))
for j, genotype in enumerate(genotypes):
marker_id = "marker_{}".format(j + 1)
self.assertEqual(
sample_geno[i][marker_id],
genotype,
)
seen_markers.add(marker_id)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# We've seen this sample now
seen_samples.add(sample_id)
expected = {
"sample_{}".format(i + 1) for i in
range(nb_samples)
}
if file_i == 0:
expected.discard("sample_2")
self.assertEqual(expected, seen_samples)
def test_convert_beeline_ped_dup_samples_error(self):
"""Tests the 'convert_beeline' function with duplicated samples."""
# Retrieving the values for the test
nb_markers = self.namespace.nb_markers
tmp_filename = self.namespace.tmp_filename
mapping_info = self.namespace.mapping_info
# Duplication samples and removing the last two markers of the file
marker_to_remove = {
"marker_{}".format(i + 1)
for i in range(nb_markers - 2, nb_markers)
}
with open(tmp_filename) as f:
content = f.read().splitlines()
with open(tmp_filename, "w") as f:
sample_1_content = []
for line in content:
if not line.startswith("sample_"):
print(line, file=f)
continue
sample, marker = line.split(",")[:2]
if sample == "sample_1":
sample_1_content.append(line)
print(line, file=f)
# Duplicating sample_1
for line in sample_1_content:
marker = line.split(",")[1]
if marker not in marker_to_remove:
print(line, file=f)
# Creating the namespace for the function
other_options = Namespace(
beeline_id="SNP Name",
beeline_sample="Sample ID",
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
nb_snps_kw="Num Used SNPs",
o_format="ped",
)
# Executing the function
with self.assertRaises(beelinetools.ProgramError) as e:
with self._my_compatibility_assertLogs(level="WARNING") as cm:
beelinetools.convert_beeline(
i_filenames=[tmp_filename],
out_dir=self.tmp_dir,
locations=mapping_info,
other_opts=other_options,
)
self.assertEqual(
tmp_filename + ": missing 2 markers for sample 'sample_1'",
e.exception.message,
)
self.assertEqual(
["WARNING:root:sample_1: duplicate sample found"],
cm.output,
)
def test_convert_beeline_ped_2(self):
"""Tests the 'convert_beeline' function (different nb SNPs kw)."""
# Retrieving the values for the test
nb_samples = self.namespace.nb_samples
nb_markers = self.namespace.nb_markers
tmp_filename = self.namespace.tmp_filename
tmp_filename_2 = self.namespace.tmp_filename_2
mapping_info = self.namespace.mapping_info
sample_genotype = self.namespace.sample_genotype
sample_genotype_2 = self.namespace.sample_genotype_2
# Renaming the SNP keyword
for fn in (tmp_filename, tmp_filename_2):
with open(fn) as f:
content = f.read()
with open(fn, "w") as f:
f.write(content.replace("Num Used SNPs,", "Num SNPs,"))
# Creating the namespace for the function
other_options = Namespace(
beeline_id="SNP Name",
beeline_sample="Sample ID",
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
nb_snps_kw="Num SNPs",
o_format="ped",
)
# Executing the function
beelinetools.convert_beeline(
i_filenames=[tmp_filename, tmp_filename_2],
out_dir=self.tmp_dir,
locations=mapping_info,
other_opts=other_options,
)
# Checking the two map files
for map_filename in (tmp_filename, tmp_filename_2):
map_filename = os.path.splitext(map_filename)[0] + ".map"
self.assertTrue(os.path.isfile(map_filename))
# Checking the first map file content
seen_markers = set()
with open(map_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
marker = "marker_{}".format(i + 1)
row = line.rstrip("\n").split("\t")
# Comparing the content of the file
self.assertTrue(marker in mapping_info)
self.assertEqual(4, len(row))
self.assertEqual(mapping_info[marker].chrom, int(row[0]))
self.assertEqual(marker, row[1])
self.assertEqual("0", row[2])
self.assertEqual(mapping_info[marker].pos, int(row[3]))
# We have compared this marker
seen_markers.add(marker)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# Checking the two ped files
zipped = zip(
(1, nb_samples + 1),
(tmp_filename, tmp_filename_2),
(sample_genotype, sample_genotype_2),
)
for sample_id_add, ped_filename, sample_geno in zipped:
ped_filename = os.path.splitext(ped_filename)[0] + ".ped"
self.assertTrue(os.path.isfile(ped_filename))
# Checking the ped file content
seen_samples = set()
with open(ped_filename, "r") as i_file:
for i, line in enumerate(i_file):
# Gathering the information
sample_id = "sample_{}".format(i + sample_id_add)
row = line.rstrip("\n").split("\t")
# Checking the sample information
self.assertEqual(6 + nb_markers, len(row))
sample_info = row[:6]
self.assertEqual(
[sample_id, sample_id, "0", "0", "0", "-9"],
sample_info,
)
# Checking the genotypes
seen_markers = set()
genotypes = row[6:]
self.assertEqual(nb_markers, len(genotypes))
for j, genotype in enumerate(genotypes):
marker_id = "marker_{}".format(j + 1)
self.assertEqual(
sample_geno[i][marker_id],
genotype,
)
seen_markers.add(marker_id)
self.assertEqual(set(mapping_info.keys()), seen_markers)
# We've seen this sample now
seen_samples.add(sample_id)
expected = {
"sample_{}".format(i + sample_id_add) for i in
range(nb_samples)
}
self.assertEqual(expected, seen_samples)
def test_convert_beeline_ped_error_1(self):
"""Tests the 'convert_beeline' function with missing nb markers."""
# Retrieving the values for the test
tmp_filename = self.namespace.tmp_filename
mapping_info = self.namespace.mapping_info
# Creating the namespace for the function
other_options = Namespace(
beeline_id="SNP Name",
beeline_sample="Sample ID",
beeline_a1="Allele1 - Forward",
beeline_a2="Allele2 - Forward",
nb_snps_kw="Num SNPs",
o_format="ped",
)
# Executing the function
with self.assertRaises(beelinetools.ProgramError) as e:
beelinetools.convert_beeline(
i_filenames=[tmp_filename] * 2,
out_dir=self.tmp_dir,
locations=mapping_info,
other_opts=other_options,
)
self.assertEqual(
tmp_filename + ": invalid header (missing 'Num SNPs' value)",
e.exception.message,
)
def test_convert_beeline_ped_error_2(self):
"""Tests the 'convert_beeline' function with missing marker map."""
# Retrieving the values for the test
nb_samples = self.namespace.nb_samples
nb_markers = self.namespace.nb_markers
tmp_filename = self.namespace.tmp_filename
mapping_info = self.namespace.mapping_info
sample_genotype = self.namespace.sample_genotype
# Removing mapping information for marker_3
del mapping_info["marker_3"]