-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContigS.py
1851 lines (1653 loc) · 79.4 KB
/
ContigS.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
__author__ = 'hervemn'
from mutation import new_mutation as mutation
import numpy as np
class repeats():
def __init__(self):
""" initialization """
@classmethod
def init_from_initial_structure(cls, ContigS, contig_a, n_copy):
from copy import deepcopy as deepcopy
# duplicated bloc instance has an id which will be tracked
obj = cls()
obj.ContigS = ContigS
obj.name = contig_a.name
obj.init_contig = contig_a.composition[0]['init_contig']
obj.id_frag_start = contig_a.composition[0]['id_frag_start']
obj.id_frag_end = contig_a.composition[0]['id_frag_end']
obj.orientation = 'w'
obj.access_bloc = str(obj.id_frag_start)+':'+str(obj.id_frag_end)
print " access bloc = ",obj.access_bloc
obj.list_fragments = deepcopy(contig_a.FragmentS)
obj.current_positions = dict() # dictionnary of current positions of the duplicates
obj.incoming_connections = [] # list of new paste ( in the future split and paste)
obj.r_x = n_copy # number of repeats
obj.ContigS.init_contigs[obj.init_contig][obj.access_bloc]['dup'] = True # set this area as duplicated
obj.ContigS.inactivate(contig_a)
return obj
@classmethod
def init_from_previous_repeat(cls, old_repeat, ContigS):
from copy import deepcopy as deepcopy
""" initiate repeats and instances from previous data"""
obj = cls()
obj.ContigS = ContigS
obj.name = old_repeat.name
obj.init_contig = old_repeat.init_contig
obj.id_frag_start = old_repeat.id_frag_start
obj.id_frag_end = old_repeat.id_frag_end
obj.orientation = old_repeat.orientation
obj.access_bloc = old_repeat.access_bloc
obj.list_fragments = deepcopy(old_repeat.list_fragments)
# building translation dictionary from old instances to new instances
obj.current_positions = dict() # dictionnary of current positions of the duplicates
obj.incoming_connections = [] # list of new paste ( in the future split and paste)
obj.r_x = old_repeat.r_x # number of repeats
if not(obj.ContigS.init_contigs.has_key(obj.init_contig)):
obj.ContigS.init_contigs[obj.init_contig] = dict()
if not(obj.ContigS.init_contigs[obj.init_contig].has_key(obj.access_bloc)):
obj.ContigS.init_contigs[obj.init_contig][obj.access_bloc] = dict()
obj.ContigS.init_contigs[obj.init_contig][obj.access_bloc]['dup'] = True # set this area as duplicated
return obj
def add_position(self,id_instance,new_pos):
self.current_positions[id_instance] = new_pos
def is_instance_free(self,id_instance):
if self.current_positions[id_instance] == id_instance:
output = True
else:
output = False
return output
def remove_position(self,id_instance):
new_pos = dict()
new_pos['orientation'] = 'w'
new_pos['position'] = 1
new_pos['@'] = id_instance
self.current_positions[id_instance] = new_pos
def update_current_position(self, id_instance, new_pos):
"""update positions in class"""
self.current_positions[id_instance] = new_pos
def update_incoming_connections(self,connection):
""" add incoming connection """
def create_contig_instance(self,):
""" create instance from template"""
from copy import deepcopy as deepcopy
from contig import contig as contig
instance = contig.initiate(self.init_contig,self.id_frag_start,self.id_frag_end,self.orientation)
new_list_frag = deepcopy(self.list_fragments)
for frag in new_list_frag:
instance.append_fragment(frag,'w')
# print "frag current name = ",frag.curr_name
id_instance = self.ContigS.add(instance)
new_pos = dict()
new_pos['orientation'] = 'w'
new_pos['position'] = 1
new_pos['@'] = id_instance
instance.new_compo[0]["dup"] = True # importnat d etre defini apres
self.add_position(id_instance,new_pos)
return id_instance
def free_all_instances(self,):
""" destroy instances from template"""
class duplicator():
def __init__(self,ContigS):
""" initialization """
self.duplicated_blocs = dict()
self.ContigS = ContigS
self.incoming_connections = []
self.old_instance_2_new_instance = dict()
def define_repeat(self,C,pos_a,pos_b,n_copy):
""" """
from contig import contig as contig
# 1) definir le bloc duplique
# 2) l extraire = split x 2 + delete du bloc
# 3) creer une instance
# 4) inserer l'instance sa position initiale par paste
###################
out_split_a = self.ContigS.split(C,pos_a) # modifier split afin de mettre a jour duplicator : pas urgent/presque inutile
# print "name upstream bloc 1 = ",out_split_a['upstream']["contig"].name
# print "name downstream bloc 1 = ",out_split_a['downstream']["contig"].name
up_C = out_split_a['upstream']["contig"]
tmp_C = out_split_a['downstream']["contig"]
out_split_b = self.ContigS.split(C,pos_b)
dup_bloc = out_split_b['upstream']["contig"] # duplicated bloc
# print "name upstream bloc = ",out_split_b['upstream']["contig"].name
# print "name downstream bloc = ",out_split_b['downstream']["contig"].name
down_C = out_split_b['downstream']["contig"]
###################
repeat = repeats.init_from_initial_structure(self.ContigS, dup_bloc, n_copy)
self.duplicated_blocs[repeat.name] = repeat
for i in range(0,n_copy):
instance_repeat_id = repeat.create_contig_instance()
self.old_instance_2_new_instance[instance_repeat_id] = dict()
self.old_instance_2_new_instance[instance_repeat_id]["new_instance"] = instance_repeat_id
self.old_instance_2_new_instance[instance_repeat_id]["remapped"] = True
instance_repeat = self.ContigS.current_contigs[instance_repeat_id]
up_C_dup = self.ContigS.paste(up_C,'w',instance_repeat,'w') # modifier paste afin de mettre a jour duplicator
original = self.ContigS.paste(up_C_dup,'w',down_C,'w') # modifier paste afin de mettre a jour duplicator
# pop out reference to duplicated part in original contig
access_bloc_dup = str(pos_a + 1 ) +':' + str(pos_b) # be carefull of the split positions
C.old_2_new.pop(access_bloc_dup)
def define_repeat_from_old(self, old_repeat,):
repeat = repeats.init_from_previous_repeat(old_repeat,self.ContigS)
self.duplicated_blocs[repeat.name] = repeat
for ele in old_repeat.current_positions:
old_instance = ele
self.old_instance_2_new_instance[old_instance] = dict()
new_instance = repeat.create_contig_instance()
self.old_instance_2_new_instance[old_instance]["new_instance"] = new_instance
self.old_instance_2_new_instance[old_instance]["remapped"] = False
def delete_duplicated_bloc(self,dup):
""""""
def add_modification_to_network(self,incoming_connection):
self.incoming_connections.append(incoming_connection)
def path_generator(self):
""" return paste and split operations to perform on duplicated blocs"""
""" update current network """
class ContigS():
# from contig import contig as contig
def __init__(self):
import numpy as np
import contig as CONTI
self.duplicator = duplicator(self,)
self.current_contigs = dict() # dictionary of current contigs entry : 1 -- n_contigs
self.init_contigs = dict() # dictionnary of initial contigs : name given by de-novo assembler
self.g_sigma = dict() # dictionnary of initial fragments
self.np_id_2_frag = dict() # dictionary conversion of matrix index to init fragment name
self.n_contigs = 0 # number of contigs
self.size_current_genome = 0
# C-structures sent to GPU !
self.frag_T = np.dtype([('mult', np.int32), ('pos_min',np.int32), ('pos_max',np.int32), ('alpha',np.int32)], align = True)
self.coord_T = np.dtype([('chrom', np.int32),
('pos_kb', np.float32),
('low', np.int32),
('high', np.int32),
('circular', np.int32),
('id_rel', np.int32),
('size_contig', np.int32),
('cumul_index', np.int32),
('alpha', np.float32)], align=True)
self.alpha_collect_T = np.dtype([('obsd', np.float64), ('expd', np.float64)], align=True)
def compute_size_current_genome(self):
from contig import contig
size_current_genome = 0
for c in self.current_contigs.keys():
cont = self.current_contigs[c]
if isinstance(cont,contig):
if cont.status == 'active':
size_current_genome += cont.n_frags
self.size_current_genome = size_current_genome
def clear(self):
self.current_contigs.clear()
self.init_contigs.clear()
self.g_sigma.clear()
self.np_id_2_frag.clear()
self.n_contigs.clear()
def add_new_composite(self,contig):
from colorama import Fore, Back, Style
from colorama import init
init(autoreset=True)
from contig import contig as class_contig
""" perform adding of a contig which contain repeats"""
curr_contig = contig
pos_cut = 0
list_id_sub_contig = []
# for ele in contig.composition:
test_condition = True
curr_pos = 0
jump_bloc = True
while test_condition:
# for ele in curr_contig.composition:
ele = curr_contig.composition[curr_pos]
# variable pour sauter de contig
init_contig = ele["init_contig"]
access_bloc = str(ele["id_frag_start"])+':'+str(ele["id_frag_end"])
length_bloc = ele["id_frag_end"] - ele["id_frag_start"] + 1
# if not(self.init_contigs.has_key(init_contig)):
# self.init_contigs[init_contig] = dict()
if self.init_contigs[init_contig].has_key(access_bloc):
if self.init_contigs[init_contig][access_bloc]["dup"]:
bloc_upstream, tmp_bloc = class_contig.split(curr_contig,pos_cut)
# add bloc_upstream
if not(bloc_upstream.name == ''):
# print "name upstream = ",bloc_upstream.name
# print " new compo = ", bloc_upstream.new_compo
if bloc_upstream.has_repeats() and len(bloc_upstream.new_compo) ==1 :# <- check if has repeats!!!
# bloc_upstream.update_repeats(self.duplicator.old_instance_2_new_instance)
old_instance = bloc_upstream.new_compo[0]["contig_id"]
id_upstream = self.duplicator.old_instance_2_new_instance[old_instance]["new_instance"]
else:
id_upstream = self.add(bloc_upstream)
# self.current_contigs[id_upstream].new_compo[0]["contig_id"] = id_upstream
self.current_contigs[id_upstream].reset_old_2_new_new_compo()
list_id_sub_contig.append(id_upstream)
# print " tmp bloc name = ",tmp_bloc.name
if not(tmp_bloc.name == ''):
# print "name tmp = ",tmp_bloc.name
dup_bloc, bloc_downstream = class_contig.split(tmp_bloc, length_bloc)
# nouveau contig defini
curr_contig = bloc_downstream
curr_pos = 0
pos_cut = 0
if not(dup_bloc.name == ''):
if dup_bloc.has_repeats() and len(dup_bloc.new_compo) ==1:# <- check if has repeats!!!
old_instance = dup_bloc.new_compo[0]["contig_id"]
id_bloc_dup = self.duplicator.old_instance_2_new_instance[old_instance]["new_instance"]
# dup_bloc.update_repeats(self.duplicator.old_instance_2_new_instance)
else:
id_bloc_dup = self.add(dup_bloc)
# self.current_contigs[id_bloc_dup].new_compo[0]["contig_id"] = id_bloc_dup
self.current_contigs[id_bloc_dup].reset_old_2_new_new_compo()
list_id_sub_contig.append(id_bloc_dup)
else:
# nouveau contig defini
curr_contig = tmp_bloc
curr_pos = 0
pos_cut = 0
else:
pos_cut += length_bloc
curr_pos += 1
else:
curr_pos += 1
pos_cut += length_bloc
len_curr_cont = len(curr_contig.composition)
if curr_contig.name == '':
test_condition = False
else:
if (curr_pos <len_curr_cont):
test_condition = True
else:
test_condition = False
if not(curr_contig.name == '' ):
# print Fore.BLUE + " on est dedans!"
# print "name last contig = ", curr_contig.name
if curr_contig.has_repeats() and len(curr_contig.new_compo) == 1:# <- check if has repeats!!!
# curr_contig.update_repeats(self.duplicator.old_instance_2_new_instance)
old_instance = curr_contig.new_compo[0]["contig_id"]
id_bloc = self.duplicator.old_instance_2_new_instance[old_instance]["new_instance"]
else:
id_bloc = self.add(curr_contig)
# self.current_contigs[id_bloc].new_compo[0]["contig_id"] = id_bloc
self.current_contigs[id_bloc].reset_old_2_new_new_compo()
list_id_sub_contig.append(id_bloc)
curr_contig = self.current_contigs[id_bloc]
# print " length contig = ",curr_contig.n_frags
# print " last contig id = ", curr_contig.contig_id
output = self.current_contigs[list_id_sub_contig[0]]
len_sub_contig = len(list_id_sub_contig)
# print "list sub contig = ", list_id_sub_contig
# print " len sub contig = ", len_sub_contig
if len_sub_contig>1:
for i in range(1,len(list_id_sub_contig)):
sub_contig = list_id_sub_contig[i]
print Fore.BLUE + output.name
print Fore.RED + self.current_contigs[sub_contig].name
output_tmp = self.paste(output,'w',
self.current_contigs[sub_contig],'w')
output = output_tmp
return output.contig_id
def add(self,contig):
self.n_contigs +=1
# add contig into current_contigs dictionary
contig.update_name(self.n_contigs)
self.current_contigs[self.n_contigs] = contig
for fragment in contig.FragmentS:
# update np_id_2_frag
# fragment.update_name(self.n_contigs)
self.np_id_2_frag[fragment.np_id_abs] = fragment.init_name
# update g_sigma
if fragment.init_name in self.g_sigma:
self.g_sigma[fragment.init_name].add(fragment.curr_name)
else:
self.g_sigma[fragment.init_name] = set()
self.g_sigma[fragment.init_name].add(fragment.curr_name)
#update init_contigs
for ele in contig.composition:
init_contig = ele['init_contig']
if init_contig in self.init_contigs:
position = str(ele['id_frag_start'])+':' + str(ele['id_frag_end'])
if not(self.init_contigs[init_contig].has_key(position)):
self.init_contigs[init_contig][position] = dict()
self.init_contigs[init_contig][position]['dup'] = False
bloc_tag = str(ele['pos_id'])+'@'+str(contig.contig_id)
self.init_contigs[init_contig][position][bloc_tag] = str(ele['orientation'])
# is_duplicated = self.init_contigs[init_contig][position]['dup']
# if is_duplicated: # update duplicator structure
# name_repeat = '>'+init_contig+':'+position+':w>'
# repeat = self.duplicator.duplicated_blocs[name_repeat]
# repeat.add_position(bloc_tag)
else:
self.init_contigs[init_contig] = dict()
position = str(ele['id_frag_start'])+':'+str(ele['id_frag_end'])
self.init_contigs[init_contig][position] = dict()
bloc_tag = str(ele['pos_id'])+'@'+str(contig.contig_id)
self.init_contigs[init_contig][position][bloc_tag] = str(ele['orientation'])
self.init_contigs[init_contig][position]['dup'] = False # track de la signature de duplication
for ele in contig.new_compo:
if ele["dup"]:
position = ele["position"]
orientation = ele["orientation"]
tmp_id_instance = ele["contig_id"]
# id_instance must be renew only at the beginning
id_instance = tmp_id_instance
# if self.duplicator.old_instance_2_new_instance[tmp_id_instance]["remapped"]:
# id_instance = tmp_id_instance
# else:
# id_instance = self.duplicator.old_instance_2_new_instance[tmp_id_instance]["new_instance"]
# self.duplicator.old_instance_2_new_instance[tmp_id_instance]["remapped"] = True
## self.duplicator.old_instance_2_new_instance[id_instance]["new_instance"] = id_instance
print "id instance = ", id_instance
ele["contig_id"] = id_instance
self.inactivate(self.current_contigs[id_instance]) # desactivation : dans tous les cas il est rajoute
name_repeat = self.current_contigs[id_instance].name # problem when going from genome t to genome ( t+1 )
repeat = self.duplicator.duplicated_blocs[name_repeat]
new_pos = dict()
new_pos['orientation'] = orientation
new_pos['position'] = position
new_pos['@'] = self.n_contigs
repeat.update_current_position(id_instance,new_pos)
self.compute_size_current_genome()
return self.n_contigs
def create_transparent_contig(self,):
from contig import contig as contig
transpa = contig.initiate("None",0,0,"w")
return transpa
def export_name_contigs(self,):
out = []
for ele in self.current_contigs:
curr_cont = self.current_contigs[ele]
if curr_cont.status == "active":
out.append(curr_cont.name)
return out
def print_active_contig(self):
from colorama import Fore, Back, Style
from colorama import init
init(autoreset=True)
print Fore.BLUE + "list active contig"
print "-----------------"
for ele in self.current_contigs:
curr_cont = self.current_contigs[ele]
if curr_cont.status == "active":
print Fore.RED + str(curr_cont.contig_id) + Fore.WHITE +" ==> " + Fore.GREEN + curr_cont.name
print "-----------------"
init(autoreset=True)
####################################################################################
################# basic mutations paste split duplicate inactivate activate ########
def inactivate(self, contig):
if self.current_contigs[contig.contig_id].status == 'active':
# print " on va inactiver les fragments et les retirer de g sigma. contig id = ",contig.contig_id
for fragment in contig.FragmentS:
# print " fragment curr name = " ,fragment.curr_name
# print " contenu g sigma = ", self.g_sigma[fragment.init_name]
# print "removing : ", fragment.curr_name
self.g_sigma[fragment.init_name].remove(fragment.curr_name)
try:
self.np_id_2_frag.pop(fragment.np_id_abs) # attention ....
except:
""
for ele in contig.composition:
init_contig = ele['init_contig']
position = str(ele['id_frag_start'])+':'+str(ele['id_frag_end'])
bloc_tag = str(ele['pos_id'])+'@'+str(contig.contig_id)
self.init_contigs[init_contig][position].pop(bloc_tag)
if self.init_contigs[init_contig][position] == {'dup':False}:
self.init_contigs[init_contig].pop(position)
for ele in contig.new_compo:
if ele["dup"]:
id_instance = ele["contig_id"]
# print "id instance = ", id_instance
name_repeat = self.current_contigs[id_instance].name
# print " name repeat = ", name_repeat
repeat = self.duplicator.duplicated_blocs[name_repeat]
repeat.remove_position(id_instance)
self.current_contigs[contig.contig_id].status = 'inactive'
self.compute_size_current_genome()
def reactivate(self,contig):
if self.current_contigs[contig.contig_id].status == 'inactive':
contig.status = 'active'
for fragment in contig.FragmentS:
# update np_id_2_frag
fragment.update_name(self.n_contigs)
self.np_id_2_frag[fragment.np_id_abs] = fragment.init_name
# update g_sigma
if self.g_sigma.has_key(fragment.init_name):
self.g_sigma[fragment.init_name].add(fragment.curr_name)
else:
self.g_sigma[fragment.init_name] = set()
self.g_sigma[fragment.init_name].add(fragment.curr_name)
#update init_contigs
for ele in contig.composition:
init_contig = ele['init_contig']
if self.init_contigs.has_key(init_contig):
position = str(ele['id_frag_start'])+':'+str(ele['id_frag_end'])
if not(self.init_contigs[init_contig].has_key(position)):
self.init_contigs[init_contig][position] = dict()
self.init_contigs[init_contig][position]["dup"] = False # added 23 /02 /2013
bloc_tag = str(ele['pos_id'])+'@'+str(contig.contig_id)
self.init_contigs[init_contig][position][bloc_tag] = str(ele['orientation'])
else:
self.init_contigs[init_contig] = dict()
position = str(ele['id_frag_start'])+':'+str(ele['id_frag_end'])
self.init_contigs[init_contig][position] = dict()
self.init_contigs[init_contig][position]['dup'] = False
bloc_tag = str(ele['pos_id'])+'@'+str(contig.contig_id)
self.init_contigs[init_contig][position][bloc_tag] = str(ele['orientation'])
for ele in contig.new_compo:
if ele["dup"]:
position = ele["position"]
orientation = ele["orientation"]
id_instance = ele["contig_id"]
name_repeat = self.current_contigs[id_instance].name
repeat = self.duplicator.duplicated_blocs[name_repeat]
new_pos = dict()
new_pos['orientation'] = orientation
new_pos['position'] = position
new_pos['@'] = contig.contig_id
repeat.add_position(id_instance,new_pos)
self.compute_size_current_genome()
return self.n_contigs
def duplicate(self,contig_a, pos_a,pos_b):
from contig import contig as contig
print "duplicate"
test_a = pos_a>=1
test_b = pos_b<=contig_a.n_frags
if test_a and test_b:
print "duplication possible"
bloc_duplicated = contig.duplicate(contig_a,pos_a,pos_b)
for ele in bloc_duplicated.new_compo:
ele['dup'] = True
id_bloc = self.add(bloc_duplicated)
else:
print "duplication impossible"
id_bloc = 0
return self.current_contigs[id_bloc]
def sort_blocs_in_old_2_new(self,contig_a):
sub_parts_tmp = contig_a.old_2_new.keys()
dico_tmp = dict()
for ele in sub_parts_tmp:
bla = int(ele.split(':')[0])
dico_tmp[bla] = ele
tmp_sub=[]
tmp_sub.extend(dico_tmp.keys())
tmp_sub.sort()
sub_parts = []
for ele in tmp_sub:
sub_parts.append(dico_tmp[ele])
return sub_parts
def pos_in_bloc_2_global_pos(self,contig,pos_in_bloc,bloc_id):
output = dict()
t = range(0,bloc_id - 1)
cumul_length = 0
print "contig new compo = ", contig.new_compo
print "contig name = ", contig.name
print "pos in bloc :", pos_in_bloc
print "bloc id = ", bloc_id
for h in t:
start = contig.new_compo[h]['start']
end = contig.new_compo[h]['end']
len_bloc = end - start + 1
cumul_length += len_bloc
start = contig.new_compo[bloc_id - 1]['start']
end = contig.new_compo[bloc_id - 1]['end']
len_bloc = end - start + 1
orientation = contig.new_compo[bloc_id - 1]["orientation"]
if orientation == 'w':
output["reverse_order"] = False
new_pos = cumul_length + pos_in_bloc
output["new_pos"] = new_pos
output["orientation"] = 'w'
else:
new_pos = cumul_length + (len_bloc - pos_in_bloc) + 1
output["reverse_order"] = True
output["new_pos"] = new_pos - 1 # because split will take the upper part of the contig
output["orientation"] = 'c'
return output
def find_new_position(self, contig_a, pos_a):
sorted_blocs = self.sort_blocs_in_old_2_new(contig_a)
output = dict()
output["upstream"] = dict()
output["downstream"] = dict()
output["safe_split"] = True
output["classic"] = dict()
i = 0
sum_size_previous_blocs = 0
size_previous_blocs = [0]
print "pos_a = ", pos_a
print "sorted blocs = "
print sorted_blocs
for ele in sorted_blocs:
print "sub parts = ", ele
tmp = ele.split(':')
low_lim = int(tmp[0])
high_lim = int(tmp[1])
size_bloc = high_lim - low_lim + 1
pos_in_bloc = pos_a - sum_size_previous_blocs
is_good_bloc = (pos_a >= low_lim and pos_a <= high_lim) or ((pos_a == 0) and (i ==0) )
# test if pos fall into a duplicated bloc ...
if is_good_bloc:
is_on_edge = False
if pos_a == high_lim:
print "output complex"
output["safe_split"] = False
cont_up_id = contig_a.old_2_new[ele]['contig_id']
up_bloc_id = contig_a.old_2_new[ele]['position']
cont_up = self.current_contigs[cont_up_id]
print "pos in bloc = ", pos_in_bloc
out_up = self.pos_in_bloc_2_global_pos(cont_up,pos_in_bloc,up_bloc_id)
output["upstream"]["bloc"] = ele
output["upstream"]["contig"] = cont_up
output["upstream"]["cut_info"] = out_up
output["upstream"]["exists"] = True
if i == len(sorted_blocs) - 1: # l index dnas les sorted blocs va de 0 a len -1
output["downstream"]["exists"] = False
output["downstream"]["bloc"] = "none"
output["downstream"]["contig"] = "none"
output["downstream"]["cut_info"] = "none"
else:
#find downstream
down_bloc = sorted_blocs[i + 1]
output["downstream"]["exists"] = True
output["downstream"]["bloc"] = down_bloc
cont_down_id = contig_a.old_2_new[down_bloc]['contig_id']
down_bloc_id = contig_a.old_2_new[down_bloc]['position']
cont_down = self.current_contigs[cont_down_id]
# pos_in_bloc_downstream = (pos_a + 1) - (sum_size_previous_blocs + size_bloc)
pos_in_bloc_downstream = 0
out_down = self.pos_in_bloc_2_global_pos(cont_down,pos_in_bloc_downstream,down_bloc_id)
output["downstream"]["bloc"] = down_bloc
output["downstream"]["contig"] = cont_down
output["downstream"]["cut_info"] = out_down
elif pos_a == 0:
print "output complex"
output["safe_split"] = False
cont_down_id = contig_a.old_2_new[ele]['contig_id']
down_bloc_id = contig_a.old_2_new[ele]['position']
cont_down = self.current_contigs[cont_down_id]
print "pos in bloc = ",pos_in_bloc
out_down = self.pos_in_bloc_2_global_pos(cont_down,pos_in_bloc,down_bloc_id)
output["downstream"]["bloc"] = ele
output["downstream"]["contig"] = cont_down
output["downstream"]["cut_info"] = out_down
output["downstream"]["exists"] = True
output["upstream"]["exists"] = False
output["upstream"]["bloc"] = "none"
output["upstream"]["contig"] = "none"
output["upstream"]["cut_info"] = "none"
else:
print "output classic"
data_bloc = contig_a.old_2_new[ele]
bloc_id = data_bloc['position']
contig_id = data_bloc['contig_id']
contig_to_split = self.current_contigs[contig_id]
output["classic"]["contig"] = contig_to_split
print "ele"
output["classic"]["bloc"] = ele
status = contig_to_split.status
# if status == 'active':
print " successful candidate to split = ", contig_to_split.name
out_classic = self.pos_in_bloc_2_global_pos(contig_to_split,pos_in_bloc,bloc_id)
output["classic"]["cut_info"] = out_classic
i +=1
sum_size_previous_blocs += size_bloc
size_previous_blocs.append(size_bloc)
return output
def post_split_update(self,contig_a, contig_1, contig_2):
# print "inactivate contig = ",contig_a.contig_id
self.inactivate(contig_a)
id_1 = self.add(contig_1)
id_2 = self.add(contig_2)
for ele in self.current_contigs[id_1].new_compo:
if (ele['dup']): # update duplicator and repeat object
position = ele["position"]
orientation = ele["orientation"]
id_instance = ele["contig_id"]
name_repeat = self.current_contigs[id_instance].name
repeat = self.duplicator.duplicated_blocs[name_repeat]
new_pos = dict()
new_pos['orientation'] = orientation
new_pos['position'] = position
new_pos['@'] = id_1
repeat.update_current_position(id_instance,new_pos)
start = ele['start']
end = ele['end']
pos = str(start)+':'+str(end)
self.current_contigs[ele['contig_id']].old_2_new[pos] = {'contig_id':id_1,'position':ele['position'],'orientation':ele['orientation']}
tmp_n_frags = self.current_contigs[ele['contig_id']].n_frags
pos_all = '1:'+str(tmp_n_frags)
for ele in self.current_contigs[id_2].new_compo:
if (ele['dup']): # update duplicator and repeat object
position = ele["position"]
orientation = ele["orientation"]
id_instance = ele["contig_id"]
name_repeat = self.current_contigs[id_instance].name
repeat = self.duplicator.duplicated_blocs[name_repeat]
new_pos = dict()
new_pos['orientation'] = orientation
new_pos['position'] = position
new_pos['@'] = id_2
repeat.update_current_position(id_instance,new_pos)
start = ele['start']
end = ele['end']
pos = str(start)+':'+str(end)
self.current_contigs[ele['contig_id']].old_2_new[pos] = {'contig_id':id_2,'position':ele['position'],'orientation':ele['orientation']}
tmp_n_frags = self.current_contigs[ele['contig_id']].n_frags
pos_all = '1:'+str(tmp_n_frags)
return id_1, id_2
def genome_2_abs_frag_vect(self):
abs_frag_vect = []
list_key = self.current_contigs.keys()
list_key.sort()
for contig in list_key:
if self.current_contigs[contig].status == 'active':
# be carefull with duplicated elements
abs_frag_vect.extend(self.current_contigs[contig].export_abs_frag_vect())
return abs_frag_vect
def export_kb_pos_and_ctg_id(self):
kb_pos_and_ctg_id = []
list_key = self.current_contigs.keys()
list_key.sort()
for contig in list_key:
if self.current_contigs[contig].status == 'active':
kb_pos_and_ctg_id.extend(self.current_contigs[contig].export_kb_pos_and_ctg_id())
return kb_pos_and_ctg_id
def extract_info_frag(self,fragment_name):
import numpy as np
# print fragment_name
data = fragment_name.split('-')
id_frag = np.int32(data[0])
contig_id =np.int32(int(data[1]))
pos_kb = np.int32(int(float(data[2]) ))
return id_frag, contig_id,pos_kb
def export_pos_frag(self,):
"deprecated"
import numpy as np
ind = -1
pos_frag = []
pos_frag.extend(self.np_id_2_frag.keys())
pos_frag.sort()
index_frag = np.zeros(len(pos_frag),dtype=np.int32)
frag_multi_pos = []
for np_frag in pos_frag:
init_frag = self.np_id_2_frag[np_frag]
multi_frags = self.g_sigma[init_frag]
for ele in multi_frags:
id_frag,contig_id,pos_kb = self.extract_info_frag(ele)
frag_multi_pos.extend([int(pos_kb),int(contig_id)])
ind +=2
# print np_frag
index_frag[np_frag-1] = ind
frag_multi_pos_np = np.array(frag_multi_pos,dtype=np.int32)
return index_frag,frag_multi_pos_np
def export_dico_frags_per_contig(self,):
import numpy as np
output_dico = dict()
for contg in self.current_contigs.keys():
tmp_ctg = self.current_contigs[contg]
tmp_frag_np = []
for frag in tmp_ctg.FragmentS:
tmp_frag_np.append(frag.np_id_abs - 1)
output_dico[contg] = np.array(tmp_frag_np,dtype = np.int32)
return output_dico
def export_index_matrix(self,):
out_np_index = []
out_np_ori = []
out_dup = []
n_frags = len(self.np_id_2_frag)
rev_np_index = np.zeros((n_frags), dtype=np.int32)
out_np_index = np.zeros((n_frags), dtype=np.int32)
new_id = 0
for ele in self.current_contigs:
cont = self.current_contigs[ele]
if cont.status == "active":
k = 0
for ele in cont.FragmentS:
np_id = ele.np_id_abs - 1
orientation = ele.orientation
bloc = self.return_bloc(cont, k + 1)
init_contig = ele.init_contig
# print "init contig = ",init_contig
is_duplicated = self.init_contigs[init_contig][bloc]['dup']
if is_duplicated:
out_dup.append(1)
else:
out_dup.append(0)
out_np_index[new_id] = np_id
out_np_ori.append(orientation)
rev_np_index[np_id] = new_id
k += 1
new_id += 1
return out_np_index, rev_np_index, out_np_ori
def clean_current_contigs(self,):
list_contigs = self.current_contigs.keys()
for c in list_contigs:
if self.current_contigs[c].status =='inactive':
self.current_contigs.pop(c)
def export_pos_frag_2_np_cl(self,):
import numpy as np
from contig import contig as contig
dico_contigs = dict()
length_contigs = []
rev_dict = dict()
list_contigs = self.current_contigs.keys()
# list_contigs.sort()
for c in list_contigs:
cont = self.current_contigs[c]
if isinstance(cont,contig):
if cont.status == 'active':
length_contigs.append(cont.n_frags)
dico_contigs[cont.contig_id] = dict()
dico_contigs[cont.contig_id]['length'] = cont.n_frags
# rel pos = position relative du contig dans la liste des contigs actifs
rel_pos = len(length_contigs) - 1
dico_contigs[cont.contig_id]['rel_pos'] = rel_pos
rev_dict[rel_pos] = cont.contig_id
# else:
# self.current_contigs.pop(c)
tmp_cumulu = ( (length_contigs[0] +1)*length_contigs[0])/2
dico_contigs[rev_dict[0]]['cumul_index'] = 0
dico_contigs[rev_dict[0]]['cumul_index_max'] = tmp_cumulu - 1
prec = tmp_cumulu
for i in xrange(1,len(length_contigs)):
dico_contigs[rev_dict[i]]['cumul_index'] = prec
cumulu = ((length_contigs[i] +1)*length_contigs[i]) / 2
tmp_cumulu = prec + cumulu
dico_contigs[rev_dict[i]]['cumul_index_max'] =tmp_cumulu -1
prec = tmp_cumulu
# on considere que les virtua contigs sont ordonnes ...
pos_frag = []
pos_frag.extend(self.np_id_2_frag.keys())
pos_frag.sort()
frag_coord_pos = []
frag_list = []
# construction dtype collect alpha contigs to do later!!!
alpha_collect = []
for i in xrange(0,len(length_contigs)):
cumulu = np.int32(((length_contigs[i] +1)*length_contigs[i])) / np.int32(2)
alpha_collect.append(cumulu)
id = 0
for np_frag in pos_frag:
init_frag = self.np_id_2_frag[np_frag]
multi_frags = self.g_sigma[init_frag]
n_multi_frag = len(multi_frags)
pos_data_0 = id
for ele in multi_frags:
id += 1
curr_id_frag, contig_id, pos_kb = self.extract_info_frag(ele)
low = self.current_contigs[contig_id].FragmentS[0].np_id_abs - 1
high = self.current_contigs[contig_id].FragmentS[-1].np_id_abs - 1
id_frag_rel = curr_id_frag - 1
circular = 0
size_contig = dico_contigs[contig_id]['length']
# print "size contig = ",size_contig
cumul_index = dico_contigs[contig_id]['cumul_index']
alpha = 0
frag_coord_pos.append((np.int32(contig_id),
np.float32(pos_kb),
np.int32(low),
np.int32(high),
np.int32(circular),
np.int32(id_frag_rel),
np.int32(size_contig),
np.int32(cumul_index),
np.float32(alpha)))
pos_data_1 = id - 1
frag_list.append((np.int32(n_multi_frag), np.int32(pos_data_0), np.int32(pos_data_1),np.int32(0)))
frag_multi_pos_np = np.array(frag_coord_pos,dtype=self.coord_T)
frag_list_np = np.array(frag_list,dtype = self.frag_T)
alpha_collect = np.array(alpha_collect)
n_alpha = alpha_collect.sum()
alpha_collect_np = np.zeros( (n_alpha,), dtype=self.alpha_collect_T)
# print "n element alpha collect = ", alpha_collect.sum()
# print "size np alpha collect = ", alpha_collect_np.shape
# print "n alpha = ", n_alpha
# for ele in range(0,n_alpha):
# alpha_collect_np[ele]['obsd'] = np.float64(0)
# alpha_collect_np[ele]['expd'] = np.float64(0)
return frag_list_np, frag_multi_pos_np, alpha_collect_np, dico_contigs
def candidate_deletion(self,contig_a):
# modifiable : augmente duplicated blocs en rajoutant les combinaison possible de bloc existant !!!
# homogeneite : meme contig initial et meme niveau de multiplication
# version actuelle: destruction des blocs homogenes de contigs
# pour la mutation inverse il suffit d aller dans le dictionnaire des contigs initiaux et de prendre un candidat para ceux existant !!!
print "scan contig to find possible deletion"
pos_duplication = []
FragS = contig_a.FragmentS
for frag in FragS:
data = self.g_sigma[frag.init_name]
n_repeats = data.__len__()
init_contig = frag.init_contig
id_init = frag.id_init
orientation = frag.orientation
pos_duplication.append([n_repeats, init_contig, id_init,orientation])
tmp = []
duplicated_blocs = []
prec_n_repeats = pos_duplication[0][0]
prec_init_contig = pos_duplication[0][1]
prec_id_init = pos_duplication[0][2]
prec_orientation = pos_duplication[0][3]
for i in range(0,len(pos_duplication)):
n_repeats = pos_duplication[i][0]
init_contig = pos_duplication[i][1]
id_init = pos_duplication[i][2]
orientation = pos_duplication[i][3]
test1 = n_repeats>1
test2 = init_contig == prec_init_contig
test3 = orientation == prec_orientation
test4 = orientation == 'w'
test5 = not(n_repeats == prec_n_repeats)
if test1:
if test2:
dif_id = id_init - prec_id_init
if (dif_id == 0) or abs(dif_id>1) or not(test3) or (test5):
if len(tmp)>0:
duplicated_blocs.append([min(tmp) + 1 , max(tmp) + 1 ])
tmp = []
else:
tmp.append(i)
elif (dif_id == -1) and test3 and test4:
if len(tmp)>0:
duplicated_blocs.append([min(tmp) + 1 , max(tmp) + 1 ])
tmp = []
else:
tmp.append(i)
elif (dif_id) == 1 and test3 and not(test4):
if len(tmp)>0:
duplicated_blocs.append([min(tmp) + 1 , max(tmp) + 1 ])
tmp = []
else:
tmp.append(i)
else:
tmp.append(i)
else:
if len(tmp)>0:
duplicated_blocs.append([min(tmp) + 1 , max(tmp) + 1 ])
tmp = []
else:
tmp.append(i)
else:
if len(tmp)>0:
duplicated_blocs.append([min(tmp) + 1 , max(tmp) + 1 ])
tmp = []
prec_n_repeats = n_repeats
prec_id_init = id_init
prec_init_contig = init_contig
prec_id_init = id_init
prec_orientation = orientation
return duplicated_blocs
########################################################################################################################
########################################################################################################################
def opposite_or(self,orientation):