-
Notifications
You must be signed in to change notification settings - Fork 1
/
submarine.py
executable file
·4617 lines (4068 loc) · 203 KB
/
submarine.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 sys
import argparse
import exceptions_onctopus as eo
import math
import lineage
import io_file as oio
import numpy as np
import copy
import constants as cons
import operator
import cnv
import logging
import numpy as np
from sklearn.cluster import KMeans
from sklearn.cluster import AgglomerativeClustering
import snp_ssm
import segment
import copy
from itertools import compress
import json
def from_files_is_tree_contained_in_partial_clone_tree(ppm_file=None, z_matrix_file=None, complete_tree_file=None, lin_file=None,
log_file=None, cna_file=None, ssm_file=None, noise_buffer_file=None):
# get ppm data, Z-matrix, lineages, CNAs, SSMs, number of segments, noise buffer
ppm, z_matrix, converted_matrix, my_lins, seg_num, noise_buffer = read_ppm_zmatrix_and_more(ppm_file,
z_matrix_file, lin_file, cna_file, ssm_file, noise_buffer_file)
# get ID mapping from log file
sorting_id_mapping = oio.get_ID_mapping_from_log_file(log_file)
# get complete tree
tree_z = oio.read_matrix_from_file(complete_tree_file)
if tree_z[0][0] == 0:
tree_z = convert_zmatrix_0_m1(tree_z)
# check whether tree is contained in Z matrix
return is_tree_contained_in_partial_clone_tree(z_matrix, my_lins, ppm, tree_z,
sorting_id_mapping, seg_num=seg_num, noise_buffer=noise_buffer)
# sorting_id_mapping[ID] = subclonal index
# unless a reverse mapping is used
def sort_z_matrix_according_ID_mapping(z_matrix, sorting_id_mapping):
lin_num = len(z_matrix[0])
# create new Z matrix
new_z_matrix = [[-1] * lin_num for x in range(lin_num)]
# go through old Z matrix
for k in range(1, lin_num):
new_z_matrix[0][k] = 1
for kp in range(1, lin_num):
if z_matrix[k][kp] == 1:
new_z_matrix[sorting_id_mapping[k]][sorting_id_mapping[kp]] = 1
elif z_matrix[k][kp] == 0:
new_z_matrix[sorting_id_mapping[k]][sorting_id_mapping[kp]] = 0
return new_z_matrix
# given a partial clone tree in z_matrix, does it contain the complete tree tree_z?
# sorting_id_mapping[ID] = subclonal index
def is_tree_contained_in_partial_clone_tree(z_matrix, my_lineages, ppm, tree_z,
sorting_id_mapping, seg_num=0, noise_buffer=0):
lin_num = len(my_lineages)
# sort tree_z according to sorting_id_mapping, meaning that the true tree is sorted
# according to the used subclonal indices of the inferred partial clone tree
tree_z = sort_z_matrix_according_ID_mapping(tree_z, sorting_id_mapping)
# check lower triangle of resorted tree_z to contain "1" values
for k in range(lin_num):
for kp in range(k):
# if "1"s are contained, the complete tree is not contained in the partial clone tree
if tree_z[k][kp] == 1:
return False, "order"
# different variables needed for this function
zero_count = lin_num * lin_num
zero_count, triplet_xys, triplet_ysx, triplet_xsy = check_and_update_complete_Z_matrix_from_matrix(z_matrix, zero_count, lin_num)
matrix_after_first_round = np.copy(z_matrix)
# go once through segments and get gains, losses and SSMs
gain_num = []
loss_num = []
CNVs = []
present_ssms = []
ssm_infl_cnv_same_lineage = []
# iterate through all segments once to get all CN changes and SSMs appearances
get_CN_changes_SSM_apperance(seg_num, gain_num, loss_num, CNVs, present_ssms, lin_num, my_lineages,
ssm_infl_cnv_same_lineage)
present_ssms = np.asarray(present_ssms)
# combine information to Z-matrix and Co object
zmco = Z_Matrix_Co(z_matrix, triplet_xys, triplet_ysx, triplet_xsy, present_ssms, matrix_after_first_round)
# get definite parents and available frequencies
last = lin_num
linFreqs = np.asarray([my_lineages[i].freq for i in range(len(my_lineages))])
defparent, avFreqs = get_definite_parents_available_frequencies(linFreqs, ppm)
initial_pps_for_all = build_initial_pps_for_all(ppm)
# adapt noise buffer if necessary
freq_num = len(linFreqs[0])
if isinstance(noise_buffer, int) or isinstance(noise_buffer, float):
noise_buffer = np.zeros(lin_num*freq_num).reshape(lin_num,freq_num)
# compare relationships in partial clone tree and complete tree
for k in range(1, lin_num):
for kp in range(k+1, lin_num):
if z_matrix[k][kp] == tree_z[k][kp]:
continue
elif z_matrix[k][kp] == 0:
try:
update_ancestry(tree_z[k][kp], k, kp, last=last, ppm=ppm, defparent=defparent,
linFreqs=linFreqs, avFreqs=avFreqs, zmco=zmco, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms,
noise_buffer=noise_buffer, initial_pps_for_all=initial_pps_for_all)
except (eo.ADRelationNotPossible, eo.NoParentsLeft, eo.NoParentsLeftNoise, eo.ZInconsistenceInfo) as e:
return False, "relationship"
else:
return False, "relationship"
return True, True
# given available frequencies, sum up those that are negative
def compute_neg_avFreqs(avFreqs):
tmp_avFreqs = np.copy(avFreqs)
tmp_avFreqs[tmp_avFreqs > 0] = 0
return np.sum(tmp_avFreqs)
# computes the MAR and the corresponding noise buffer used
def compute_MAR_noise_buffer(number_undef_rels, undef_rels, USED_P1, USED_M1, K, KP, sbclr, last, linFreqs, seg_num, zero_count, gain_num,
loss_num, CNVs, noise_buffer):
# check all parental relationships
for j in range(number_undef_rels):
# ambiguous value
value = 0
# relationship is only present
if undef_rels[j][USED_P1] == True:
if undef_rels[j][USED_M1] == False:
value = 1
# relationship is only absent
else:
if undef_rels[j][USED_M1] == True:
value = -1
# update relationship
if value != 0:
update_ancestry(value, undef_rels[j][K], undef_rels[j][KP], last=last, ppm=sbclr.ppm, defparent=sbclr.defparent,
linFreqs=linFreqs, avFreqs=sbclr.avFreqs, zmco=sbclr.zmco, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=sbclr.present_ssms,
noise_buffer=noise_buffer, initial_pps_for_all=sbclr.initial_pps_for_all)
# get noise buffer set
subsam_specific_noise_buffers = get_subclone_specific_noise_buffer(noise_buffer, sbclr.ppm, sbclr.avFreqs, linFreqs)
largest_necessary_buffer = get_largest_subclone_specific_noise_buffer_set(subsam_specific_noise_buffers, sbclr.zmco.z_matrix, linFreqs)
return sbclr.zmco.z_matrix, largest_necessary_buffer, sbclr.ppm
def reorder_matrix_according_to_mapping(my_matrix, mapping):
lin_num = len(my_matrix)
new_matrix = np.zeros(lin_num*lin_num).reshape(lin_num, lin_num)
for k in range(lin_num):
for kp in range(lin_num):
try:
new_matrix[k][kp] = my_matrix[mapping[k]][mapping[kp]]
# possible that mapping doesn't contain the germline
except KeyError:
if k == 0 and kp == 0:
new_matrix[k][kp] = my_matrix[k][kp]
elif k == 0:
new_matrix[k][kp] = my_matrix[k][mapping[kp]]
elif kp == 0:
new_matrix[k][kp] = my_matrix[mapping[k]][kp]
return new_matrix
def combine_different_submars(submars, coeffs=[], uniform=False, use_ppm=False):
submar_num = len(submars)
# check that right format is used, no relationship expressed with value 0
if use_ppm == False and submars[0][0][0] == -1:
[convert_zmatrix_to_presentation_mode(submars[i]) for i in range(submar_num)]
# convert array to contain floats
try:
submars = [submars[i].astype('float64') for i in range(submar_num)]
except AttributeError:
submars = [np.asarray(submars[i]).astype('float64') for i in range(submar_num)]
# convert ambiguous entries to 0.5
if use_ppm == False:
[convert_ambiguous_to_zpf(submars[i]) for i in range(submar_num)]
# check coefficients
# if no information is given, weights are uniformly distributed
if uniform == False and coeffs == []:
uniform = True
# compute uniform coefficients
if uniform == True:
coeffs = [1.0/submar_num] * submar_num
# take care that coeffs are scaled
else:
coeffs_sum = sum(coeffs)
if coeffs_sum != 1:
coeffs = [coeffs[i]/float(coeffs_sum) for i in range(submar_num)]
# multiply coefficients
submars = [submars[i] * coeffs[i] for i in range(submar_num)]
# sum and take average
av_submar = np.sum(submars, axis=0)
return av_submar
def new_dfs(z_matrix, my_lineages, seg_num=None, filename=None, count_threshold=-1, ppm=None, test_iteration=False,
test_reconstructions=False, analyze_ambiguity_during_runtime=False, noise_buffer=0, find_best_noise_buffer=False,
converted_matrix=False):
# ensure that input data is correct
if find_best_noise_buffer:
assert ppm is not None
if z_matrix[0][0] == 0:
convert_zmatrix_for_internal_use(z_matrix)
converted_matrix = True
z_matrix = np.asarray(z_matrix)
total_count = 0
valid_count = 0
# create list structure "undef_rels" to iterate through all possible settings of matrix
undef_rels = []
REL = 0
K = 1
KP = 2
SBCLR = 3
USED_P1 = 4
USED_M1 = 5
# get undefined relationships based on Z-matrix
if ppm is None:
for kp in range(len(z_matrix)):
for k in range(0, kp):
if z_matrix[k][kp] == 0:
undef_rels.append([0, k, kp, None, False, False])
# get undefined relationships based on possible parent matrix
else:
for kp in range(len(ppm)):
for k in range(0, kp):
if ppm[kp][k] == 1 and z_matrix[k][kp] == 0:
undef_rels.append([0, k, kp, None, False, False])
number_undef_rels = len(undef_rels)
# different variables needed for this function
lin_num = len(my_lineages)
zero_count = lin_num * lin_num
zero_count, triplet_xys, triplet_ysx, triplet_xsy = check_and_update_complete_Z_matrix_from_matrix(z_matrix, zero_count, lin_num)
matrix_after_first_round = np.copy(z_matrix)
# go once through segments and get gains, losses and SSMs
gain_num = []
loss_num = []
CNVs = []
present_ssms = []
ssm_infl_cnv_same_lineage = []
# iterate through all segments once to get all CN changes and SSMs appearances
get_CN_changes_SSM_apperance(seg_num, gain_num, loss_num, CNVs, present_ssms, lin_num, my_lineages,
ssm_infl_cnv_same_lineage)
present_ssms = np.asarray(present_ssms)
# combine information to Z-matrix and Co object
zmco = Z_Matrix_Co(z_matrix, triplet_xys, triplet_ysx, triplet_xsy, present_ssms, matrix_after_first_round)
# create variables needed for sum rule
last = None
defparent = None
avFreqs = None
linFreqs = np.asarray([my_lineages[i].freq for i in range(len(my_lineages))])
initial_pps_for_all = None
if ppm is not None:
last = lin_num
# get definite parents and available frequencies
defparent, avFreqs = get_definite_parents_available_frequencies(linFreqs, ppm)
initial_pps_for_all = build_initial_pps_for_all(ppm)
# take care that noise buffer has correct format
freq_num = len(linFreqs[0])
if isinstance(noise_buffer, int) or isinstance(noise_buffer, float):
noise_buffer = np.zeros(lin_num*freq_num).reshape(lin_num,freq_num)
sbclr_0 = Subclonal_Reconstruction_for_DFS(zmco, present_ssms, ppm, defparent, avFreqs, initial_pps_for_all)
# checks whether given partial subclonal reconstruction is valid
if not is_reconstruction_valid(my_lineages, z_matrix, ppm, seg_num, gain_num, loss_num, CNVs, present_ssms, ssm_infl_cnv_same_lineage,
check_only_validity_possible=True, noise_buffer=noise_buffer):
raise eo.ReconstructionInvalid("Reconstruction is invalid")
# testing whether function iterates correctly over all possible settings in Z-matrix
if test_iteration:
all_options = []
# testing whether function allows and forbids correct subclonal reconstructions
if test_reconstructions:
reconstructions = []
# pointer i iterates through list with undefined relationships
i = 0
neg_avFreq = -float("inf")
while i < number_undef_rels + 1 and number_undef_rels != 0:
# current relationship is undefined
if i < number_undef_rels and undef_rels[i][REL] == 0:
# set relationship to present
undef_rels[i][REL] = 1
# next steps not needed for testing whether iteration finds all settings
if test_iteration:
i += 1
continue
# create first subclonal reconstruction to update
if i == 0:
sbclr = copy.deepcopy(sbclr_0)
# use previous subclonal reconstruction to update
else:
sbclr = copy.deepcopy(undef_rels[i-1][SBCLR])
try:
# update relationship in subclonal reconstruction to present
update_ancestry(1, undef_rels[i][K], undef_rels[i][KP], last=last, ppm=sbclr.ppm, defparent=sbclr.defparent,
linFreqs=linFreqs, avFreqs=sbclr.avFreqs, zmco=sbclr.zmco, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=sbclr.present_ssms,
noise_buffer=noise_buffer, initial_pps_for_all=sbclr.initial_pps_for_all)
# if best noise buffer should be found
if find_best_noise_buffer:
# negative available frequency is smaller
if compute_neg_avFreqs(sbclr.avFreqs) < neg_avFreq:
raise eo.SmallerNegAvFreq("Better negative frequencies found")
undef_rels[i][SBCLR] = sbclr
except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible, eo.NoParentsLeft, eo.NoParentsLeftNoise,
eo.RelationshipAlreadySet, eo.SmallerNegAvFreq, eo.PhasingForbidsRelation) as e:
# update not possible or noise buffer was worse
# thus, count one tree that was enumerated
total_count += 1
if total_count % 100000 == 0:
logging.info("Total count: {0}".format(total_count))
# update relationship in subclonal reconstruction to other value
undef_rels[i][REL] = -1
# create subclonal reconstruction to update
if i == 0:
sbclr = copy.deepcopy(sbclr_0)
else:
sbclr = copy.deepcopy(undef_rels[i-1][SBCLR])
# update relationship in subclonal reconstruction to absent
total_count, i = update_sbclr_dfs(-1, undef_rels[i][K], undef_rels[i][KP], last, sbclr, seg_num, zero_count,
gain_num, loss_num, CNVs, total_count, undef_rels, i, REL, SBCLR, linFreqs, noise_buffer=noise_buffer,
neg_avFreq=neg_avFreq, find_best_noise_buffer=find_best_noise_buffer)
undef_rels[i][SBCLR] = sbclr
# current relationship is present
elif i < number_undef_rels and undef_rels[i][REL] == 1:
# set relationship to absent
undef_rels[i][REL] = -1
# next steps not needed for testing whether iteration finds all settings
if test_iteration:
i += 1
continue
# create subclonal reconstruction to update
if i == 0:
sbclr = copy.deepcopy(sbclr_0)
else:
sbclr = copy.deepcopy(undef_rels[i-1][SBCLR])
total_count, i = update_sbclr_dfs(-1, undef_rels[i][K], undef_rels[i][KP], last, sbclr, seg_num, zero_count,
gain_num, loss_num, CNVs, total_count, undef_rels, i, REL, SBCLR, linFreqs, noise_buffer=noise_buffer,
neg_avFreq=neg_avFreq, find_best_noise_buffer=find_best_noise_buffer)
undef_rels[i][SBCLR] = sbclr
# current relationship is absent
elif i < number_undef_rels and undef_rels[i][REL] == -1:
# look for last relationship that was set to present
i -= 1
while i >= 0 and undef_rels[i][REL] != 1:
i -= 1
# no relationship is present anymore, this means all possible settings where tried
if i < 0:
break
# last present relationship is found
if undef_rels[i][REL] == 1:
# set following relationships to ambiguous again
for j in range(i+1, number_undef_rels):
undef_rels[j][REL] = 0
undef_rels[j][SBCLR] = None
# decrease i because it's going to be increased after condistions
i -= 1
# all relationships were set
elif i == number_undef_rels:
i -= 1
# when function should be tested, append current setting to list
if test_iteration:
all_options.append([x[REL] for x in undef_rels])
continue
# current subclonal reconstruction is complete
total_count += 1
if total_count % 100000 == 0:
logging.info("Total count: {0}".format(total_count))
# sum rule is satisfied, hence, reconstruction is valid
if check_sum_rule(my_lineages, undef_rels[i][SBCLR].zmco.z_matrix, noise_buffer=noise_buffer):
valid_count += 1
if valid_count % 1000 == 0:
logging.info("Valid count: {0}".format(valid_count))
if analyze_ambiguity_during_runtime:
used_p1 = [x[USED_P1] for x in undef_rels]
used_m1 = [x[USED_M1] for x in undef_rels]
logging.info("Ambiguity: {0}".format(np.logical_and(used_p1, used_m1).all()))
# if smallest noise buffer should be found
if find_best_noise_buffer:
current_neg_avFreq = compute_neg_avFreqs(undef_rels[i][SBCLR].avFreqs)
# if current negative available frequencies are larger than the ones of a previous run, better noise buffer is found
if current_neg_avFreq > neg_avFreq:
# if valid count >= 1000: output that better noise buffer was found because we already printed out some valid counts in log file
if valid_count >= 1000:
logging.info("Better noise buffer was found, valid count set back to 1")
valid_count = 1
neg_avFreq = current_neg_avFreq
for j in range(number_undef_rels):
undef_rels[j][USED_P1] = False
undef_rels[j][USED_M1] = False
# if Z-matrix should be written to file and maximum number in file is not reached yet
if filename is not None and valid_count <= count_threshold:
if converted_matrix:
convert_zmatrix_to_presentation_mode(undef_rels[i][SBCLR].zmco.z_matrix)
if valid_count == 1:
with open(filename, "w") as f:
my_string = json.dumps(convert_zmatrix_0_m1(undef_rels[i][SBCLR].zmco.z_matrix))
f.write("{0}\n".format(my_string))
else:
with open(filename, "a") as f:
my_string = json.dumps(convert_zmatrix_0_m1(undef_rels[i][SBCLR].zmco.z_matrix))
f.write("{0}\n".format(my_string))
if converted_matrix:
convert_zmatrix_for_internal_use(undef_rels[i][SBCLR].zmco.z_matrix)
# if used relationships should be anaylzed during runtime
if analyze_ambiguity_during_runtime:
for j in range(number_undef_rels):
if undef_rels[j][REL] == 1:
undef_rels[j][USED_P1] = True
elif undef_rels[j][REL] == -1:
undef_rels[j][USED_M1] = True
else:
raise eo.MyException("should never happen")
# testing whether function allows and forbids correct subclonal reconstructions
if test_reconstructions:
reconstructions.append(undef_rels[i][SBCLR])
# decrease i because it's going to be increased after condistions
i -= 1
i += 1
# if ambiguity should be analyzed during runtime
output = ""
if analyze_ambiguity_during_runtime and find_best_noise_buffer is False:
for j in range(number_undef_rels):
if undef_rels[j][USED_P1] == False or undef_rels[j][USED_M1] == False:
output += "False, {0}, {1}, {2}, {3}\n".format(undef_rels[j][K], undef_rels[j][KP],
undef_rels[j][USED_P1], undef_rels[j][USED_M1])
if output == "" and number_undef_rels > 0:
output = "True\n"
elif output == "":
output = "All ancestral relationships are defined.\n"
# if best noise buffer should be found
if find_best_noise_buffer:
my_MAR, largest_necessary_buffer, final_ppm = compute_MAR_noise_buffer(number_undef_rels, undef_rels, USED_P1, USED_M1, K, KP, sbclr_0, last,
linFreqs, seg_num, zero_count, gain_num, loss_num, CNVs, noise_buffer)
if number_undef_rels == 0:
valid_count = 1
# testing iteration
if test_iteration:
return all_options
# testing whether function allows and forbids correct subclonal reconstructions
if test_reconstructions:
return reconstructions, total_count, valid_count
# if best noise buffer should be found
if find_best_noise_buffer:
if converted_matrix:
convert_zmatrix_to_presentation_mode(my_MAR)
return total_count, valid_count, my_MAR, final_ppm, largest_necessary_buffer, neg_avFreq
# if ambiguity should be analyzed during runtime
if analyze_ambiguity_during_runtime:
return total_count, valid_count, output
return total_count, valid_count
def update_sbclr_dfs(value, k, kp, last, sbclr, seg_num, zero_count, gain_num, loss_num, CNVs, total_count, undef_rels, i, REL, SBCLR, linFreqs,
noise_buffer=0, neg_avFreq=0, find_best_noise_buffer=False):
undef_rels[i][REL] = value
# update relationship in subclonal reconstruction
try:
update_ancestry(value, k, kp, last=last, ppm=sbclr.ppm, defparent=sbclr.defparent,
linFreqs=linFreqs, avFreqs=sbclr.avFreqs, zmco=sbclr.zmco, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=sbclr.present_ssms,
noise_buffer=noise_buffer, initial_pps_for_all=sbclr.initial_pps_for_all)
# if best noise buffer should be found
if find_best_noise_buffer:
# negative available frequency is smaller
if compute_neg_avFreqs(sbclr.avFreqs) < neg_avFreq:
raise eo.SmallerNegAvFreq("Better negative frequencies found")
undef_rels[i][SBCLR] = sbclr
except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible, eo.NoParentsLeft, eo.NoParentsLeftNoise,
eo.RelationshipAlreadySet, eo.SmallerNegAvFreq, eo.PhasingForbidsRelation) as e:
# update not possible
# thus, count one tree that was enumerated
total_count += 1
if total_count % 100000 == 0:
logging.info("Total count: {0}".format(total_count))
# decrease i because it's going to be increased after condistions in main loop
i -= 1
return total_count, i
# given a Z-matrix, counts how often lineage relationships are ambiguous
def count_ambiguous_relationships(z_matrix):
z_matrix = np.asarray(z_matrix)
ambi_num = 0
# forst row skipt because it does not contain ambiguous relationships by definition
for k in range(1,len(z_matrix)):
ambi_num += len(np.where(z_matrix[k] == 0)[0])
return ambi_num
def update_ancestry_w_preprocessing(my_lineages, z_matrix, ppm, seg_num, value, k, kprime):
# get present mutations from lineages
lineage_num = len(my_lineages)
# go once through segment and get gains, losses and SSMs
gain_num = []
loss_num = []
CNVs = []
present_ssms = []
ssm_infl_cnv_same_lineage = []
# iterate through all segments once to get all CN changes and SSMs appearances
get_CN_changes_SSM_apperance(seg_num, gain_num, loss_num, CNVs, present_ssms, lineage_num, my_lineages,
ssm_infl_cnv_same_lineage)
# get definite parents and available frequencies
frequencies = np.asarray([my_lineages[i].freq for i in range(len(my_lineages))])
defp, avFreqs = get_definite_parents_available_frequencies(frequencies, ppm)
# copy
origin_z_matrix = copy.deepcopy(z_matrix)
origin_ppm = copy.deepcopy(ppm)
last = lineage_num - 1
# create zmco
dummy_zero_count = lineage_num * lineage_num
zero_count, triplet_xys, triplet_ysx, triplet_xsy = check_and_update_complete_Z_matrix_from_matrix(z_matrix, dummy_zero_count, lineage_num,
CNVs=CNVs, present_ssms=present_ssms, z_matrix_after_CN_influence_check=origin_z_matrix)
assert (np.asarray(origin_z_matrix) == np.asarray(z_matrix)).all()
triplets_list = [[triplet_xys, triplet_ysx, triplet_xsy]]
zmcos = create_Z_Matrix_Co_objects([z_matrix], origin_z_matrix, [present_ssms], triplets_list)
zmco = zmcos[0]
update_ancestry(value, k, kprime, last=last, ppm=ppm, defparent=defp, linFreqs=frequencies, avFreqs=avFreqs, zmco=zmco, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
# given a subclonal reconstruction with lineages, mutations, Z-matrix and possible parent matrix, check whether it is valid
def is_reconstruction_valid(my_lineages, z_matrix, ppm, seg_num, gain_num=None, loss_num=None, CNVs=None, present_ssms=None,
ssm_infl_cnv_same_lineage=None, check_only_validity_possible=False, noise_buffer=0):
# get present mutations from lineages
lineage_num = len(my_lineages)
# go once through segment and get gains, losses and SSMs
if gain_num is None and loss_num is None and CNVs is None and present_ssms is None and ssm_infl_cnv_same_lineage is None:
gain_num = []
loss_num = []
CNVs = []
present_ssms = []
ssm_infl_cnv_same_lineage = []
# iterate through all segments once to get all CN changes and SSMs appearances
get_CN_changes_SSM_apperance(seg_num, gain_num, loss_num, CNVs, present_ssms, lineage_num, my_lineages,
ssm_infl_cnv_same_lineage)
# copy elements
origin_present_ssms = copy.deepcopy(present_ssms)
origin_z_matrix = copy.deepcopy(z_matrix)
origin_ppm = copy.deepcopy(ppm)
# propagate tree rules
dummy_zero_count = lineage_num * lineage_num
try:
zero_count, triplet_xys, triplet_ysx, triplet_xsy = check_and_update_complete_Z_matrix_from_matrix(z_matrix, dummy_zero_count, lineage_num,
CNVs=CNVs, present_ssms=present_ssms, z_matrix_after_CN_influence_check=origin_z_matrix)
except eo.MyException as e:
return False
# propagate crossing rule
zero_count = check_crossing_rule_function(my_lineages, z_matrix, zero_count, triplet_xys, triplet_ysx, triplet_xsy,
noise_buffer=noise_buffer)
# propagate relationship absense rule
try:
z_matrix_list, z_matrix_fst_rnd, triplets_list = (
post_analysis_Z_matrix(my_lineages, seg_num, z_matrix, zero_count, triplet_xys, triplet_ysx, triplet_xsy,
matrix_splitting=False, first_absence_propagation=True, CNVs=CNVs, present_ssms=present_ssms, gain_num=gain_num,
loss_num=loss_num))
except eo.MyException as e:
return False
# propagate sum rule
zmcos = create_Z_Matrix_Co_objects(z_matrix_list, z_matrix_fst_rnd, [present_ssms], triplets_list)
zmco = zmcos[0]
frequencies = np.asarray([my_lineages[i].freq for i in range(len(my_lineages))])
try:
sum_rule_worked, avFreqs, ppm = sum_rule_algo_outer_loop(frequencies, zmco, seg_num, zero_count,
gain_num, loss_num, CNVs, present_ssms, noise_buffer=noise_buffer)
except eo.MyException as e:
return False
if check_only_validity_possible:
return True
if not (np.asarray(z_matrix) == np.asarray(origin_z_matrix)).all():
return False
if origin_ppm is not None and not (ppm == origin_ppm).all():
return False
if not present_ssms == origin_present_ssms:
return False
return True
# given lineage frequencies and a possible parent matrix, get the definite parent of each lineage if available
# and compute the available frequencies of lineages
def get_definite_parents_available_frequencies(freqs, ppm):
lin_num = len(freqs)
# compute definite parents
defp = np.asarray([-1] * lin_num)
for k in range(1, lin_num):
pp = np.where(ppm[k] == 1)[0]
if len(pp) == 1:
defp[k] = pp[0]
# compute available freq
avFreqs = np.copy(freqs)
for k in range(lin_num):
children = np.where(defp == k)[0]
for child in children:
avFreqs[k] = np.subtract(avFreqs[k], freqs[child])
return defp, avFreqs
# given the list parental_list, where parental_list[k] = k* meaning that lineage k+1 has lineage k^* as parent
# build the sublin lists, where a list contains all descendants of a lineage
def build_sublin_lists_from_parental_info(mylins, parental_list):
lin_num = len(mylins)
# initialize lists of cancerous lineages with their children
for i in range(1, len(parental_list)):
mylins[parental_list[i]].sublins.append(i+1)
# if there are only three lineages, lin 1 can only have lin 2 as child and lin 0 is done per definition
# nothing to do
if lin_num == 3:
return
# go backwards through sublins lists and add descendants of children
for i in range(lin_num-3, 0, -1):
children_num = len(mylins[i].sublins)
for c in range(children_num):
mylins[i].sublins.extend(mylins[mylins[i].sublins[c]].sublins)
mylins[i].sublins.sort()
# given two lineages k and k', returns their lowest common ancestor
# if k is ancestor of k', k is returned
def get_lca(k, kprime, z_matrix):
if k > kprime:
raise eo.MyException("k needs to be smaller k'")
if z_matrix[k][kprime] == 1:
return k
for kstar in range(k-1, -1, -1):
if z_matrix[kstar][k] == 1 and z_matrix[kstar][kprime] == 1:
return kstar
# finds the lca for a list of lineages
def get_lca_from_multiple_lineages(possible_parents, z_matrix):
lca = get_lca(possible_parents[0], possible_parents[1], z_matrix)
for i in range(2, len(possible_parents)):
lca_new = get_lca(lca, possible_parents[i], z_matrix)
lca = lca_new
return lca
# checks whether all ambiguous entries in the original Z-matrix represent present and absent relationships in all
# Z-matrices without ambiguities
def check_untightess_zmatrix(z_matrix, z_matrix_list, total_number):
output = ""
lin_num = len(z_matrix)
# if Z-matrix list contains less matrices than existing, it makes no sense to process this dataset
if len(z_matrix_list) < total_number:
return "False, -1, -1\n"
# data structure to keep track of tightness
tightness_matrix = np.zeros(lin_num * lin_num * 3).reshape(lin_num, lin_num, 3)
# note where original Z-matrix is ambiguous
for k in range(lin_num-1):
for k_prime in range(k, lin_num):
if z_matrix[k][k_prime] == 0:
tightness_matrix[k][k_prime][0] = 1
# check all unambiguous Z-matrices
for unam_m in z_matrix_list:
for k in range(lin_num-1):
for k_prime in range(k, lin_num):
# if original matrix is ambiguous at position
if tightness_matrix[k][k_prime][0] == 1:
# current matrix has present relationship
if unam_m[k][k_prime] == 1:
tightness_matrix[k][k_prime][1] = 1
# current matrix has absent relationship
elif unam_m[k][k_prime] == -1:
tightness_matrix[k][k_prime][2] = 1
# unknown relationship
else:
raise Exception("Relationship has to be either present or absent.")
# check whether both values were used for ambiguous entries
for k in range(lin_num-1):
for k_prime in range(k, lin_num):
if tightness_matrix[k][k_prime][0] == 1:
if tightness_matrix[k][k_prime][1] == 1 and tightness_matrix[k][k_prime][2] == 1:
continue
else:
output += "False, {0}, {1}, {2}, {3}\n".format(k, k_prime, tightness_matrix[k][k_prime][1],
tightness_matrix[k][k_prime][2])
# all ambiguous entries were ambiguous
if output == "":
return "True\n"
else:
return output
# returns the upper bound as logarithm on possible reconstructions
# \sum_{k=1}^{K-1} log(# possible parents of lineage k)
def upper_bound_number_reconstructions(ppm):
if ppm[0][0] == 1:
raise Exception("Wrong format of possible parent matrix.")
return np.sum([np.log(np.count_nonzero(ppm[k])) for k in range(1, len(ppm))])
# computes the upper bound on set of (sub)MAR-completing clone trees
def compute_upper_bound(ppm_file=None, z_matrix_file=None):
# check if ppm file is there
if ppm_file is None:
# read z_matrix_file
if z_matrix_file is None:
raise Exception("Possible parent file or ancestry matrix Z need to be given.")
z_matrix = oio.read_matrix_from_file(z_matrix_file)
if z_matrix[0][0] == 0:
z_matrix = convert_zmatrix_0_m1(z_matrix)
# compute ppm from zmatrix
ppm = get_possible_parents(z_matrix)
else:
# read ppm file
ppm = np.loadtxt(ppm_file, delimiter=",")
# compute upper bound
log_bound = upper_bound_number_reconstructions(ppm)
if log_bound > np.log(sys.maxsize):
print("Upper bound on set of valid (sub)MAR-completing clone trees: e^{0}".format(log_bound))
else:
bound = round(np.exp(log_bound))
print("Upper bound on set of valid (sub)MAR-completing clone trees: {0}".format(bound))
def read_ppm_zmatrix_and_more(ppm_file, z_matrix_file, lin_file, cna_file, ssm_file, noise_buffer_file):
# get ppm data
ppm = np.loadtxt(ppm_file, delimiter=",")
# get Z-matrix
z_matrix = oio.read_matrix_from_file(z_matrix_file)
converted_matrix = False
if z_matrix[0][0] == 0:
z_matrix = convert_zmatrix_0_m1(z_matrix)
converted_matrix = True
# get lineages
my_lins = oio.read_JSON_result_file(lin_file)
# get CNAs
if cna_file is None:
my_cnas = []
else:
my_cnas = oio.read_cnas(cna_file, use_cna_indices=True)
# get SSMs
if ssm_file is None:
my_ssms = []
else:
my_ssms = oio.read_ssms(ssm_file, phasing=False, use_SSM_index=True)
# get number of segments
seg_num = get_seg_num(my_cnas, my_ssms)
# get noise buffer
noise_buffer = 0
if noise_buffer_file is not None:
noise_buffer = np.loadtxt(noise_buffer_file, delimiter=",", ndmin=2)
return ppm, z_matrix, converted_matrix, my_lins, seg_num, noise_buffer
def depth_first_search(ppm_file=None, z_matrix_file=None, lin_file=None, cna_file=None, ssm_file=None, output_prefix=None, overwrite=False,
noise_buffer_file=None, find_best_noise_buffer=False):
# get ppm data, Z-matrix, lineages, number of segments, noise buffer
ppm, z_matrix, converted_matrix, my_lins, seg_num, noise_buffer = read_ppm_zmatrix_and_more(ppm_file,
z_matrix_file, lin_file, cna_file, ssm_file, noise_buffer_file)
# create filenames
valid_count_file = "{0}.valid_count.txt".format(output_prefix)
ambi_file = "{0}.ambiguity.txt".format(output_prefix)
my_MAR_file = "{0}.zmatrix.MAR".format(output_prefix)
ppm_MAR_file = "{0}.pospars.MAR".format(output_prefix)
noisebuffer_MAR_file = "{0}.noisebuffer.MAR".format(output_prefix)
neg_avFreq_MAR_file = "{0}.negfreqs.MAR".format(output_prefix)
if overwrite == False:
oio.raise_if_file_exists(valid_count_file)
oio.raise_if_file_exists(ambi_file)
if find_best_noise_buffer:
oio.raise_if_file_exists(my_MAR_file)
oio.raise_if_file_exists(ppm_MAR_file)
oio.raise_if_file_exists(noisebuffer_MAR_file)
oio.raise_if_file_exists(neg_avFreq_MAR_file)
# start logging
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename="{0}.dfs.log".format(output_prefix), filemode='w', level=10)
# compute correct number and all possible reconstructions
if find_best_noise_buffer:
total_count, valid_count, my_MAR, final_ppm, largest_necessary_buffer, neg_avFreq = new_dfs(z_matrix, my_lins, seg_num, ppm=ppm,
analyze_ambiguity_during_runtime=True, noise_buffer=noise_buffer, converted_matrix=converted_matrix, find_best_noise_buffer=True)
else:
total_count, valid_count, output = new_dfs(z_matrix, my_lins, seg_num, ppm=ppm, analyze_ambiguity_during_runtime=True,
noise_buffer=noise_buffer, converted_matrix=converted_matrix)
# last logging
logging.info("Total number of enumerated trees: {0}".format(total_count))
logging.info("Valid number of trees: {0}".format(valid_count))
# write to file
with open(valid_count_file, "w") as f:
f.write("{0}\n".format(valid_count))
# if best noise buffer should be found, result is MAR and there all uncertain entries are ambiguous, also, no output is returned
if not find_best_noise_buffer:
with open(ambi_file, "w") as f:
f.write(output)
if find_best_noise_buffer:
np.savetxt(my_MAR_file, my_MAR, delimiter=",", fmt='%1.0f')
np.savetxt(ppm_MAR_file, final_ppm, delimiter=",", fmt='%1.0f')
np.savetxt(noisebuffer_MAR_file, largest_necessary_buffer, delimiter=",")
np.savetxt(neg_avFreq_MAR_file, np.asarray([neg_avFreq]))
# given a subclonal reconstruction with ambiguous lineage relationships, this function iterivly tries all possible
# values and returns the number of valid reconstructions
def compute_number_ambiguous_recs(my_lineages, seg_num, z_matrix, recursive=False, filename=None, count_threshold=-1, ppm=None,
check_validity=False):
if check_validity and not is_reconstruction_valid(my_lineages, z_matrix, ppm, seg_num):
raise eo.MyException("reconstruction is not valid")
# different variables needed for this function
lin_num = len(my_lineages)
zero_count = lin_num * lin_num
zero_count, triplet_xys, triplet_ysx, triplet_xsy = check_and_update_complete_Z_matrix_from_matrix(z_matrix, zero_count, lin_num)
matrix_after_first_round = copy.deepcopy(z_matrix)
# go once through segment and get gains, losses and SSMs
gain_num = []
loss_num = []
CNVs = []
present_ssms = []
ssm_infl_cnv_same_lineage = []
# iterate through all segments once to get all CN changes and SSMs appearances
get_CN_changes_SSM_apperance(seg_num, gain_num, loss_num, CNVs, present_ssms, lin_num, my_lineages,
ssm_infl_cnv_same_lineage)
# combine information to Z-matrix and Co object
zmco = Z_Matrix_Co(z_matrix, triplet_xys, triplet_ysx, triplet_xsy, present_ssms, matrix_after_first_round)
if recursive == False:
raise Exception("Not supported anymore")
## create list with Z-matrix and Co objects
#zmco_list = [zmco]
## iterate through complete matrix
#for k in range(lin_num-1):
# for k_prime in range(k+1, lin_num):
# # create new list for next round
# new_zmco_list = []
# # iterate through all Z-matrices in list
# for i in range(len(zmco_list)):
# # if current entry is ambiguous, fork matrix
# if zmco_list[i].z_matrix[k][k_prime] == 0:
# # copy current Z-matrix and co object for setting entry to 1 (relationship present)
# zmco_dup = copy.deepcopy(zmco_list[i])
# try:
# update_single_z_matrix_entry(1, k, k_prime, zmco_dup)
# new_zmco_list.append(zmco_dup)
# except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible) as e:
# pass
# # set entry of current Z-matrix and co object to -1 (relationship absent)
# try:
# update_single_z_matrix_entry(-1, k, k_prime, zmco_list[i])
# new_zmco_list.append(zmco_list[i])
# except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible) as e:
# pass
# else:
# # if current entry is not ambiguous, keep current Z-matrix and co object in list for next round
# new_zmco_list.append(zmco_list[i])
# # make new_zmco_list to standard list
# zmco_list = new_zmco_list
## check sum rule for all reconstruction
#is_sum_rule_fulfilled = [check_sum_rule(my_lineages, zmco_list[i].z_matrix) for i in range(len(zmco_list))]
## only keep reconstructions that fulfill the sum rule
#zmco_list_fulfills_sum_rule = list(compress(zmco_list, is_sum_rule_fulfilled))
## number of valid reconstructions and valid reconstructions
#return len(zmco_list_fulfills_sum_rule), zmco_list_fulfills_sum_rule
# recursive function
else:
last = None
defparent = None
avFreqs = None
linFreqs = None
if ppm is not None:
last = lin_num
# get definite parents and available frequencies
linFreqs = np.asarray([my_lineages[i].freq for i in range(len(my_lineages))])
defparent, avFreqs = get_definite_parents_available_frequencies(linFreqs, ppm)
return recursive_number_ambiguous_recs(0, 0, lin_num, zmco, my_lineages, 0, filename=filename, count_threshold=count_threshold,
last=last, ppm=ppm, defparent=defparent, linFreqs=linFreqs, avFreqs=avFreqs, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
# recursive function for depth-first search of ambiguous reconstructions
def recursive_number_ambiguous_recs(k_current, k_prime_checked, lin_num, zmco_current, my_lineages, count, filename=None, count_threshold=-1,
last=None, ppm=None, defparent=None, linFreqs=None, avFreqs=None, seg_num=None, zero_count=None, gain_num=None, loss_num=None,
CNVs=None, present_ssms=None):
# tracks whether this is the last recursive call
last_call = True
# iterate through matrix, starting after Z[k][k_prime_checked]
for k in range(k_current, lin_num-1):
for k_prime in range(k+1, lin_num):
# only check entry if it wasn't checked already
if k == k_current and k_prime <= k_prime_checked:
continue
if zmco_current.z_matrix[k][k_prime] == 0:
# recursion will be called again
last_call = False
# copy current Z-matrix and co object for setting entry to 1 (relationship present)
zmco_dup = copy.deepcopy(zmco_current)
try:
# ancestry is updated, lineage relationship absence constraints are propagated only if sum rule
# should be applied as well, otherwise the SSM phasing takes care that invalid scenarios get caught
# concerning the case that two losses of the same allele in the same segment should be set into a
# present relation, the upper function takes care of this as it can check for invalid reconstructions
# and because this case is forbidden independent of SSM phasing, the relationship should always be
# absent
update_ancestry(1, k, k_prime, last=last, ppm=ppm, defparent=defparent, linFreqs=linFreqs,
avFreqs=avFreqs, zmco=zmco_dup, seg_num=seg_num, zero_count=zero_count, gain_num=gain_num,
loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
# go into recursion
count = recursive_number_ambiguous_recs(k, k_prime, lin_num, zmco_dup, my_lineages, count, filename, count_threshold,
last=last, ppm=ppm, defparent=defparent, linFreqs=linFreqs, avFreqs=avFreqs, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible, eo.NoParentsLeft,
eo.NoParentsLeftNoise) as e:
pass
# set entry of current Z-matrix and co object to -1 (relationship absent)
try:
update_ancestry(-1, k, k_prime, last=last, ppm=ppm, defparent=defparent, linFreqs=linFreqs,
avFreqs=avFreqs, zmco=zmco_current, seg_num=seg_num, zero_count=zero_count, gain_num=gain_num,
loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
# go into recursion
count = recursive_number_ambiguous_recs(k, k_prime, lin_num, zmco_current, my_lineages, count, filename, count_threshold,
last=last, ppm=ppm, defparent=defparent, linFreqs=linFreqs, avFreqs=avFreqs, seg_num=seg_num,
zero_count=zero_count, gain_num=gain_num, loss_num=loss_num, CNVs=CNVs, present_ssms=present_ssms)
except (eo.ZInconsistenceInfo, eo.ADRelationNotPossible, eo.ZUpdateNotPossible, eo.NoParentsLeft,
eo.NoParentsLeftNoise) as e:
pass
# going back one level
return count
if last_call:
# check sum rule
if check_sum_rule(my_lineages, zmco_current.z_matrix):
count += 1
# if Z-matrix should be written to file and maximum number in file is not reached yet
if filename is not None and count <= count_threshold:
with open(filename, "a") as f:
my_string = json.dumps(convert_zmatrix_0_m1(zmco_current.z_matrix))
f.write("{0}\n".format(my_string))