-
Notifications
You must be signed in to change notification settings - Fork 1
/
io_file.py
executable file
·1930 lines (1705 loc) · 65.3 KB
/
io_file.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 segment
import snp_ssm
import cnv
import constants as cons
import exceptions_onctopus as eo
import os.path
import lineage
import submarine
import itertools
import numpy as np
import logging
import os
import random
import json
# defined functions in this file
# def parse_vcf_file_for_onctopus(input_file_name, output_file_name, test):
# def write_CPLEX_results_to_result_file(file_name, opt, snp_list, ssm_list, seg_list):
# def get_CNV_lines_from_CPLEX(opt, seg_list, start_index):
# def get_SSM_lines_from_CPLEX(opt, ssm_list, start_index):
# def get_SNP_line_from_CPLEX(opt, snp_list, start_index):
# def read_result_file(file_name):
# def store_results(tag, my_lineage, line_part):
# def get_sublineages_list_from_result_file(line_part):
# def get_CNV_list_from_result_file(line_part):
# def get_SNP_SSM_list_from_result_file(line_part):
# def read_segment_file(file_name):
# def read_snp_ssm_file(file_name, mut_type):
# def raise_if_file_exists(file_name):
# def raise_if_file_not_exists(file_name):
# def write_segment_file(reads_total, seg_start, seg_end, segment_number, mass, file_name, no_test):
# def write_single_muts_file(reads_total, lineages, seg_start, segment_number, file_name_snp, file_name_ssm, no_test):
# def get_sublineages_line(sublins):
# def get_end_of_mutation_line(line, mut, lin, pha, segment_number, seg_start, seg_end):
# def write_simulation_results(seg_start, seg_end, lineages, segment_number, file_name, no_test):
# def write_simulation_info(lineages_file, segment_number, snp_number, ssm_number, cnv_number,
# def read_lineages_tree(file_name, segment_number):
# def read_mutation_assignments(file_name)
# def str_to_bool(s):
# def str_possibly_to_none(s):
# def check_duplicates(chr_pos_list):
# def create_fixed_segments_all_but_one(result_file, output_prefix, cn_state_num=2, test=False):
# def create_fixed_CNV_data(result_file, cn_state_num):
# def create_fixed_SNPs_data(result_file):
# def create_fixed_SSMs_data(result_file):
# def create_fixed_Z_data(result_file):
# def create_fixed_frequencies_data(result_file):
# def read_fixed_value_file(fixed_file):
# def write_fixed_value_file(data, output_file, row_num, column_num, info, unfixed_segment = -1, unfixed_start = -1, unfixed_stop = -1, file_type=None, test=False):
# def visualize_result_file(result_file, output_file=None, test=False):
def read_parent_vector(my_file):
lins_parents = []
first_line = True
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
lins_parents.append(list(map(int,line.rstrip().split("\t"))))
parents = [p[1] for p in sorted(lins_parents, key=lambda x: x[0])]
return parents
def read_frequencies(my_file, return_ids=False, ordering_given=True):
lins_freqs = []
first_line = True
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
lins = int(line.split("\t")[0])
freqs = list(map(float, line.rstrip().split("\t")[1:]))
lins_freqs.append([lins, freqs])
if ordering_given:
freqs = [f[1] for f in sorted(lins_freqs, key=lambda x: x[0])]
else:
freqs = [f[1] for f in lins_freqs]
if return_ids == False:
return freqs
if ordering_given == False:
return freqs, [str(f[0]) for f in lins_freqs]
raise eo.MyException("nothing returned here")
def write_new_ssm_phasing(ssm_phasing, output_file, overwrite=False):
if overwrite == False:
raise_if_file_exists(output_file)
with open(output_file, "w") as f:
f.write("SSM_index\tphase\n")
for current_ssm in ssm_phasing:
if current_ssm[1] == cons.A:
phase = "A"
elif current_ssm[1] == cons.B:
phase = "B"
else:
phase = 0
f.write("{0}\t{1}\n".format(current_ssm[0], phase))
def read_cnas(my_file, sorting_id_mapping=None, use_cna_indices=False, lin_num=-1):
my_cnas = []
first_line = True
cna_index_count = 0
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
if use_cna_indices is False:
seg_index, chromosome, start, end, lineage, phase, change = line.rstrip().split("\t")
else:
entries = line.rstrip().split("\t")
if len(entries) == 5:
cna_index, seg_index, lineage, phase, change = entries
chromosome = -1
start = -1
end = -1
else:
cna_index, seg_index, lineage, phase, change, chromosome, start, end = entries
if int(cna_index) != cna_index_count:
raise eo.MyException("CNAs have to be sorted in order of their indices, indices must go from "
"0 to L-1, where L is the total number of CNAs.")
cna_index_count += 1
cna = cnv.CNV(int(change), int(seg_index), int(chromosome), int(start), int(end))
if int(change) < -1:
raise eo.MyException("Loss cannot be smaller than -1 because of monotonicity restriction.")
if use_cna_indices:
cna.index = int(cna_index)
if phase == "A":
cna.phase = cons.A
elif phase == "B":
cna.phase = cons.B
else:
raise eo.MyException("undefined phase for CNA")
if sorting_id_mapping is None:
cna.lineage = int(lineage)
else:
try:
cna.lineage = sorting_id_mapping[lineage]
except KeyError:
raise eo.MyException("Subclone ID {0} wasn't used in frequency matrix".format(lineage))
if lin_num != -1:
if cna.lineage >= lin_num:
raise eo.MyException("CNA cannot be assign to subclone {0}. Only {1} subclones given.".format(
cna.lineage, lin_num))
my_cnas.append(cna)
return my_cnas
def get_SSM_constraints(userSSM_file=None, my_ssms=None):
ssm_num = len(my_ssms)
first_line = True
with open(userSSM_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
index, phase = line.rstrip().split("\t")
index = int(index)
if index >= ssm_num:
raise eo.MyException("User SSM constraints cannot be used. No SSM with index {0} "
"exists.".format(index))
# get user phase
if phase == "A":
phase = cons.A
elif phase == "B":
phase = cons.B
else:
raise eo.MyException("Phase type {0} for SSM {1} is invalid".format(phase, index))
# SSM has no phasing yet
if my_ssms[index].phase is None:
my_ssms[index].phase = phase
elif my_ssms[index].phase != phase:
raise eo.MyException("According to CNA impact, SSM {0} must have phase {1}. This contradicts with "
"user constraint for phase {2}".format(index, my_ssms[index].phase, phase))
def create_impact_matrix(impact_file=None, cna_num=-1, ssm_num=-1):
# either no CNAs or SSMs exist, or no impact file is given
if impact_file is None or cna_num == -1 or ssm_num == -1:
return None
# create empty impact matrix
impact_matrix = np.zeros(ssm_num*cna_num).reshape(ssm_num, cna_num)
# read impact file and update matrix
first_line = True
with open(impact_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
entries = line.rstrip().split("\t")
if entries != [] and entries != [""]:
ssm_index, cna_index = map(int, entries)
if cna_index >= cna_num:
raise eo.MyException("CNA index {0} is too high.".format(cna_index))
if ssm_index >= ssm_num:
raise eo.MyException("SSM index {0} is too high.".format(ssm_index))
impact_matrix[ssm_index][cna_index] = 1
return impact_matrix
def read_ssms(my_file, phasing=True, sorting_id_mapping=None, use_SSM_index=False, lin_num=-1):
my_ssms = []
first_line = True
ssm_index_count = 0
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
if phasing == True:
seg_index, chromosome, pos, lineage, phase, cna_infl_same_lineage = line.rstrip().split("\t")
elif use_SSM_index == False:
seg_index, chromosome, pos, lineage = line.rstrip().split("\t")
else:
entries = line.rstrip().split("\t")
if len(entries) == 3:
ssm_index, seg_index, lineage = entries
chromosome = -1
(pos) = -1
else:
ssm_index, seg_index, lineage, chromosome, pos = entries
if int(ssm_index) != ssm_index_count:
raise eo.MyException("SSMs have to be sorted in order of their indices, indices must go from "
"0 to J-1, where J is the total number of SSMs.")
ssm_index_count += 1
ssm = snp_ssm.SSM()
ssm.chr = int(chromosome)
ssm.pos = int(pos)
ssm.seg_index = int(seg_index)
if use_SSM_index:
ssm.index = int(ssm_index)
if phasing == True:
if cna_infl_same_lineage == "0":
ssm.infl_cnv_same_lin = False
elif cna_infl_same_lineage == "1":
ssm.infl_cnv_same_lin = True
else:
raise eo.MyException("undefined state for SSM")
if phase == "A":
ssm.phase = cons.A
elif phase == "B":
ssm.phase = cons.B
elif phase == "0":
ssm.phase = cons.UNPHASED
else:
raise eo.MyException("undefined phase for SSM")
if sorting_id_mapping is None:
ssm.lineage = int(lineage)
else:
try:
ssm.lineage = int(sorting_id_mapping[lineage])
except KeyError:
raise eo.MyException("Subclone ID {0} is used for SSMs but wasn't defined in frequency matrix.".format(
lineage))
if lin_num != -1:
if ssm.lineage >= lin_num:
raise eo.MyException("SSM cannot be assign to subclone {0}. Only {1} subclones given.".format(
ssm.lineage, lin_num))
my_ssms.append(ssm)
return my_ssms
def read_userZ(my_file, lin_num, sorting_id_mapping=None):
z_matrix = np.zeros(lin_num*lin_num).reshape(lin_num,lin_num)
first_line = True
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
k, kp, v = list(map(int, line.rstrip().split("\t")))
if sorting_id_mapping is not None:
k = sorting_id_mapping[str(k)]
kp = sorting_id_mapping[str(kp)]
if v == 1:
z_matrix[k][kp] = 1
elif v == 0:
z_matrix[k][kp] = -1
else:
raise eo.MyException("undefined relationship")
return z_matrix
def read_userSSM(my_file, lin_num, seg_num):
tmp_user_ssm = [[False] * lin_num for i in range(3)]
user_ssm = [tmp_user_ssm for i in range(seg_num)]
first_line = True
with open(my_file, "r") as f:
for line in f:
if first_line:
first_line = False
continue
seg_index, phase, lineage = line.rstrip().split("\t")
if phase == "A":
phase = cons.A
elif phase == "B":
phase = cons.B
else:
raise eo.MyException("phase undefined")
user_ssm[int(seg_index)][phase][int(lineage)] = True
return user_ssm
def print_ssm_phasing(my_lins, output_file, overwrite=False):
if overwrite == False:
raise_if_file_exists(output_file)
my_ssms = []
for k in range(1, len(my_lins)):
get_ssm_information(my_lins[k].ssms, my_ssms)
get_ssm_information(my_lins[k].ssms_a, my_ssms)
get_ssm_information(my_lins[k].ssms_b, my_ssms)
my_ssms = sorted(my_ssms, key=lambda x: (x[0], x[1], x[2]))
with open(output_file, "w") as f:
f.write("seg_index\tchr\tpos\tlineage\tphase\tcna_infl_same_lineage\n")
for ssm in my_ssms:
f.write("{0}\n".format("\t".join(list(map(str, ssm)))))
def get_ssm_information(ssm_list, info_list):
for ssm in ssm_list:
if ssm.phase == cons.A:
phase = "A"
elif ssm.phase == cons.B:
phase = "B"
else:
phase = 0
if ssm.infl_cnv_same_lin:
cna_infl_same_lineage = 1
else:
cna_infl_same_lineage = 0
info_list.append([ssm.seg_index, ssm.chr, ssm.pos, ssm.lineage, phase, cna_infl_same_lineage])
return info_list
# parses a VCF file into a file Onctopus can read
# TODO old function, do I really need it?
def parse_vcf_file_for_onctopus(input_file_name, output_file_name, test):
#open VCF-File as Reader
vcf_reader= vcf.Reader(open(input_file_name,"r"))
#open output as Writer if file doesn't exist (in a non test case)
output = None
if not test:
raise_if_file_exists(output_file_name)
output=open(output_file_name,"w")
else:
output=open(output_file_name,"w")
#clear outputfile
output.truncate()
#write chrom, pos, variance count and reference count in outputfile
for record in vcf_reader:
output.write((record.CHROM.split("chr")[1]))
output.write("\t")
output.write(str(record.POS))
output.write("\t")
#get last field of tumour entry
sample=record.samples[0].data[1]
output.write(str(sample[1]))
output.write("\t")
output.write(str(sample[0]))
output.write("\n")
output.close()
# reads a vcf file
# slightly modified from https://github.com/morrislab/phylowgs/blob/master/
# parser/create_phylowgs_inputs.py
def read_vcf_file(input_file_name):
vcf_reader = vcf.Reader(filename=input_file_name)
records = []
for variant in vcf_reader:
variant.CHROM = variant.CHROM.upper()
# Some VCF dialects prepend "chr", some don't. Remove the prefix to
# standardize.
if variant.CHROM.startswith('CHR'):
variant.CHROM = variant.CHROM[3:]
records.append(variant)
return records
# variants: vcf object
# output_file_name: path where to write file for Onctopus
# gets vcf object and parses it to new file that is in a format that Onctopus expects
def create_onctopus_SSM_file_from_vcf_record(variants, output_file_name, test=False):
#open output as Writer if file doesn't exist (in a non test case)
output = None
if not test:
raise_if_file_exists(output_file_name)
output=open(output_file_name,"w")
else:
output=open(output_file_name,"w")
#clear outputfile
output.truncate()
# write sigle variants to file
for i, variant in enumerate(variants):
try:
create_onctopus_SSM_line_from_variant_record(variant, output)
except eo.ReadCountsUnavailableError as exc:
logging.info("Variant {0} not added to Onctopus because of following error: {1}".format(
i, exc))
output.close()
# variant: vcf variant entry
# output: output stream
# parses information from variant entry and writes it to line in format
# that Onctopus expects: "chr \t pos \t var_count \t ref_count"
# modified from https://github.com/morrislab/phylowgs/blob/master/
# parser/create_phylowgs_inputs.py
def create_onctopus_SSM_line_from_variant_record(variant, output):
if not ('t_alt_count' in variant.INFO and 't_ref_count' in variant.INFO):
raise eo.ReadCountsUnavailableError("\'t_alt_count\' or \'t_ref_count\' don't exist.")
# multiple entries for alternative and variant count
single_entry = False
try:
len(variant.INFO['t_alt_count'])
except TypeError:
single_entry = True
if single_entry == False:
assert len(variant.INFO['t_alt_count']) == len(variant.INFO['t_ref_count']) == 1
else:
assert type(variant.INFO['t_ref_count']) is int
# get fields
chromosome = variant.CHROM
position = variant.POS
if single_entry == False:
alt_reads = int(variant.INFO['t_alt_count'][0])
ref_reads = int(variant.INFO['t_ref_count'][0])
else:
alt_reads = variant.INFO['t_alt_count']
ref_reads = variant.INFO['t_ref_count']
# Some variants havezero alt and ref reads.
if alt_reads + ref_reads == 0:
raise eo.ReadCountsUnavailableError("No reads for variant.")
# write line
output.write("{0}\t{1}\t{2}\t{3}\n".format(chromosome, position, alt_reads, ref_reads))
# writes an SSM file in the format Onctopus needs as input
def write_onctopus_ssm_file(file_name, ssm_list, test=False):
if not test:
raise_if_file_exists(file_name)
output_file = open(file_name, 'w')
for ssm in ssm_list:
output_file.write("{0}\t{1}\t{2}\t{3}\n".format(ssm.chr, ssm.pos,
ssm.variant_count, ssm.ref_count))
output_file.close()
# get a list of lineages objects and writes them to a result file
def write_lineages_to_result_file(file_name, my_lineages, test=False):
if not test:
raise_if_file_exists(file_name)
result_file = open(file_name, 'w')
for i in range(len(my_lineages)):
result_file.write("@\n")
result_file.write("LINEAGE: {0}\n".format(i))
freq_index = my_lineages[i].freq
result_file.write("FREQUENCY: {0:.25f}\n".format(my_lineages[i].freq))
result_file.write("SUBLINEAGES: {0}\n".format(";".join(str(s) for s in
my_lineages[i].sublins)))
# normal lineage
if i == 0:
# SNPs are written
snps_line = get_SNP_line_from_lineage(my_lineages[0].snps)
result_file.write("SNPS: {0}\n".format(snps_line))
snps_a_line = get_SNP_line_from_lineage(my_lineages[0].snps_a)
result_file.write("SNPS_A: {0}\n".format(snps_a_line))
snps_b_line = get_SNP_line_from_lineage(my_lineages[0].snps_b)
result_file.write("SNPS_B: {0}\n".format(snps_b_line))
# no SSMs appear in normal lineage
result_file.write("SSMS: \nSSMS_A: \nSSMS_B: \nCNVS_A: {0}\nCNVS_B: \n".format(
";".join(get_CNV_lines_from_lineages(my_lineages[cons.NORMAL].cnvs_a))))
# not the normal lineage
else:
# no SNPs appear in sublineages
result_file.write("SNPS: \nSNPS_A: \nSNPS_B: \n")
# write mutation of sublineages
ssms_line = get_SSM_lines_from_lineages(my_lineages[i].ssms)
result_file.write("SSMS: {0}\n".format(";".join(ssms_line)))
ssms_a_line = get_SSM_lines_from_lineages(my_lineages[i].ssms_a)
result_file.write("SSMS_A: {0}\n".format(";".join(ssms_a_line)))
ssms_b_line = get_SSM_lines_from_lineages(my_lineages[i].ssms_b)
result_file.write("SSMS_B: {0}\n".format(";".join(ssms_b_line)))
cnvs_a_line = get_CNV_lines_from_lineages(my_lineages[i].cnvs_a)
result_file.write("CNVS_A: {0}\n".format(";".join(cnvs_a_line)))
cnvs_b_line = get_CNV_lines_from_lineages(my_lineages[i].cnvs_b)
result_file.write("CNVS_B: {0}\n".format(";".join(cnvs_b_line)))
result_file.close()
# given a list with segments, formats them in a line that is written to a result file
def get_CNV_lines_from_lineages(cnv_list):
cnvs_line = []
for i in range(len(cnv_list)):
state = ""
if cnv_list[i].change >= 1:
state = "+{0}".format(str(cnv_list[i].change))
elif cnv_list[i].change == -1:
state = "-1"
elif cnv_list[i].change == 0:
state = "0"
cnvs_line.append("{4},{0},{1},{2},{3}".format(cnv_list[i].seg_index, cnv_list[i].chr, cnv_list[i].start,
cnv_list[i].end, state))
return cnvs_line
# given a list with with SSMs, formats them in a line that is written to a result file
def get_SSM_lines_from_lineages(ssm_list):
ssms_line = []
for i in range(len(ssm_list)):
current_ssm = ("{0},{1},{2}".format(ssm_list[i].seg_index,
ssm_list[i].chr, ssm_list[i].pos))
# if SSM is influenced by CN gain in same lineage, the phase of the gain is added
try:
if ssm_list[i].infl_cnv_same_lin == True:
current_ssm += ",infl"
except AttributeError:
pass
ssms_line.append(current_ssm)
return ssms_line
# given a list with with SNPs, formats them in a line that is written to a result file
def get_SNP_line_from_lineage(snp_list):
snps = []
for i in range(len(snp_list)):
snps.append("{0},{1},{2}".format(snp_list[i].seg_index, snp_list[i].chr,
snp_list[i].pos))
return ';'.join(snps)
###########################################################################################
############################ read_result_file ###########################################
# result file is read
# '@' marks the start of a new lineage
# each other row starts with an idenifier, according to this identifier the line is split
# at the delimiter character ';' and according to the type of information in the
# row (SNP, SSM, CNV) the information is further parsed and saved in corresponding
# objects (snp_ssm.SNP_SSM, segment.Segment) that are then put in a list
# for the actual lineage
# phasing_not_known: if I don't know about the phasing of the SSMs because I used a different method than
# Onctopus
def read_result_file(file_name, phasing_not_known=False):
lineages_list = []
with open(file_name) as f:
my_lineage = None
lineage_index = 0
for line in f:
split_line = line.rstrip("\n").split(":")
tag = split_line[0]
#print tag
if tag.startswith("@"):
# lineage is stored in list
if my_lineage is not None:
lineages_list.append(my_lineage)
lineage_index += 1
#print "new lineage"
my_lineage = lineage.Lineage([], -1, [], [], [], [], [],
[], [], [])
else:
# split_line[1] is information about mutations/frequency/sublins stored in line
store_results(tag, my_lineage, split_line[1], phasing_not_known, lineage_index)
# store last lineage in list
lineages_list.append(my_lineage)
return lineages_list
# phasing_not_known: if I don't know about the phasing of the SSMs because I used a different method than
# Onctopus
def store_results(tag, my_lineage, line_part, phasing_not_known, lineage_index):
line_part=line_part.lstrip()
if tag == "LINEAGE":
pass
elif tag == "FREQUENCY":
my_lineage.freq = float(line_part)
elif tag == "SUBLINEAGES":
my_lineage.sublins=get_sublineages_list_from_result_file(line_part)
elif tag == "SNPS":
my_lineage.snps = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SNP)
elif tag == "SNPS_A":
my_lineage.snps_a = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SNP)
elif tag == "SNPS_B":
my_lineage.snps_b = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SNP)
elif tag == "SSMS":
my_lineage.ssms = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SSM,
phasing_not_known=phasing_not_known, phase=cons.UNPHASED, lineage_index=lineage_index)
elif tag == "SSMS_A":
my_lineage.ssms_a = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SSM,
phasing_not_known=phasing_not_known, phase=cons.A, lineage_index=lineage_index)
elif tag == "SSMS_B":
my_lineage.ssms_b = get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SSM,
phasing_not_known=phasing_not_known, phase=cons.B, lineage_index=lineage_index)
elif tag == "CNVS_A":
my_lineage.cnvs_a = get_CNV_list_from_result_file(line_part, cons.A)
elif tag == "CNVS_B":
my_lineage.cnvs_b = get_CNV_list_from_result_file(line_part, cons.B)
def write_result_file(lineages, file_name, test=False):
#test, if output file exists
if not test:
raise_if_file_exists(file_name)
with open(file_name, 'w') as f:
#clear file in testcase
if test:
f.truncate()
for lin_num, lineage in enumerate(lineages):
# set all entries to valid type, if they were None
if lineage.freq == None:
lineage.freq = 0.0
if lineage.sublins == None:
lineage.sublins = []
if lineage.snps == None:
lineage.snps = []
if lineage.snps_a == None:
lineage.snps_a = []
if lineage.snps_b == None:
lineage.snps_b = []
if lineage.ssms == None:
lineage.ssms = []
if lineage.ssms_a == None:
lineage.ssms_a = []
if lineage.ssms_b == None:
lineage.ssms_b = []
if lineage.cnvs_a == None:
lineage.cnvs_a = []
if lineage.cnvs_b == None:
lineage.cnvs_b = []
#write file
f.write("@\n")
f.write("LINEAGE: {0}\n".format(lin_num))
f.write("FREQUENCY: {0:.5f}\n".format(lineage.freq))
#SUBLINEAGES
f.write("SUBLINEAGES: ")
# every entry after the first needs ',' as seperator
for num, sublin in enumerate(lineage.sublins):
if num == 0:
f.write(str(sublin))
else:
f.write(";{0}".format(sublin))
# new line
f.write("\n")
#SNPS
f.write("SNPS: ")
for num, snp in enumerate(lineage.snps):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
else:
f.write(";{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
# new line
f.write("\n")
#SNPS_A
f.write("SNPS_A: ")
for num, snp in enumerate(lineage.snps_a):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
else:
f.write(";{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
# new line
f.write("\n")
#SNPS_B
f.write("SNPS_B: ")
for num, snp in enumerate(lineage.snps_b):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
else:
f.write(";{0},{1},{2}".format(snp.seg_index, snp.chr, snp.pos))
# new line
f.write("\n")
#SSMS
f.write("SSMS: ")
for num, ssm in enumerate(lineage.ssms):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
else:
f.write(";{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
# new line
f.write("\n")
#SSMS_A
f.write("SSMS_A: ")
for num, ssm in enumerate(lineage.ssms_a):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
else:
f.write(";{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
# new line
f.write("\n")
#SSMS_B
f.write("SSMS_B: ")
for num, ssm in enumerate(lineage.ssms_b):
# every entry after the first needs ';' as seperator
if num == 0:
f.write("{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
else:
f.write(";{0},{1},{2}".format(ssm.seg_index, ssm.chr, ssm.pos))
# new line
f.write("\n")
#CNVS_A
f.write("CNVS_A: ")
for num, cnv in enumerate(lineage.cnvs_a):
# every entry after the first needs ';' as seperator
if num == 0:
#+1 change needs extra character +
if cnv.change == 1:
f.write("+{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
f.write("{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
if cnv.change == 1:
f.write(";+{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
f.write(";{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
# new line
f.write("\n")
#CNVS_B
f.write("CNVS_B: ")
for num, cnv in enumerate(lineage.cnvs_b):
# every entry after the first needs ';' as seperator
if num == 0:
#+1 change needs extra character +
if cnv.change == 1:
f.write("+{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
f.write("{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
if cnv.change == 1:
f.write(";+{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
else:
f.write(";{0},{1},{2},{3},{4}".format(cnv.change,
cnv.seg_index, cnv.chr, cnv.start, cnv.end))
# new line
f.write("\n")
# write the lineages list to JSON file
def write_result_file_as_JSON(lineages, file_name, test=False):
#test, if output file exists
if not test:
raise_if_file_exists(file_name)
# create serializable structure
seri = [my_lin.create_dict() for my_lin in lineages]
# write to file
with open(file_name, "w") as f:
json.dump(seri, f)
# reads a result file in json formate and returns a list of lineages
def read_JSON_result_file(file_name):
with open(file_name, "r") as f:
lineages_json = json.load(f)
my_lineages = []
for lin in lineages_json:
ssms = [create_ssm_from_json_dump(current_ssm) for current_ssm in lin["ssms"]]
ssms_a = [create_ssm_from_json_dump(current_ssm) for current_ssm in lin["ssms_a"]]
ssms_b = [create_ssm_from_json_dump(current_ssm) for current_ssm in lin["ssms_b"]]
cnvs_a = [create_cnv_from_json_dump(current_cnv) for current_cnv in lin["cnvs_a"]]
cnvs_b = [create_cnv_from_json_dump(current_cnv) for current_cnv in lin["cnvs_b"]]
my_lineages.append(lineage.Lineage(lin["sublins"], lin["freq"], cnvs_a, cnvs_b, [], [], [],
ssms, ssms_a, ssms_b))
return my_lineages
# given the information of an CNV object in a dictionary, create an CNV object
def create_cnv_from_json_dump(cnv_dict):
my_cnv = cnv.CNV(cnv_dict["change"], cnv_dict["seg_index"], cnv_dict["chr"], cnv_dict["start"], cnv_dict["end"])
my_cnv.phase = cnv_dict["phase"]
return my_cnv
# given the information of an SSM object in a dictionary, create an SSM object
def create_ssm_from_json_dump(ssm_dict):
my_ssm = snp_ssm.SSM()
my_ssm.chr = ssm_dict["chr"]
my_ssm.pos = ssm_dict["pos"]
my_ssm.variant_count = ssm_dict["variant_count"]
my_ssm.seg_index = ssm_dict["seg_index"]
my_ssm.infl_cnv_same_lin = ssm_dict["infl_cnv_same_lin"]
my_ssm.phase = ssm_dict["phase"]
my_ssm.lineage = ssm_dict["lineage"]
return my_ssm
def get_sublineages_list_from_result_file(line_part):
if line_part == "":
return []
sublins=line_part.split(";")
return list(map(int,sublins))
def get_CNV_list_from_result_file(line_part, phase=-1):
cnv_list = []
if line_part == "":
return cnv_list
cnvs = line_part.split(";")
for i in range(len(cnvs)):
(change, seg_index, chr, start, end) = cnvs[i].split(",")
cnv_list.append(cnv.CNV(int(change), int(seg_index), int(chr), int(start), int(end)))
cnv_list[-1].phase = phase
return cnv_list
# phasing_not_known: if I don't know about the phasing of the SSMs because I used a different method than Onctopus
def get_SNP_SSM_list_from_result_file(line_part, my_type=cons.SSM, phasing_not_known=False, phase=None,
lineage_index=-1):
snp_list = []
if line_part == "":
return snp_list
snps = line_part.split(";")
for i in range(len(snps)):
if my_type == cons.SSM:
snp_ssm_object = snp_ssm.SSM()
else:
snp_ssm_object = snp_ssm.SNP()
# to store influence of CN gain in same lineage
infl = None
try:
(seg_index, chr, pos) = snps[i].split(",")
except ValueError:
# influence of CN gain in same lineage is also stored in result file
(seg_index, chr, pos, infl) = snps[i].split(",")
snp_ssm_object.chr = int(chr)
snp_ssm_object.pos = int(pos)
snp_ssm_object.seg_index = int(seg_index)
# if influence of CN gain in same lineage exists, it is stored
if infl is not None:
snp_ssm_object.infl_cnv_same_lin = True
# if phasing information about the SSM is known, set it
if phasing_not_known == False:
snp_ssm_object.phase = phase
# set lineage index
snp_ssm_object.lineage = lineage_index
snp_list.append(snp_ssm_object)
return snp_list
# given a lineage file (input_file) a new lineage file (output_file) is created
# that contains only those mutations that appear on the segment with index seg_index
def create_result_file_for_seg_x(input_file, output_file, seg_index, test=False):
# read result file
my_lins = read_result_file(input_file)
# only use SSMs and CNVs that are in right segment
for lin in my_lins:
lin.cnvs_a = get_mutations_for_seg_x(lin.cnvs_a, seg_index)
lin.cnvs_b = get_mutations_for_seg_x(lin.cnvs_b, seg_index)
lin.ssms = get_mutations_for_seg_x(lin.ssms, seg_index)
lin.ssms_a = get_mutations_for_seg_x(lin.ssms_a, seg_index)
lin.ssms_b = get_mutations_for_seg_x(lin.ssms_b, seg_index)
# write result file
write_result_file(my_lins, output_file, test=test)
def get_mutations_for_seg_x(mutations, seg_index):
new_mutations = []
for mut in mutations:
if mut.seg_index == seg_index:
new_mutations.append(mut)
return new_mutations
############################ read_result_file ###########################################
###########################################################################################
def read_segment_file(file_name, allele_specific=False):
segment_list = []
with open(file_name) as f:
for line in f:
if allele_specific:
(chr, start, end, given_cn_A, standard_error_A, given_cn_B,
standard_error_B) = (line.rstrip()).split('\t')
# check that CN of A is bigger equal CN of B, if not, swap
if given_cn_A < given_cn_B:
(given_cn_A, standard_error_A, given_cn_B, standard_error_B) = (
given_cn_B, standard_error_B, given_cn_A, standard_error_A)
logging.info("CN A needs to be larger or equal than CN B. Swapping "
"CNs for line: {0}".format(line.rstrip()))
segment_list.append(segment.Segment_allele_specific(int(chr),
int(start), int(end), float(given_cn_A),
float(standard_error_A), float(given_cn_B),
float(standard_error_B)))
else:
(chr, start, end, c, hm) = (line.rstrip()).split('\t')
segment_list.append(segment.Segment(int(chr), int(start),
int(end), float(c), float(hm)))
return segment_list
def read_snp_ssm_file(file_name, mut_type):
mut_list = []
with open(file_name) as f:
for line in f:
(chr, pos, c1, c2) = (line.rstrip()).split('\t')
mut = snp_ssm.SNP()
if (mut_type == cons.SSM):
mut = snp_ssm.SSM()
mut.set_all_but_seg_index(int(chr), int(pos), int(c1), int(c2))
mut_list.append(mut)
return mut_list
def raise_if_file_exists(file_name):
if os.path.isfile(file_name):
error = "File {0} does already exist.\n".format(file_name)
raise(eo.FileExistsException(error))
return True
def raise_if_file_not_exists(file_name):
if not os.path.isfile(file_name):
error = "File {0} does not exist.\n".format(file_name)
raise(eo.FileDoesNotExistException(error))
return True
# for the simulation of data
def write_segment_file(reads_total, seg_start, seg_end, segment_number, mass, file_name, no_test):
chr = 1
if no_test:
raise_if_file_exists(file_name)
with open(file_name, 'w') as f:
for seg in range(segment_number):
start = seg_start[seg]
end = seg_end[seg]
line = "{0}\t{1}\t{2}\t{3}\t{4}\n".format(chr, start, end, reads_total[seg], mass[seg])
f.write(line)
# for the simulation of data
def write_segment_file_allele_specific(seg_start, seg_end, segment_number, cn_A, cn_B,
standard_error_A, standard_error_B, file_name, no_test):
chr = 1
if no_test:
raise_if_file_exists(file_name)
with open(file_name, 'w') as f:
for seg in range(segment_number):
start = seg_start[seg]
end = seg_end[seg]
line = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n".format(chr, start, end, cn_A[seg],
standard_error_A[seg], cn_B[seg], standard_error_B[seg])
f.write(line)
# write file from segments
def write_segment_file_allele_specific_from_segments(segments, file_name):
raise_if_file_exists(file_name)
with open(file_name, 'w') as f:
for seg in segments:
line = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n".format(seg.chr, seg.start, seg.end, seg.given_cn_A,
seg.standard_error_A, seg.given_cn_B, seg.standard_error_B)
f.write(line)
#for the simulation of data
# in allele-specific CN case, SNPs are not used
def write_single_muts_file(reads_total, lineages, seg_start, segment_number, file_name_snp, file_name_ssm,
no_test, allele_specific=False):
chr = 1
if no_test:
if not allele_specific:
raise_if_file_exists(file_name_snp)
raise_if_file_exists(file_name_ssm)
if not allele_specific: