-
Notifications
You must be signed in to change notification settings - Fork 3
/
utility.py
2723 lines (2108 loc) · 81.4 KB
/
utility.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
#encoding:utf-8
#-*- coding: utf-8 -*-
from optparse import OptionParser
import os.path
import pandas as pd
import numpy as np
import os
import sys
import math
import random
import scipy
import scipy.io
from numpy.lib.recfunctions import append_fields
import sklearn.preprocessing
from sklearn.externals import joblib
from sklearn.metrics import average_precision_score,precision_score,recall_score,f1_score
from sklearn.metrics import roc_auc_score,accuracy_score,matthews_corrcoef
from sklearn import datasets
from sklearn import cluster
from sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_mutual_info_score, adjusted_rand_score
from sklearn import metrics
from sklearn.metrics import pairwise_distances
from scipy.special import comb
import copy
import scipy.ndimage
import warnings
import multiprocessing as mp
from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral)
import medpy
from medpy.filter.smoothing import anisotropic_diffusion
import multiprocessing as mp
import threading
import time
import matplotlib
import matplotlib.pyplot as plt
matplotlib.pyplot.switch_backend('agg')
THRESH1=1e-05
def merge_contact_file(path1, output_filename1):
# filename1 = 'merge_contact_file.txt'
chrom_vec = np.asarray(range(1,23))
colnames1 = ['chrom','start1','start2','value']
num1 = len(chrom_vec)
for i in range(0,num1):
chrom_id = chrom_vec[i]
print chrom_id
filename1 = '%s/chr%d.50K.txt'%(path1,chrom_id)
# filename1 = '%s/chr%d.observed.kr.50K.txt'%(path1,chrom_id)
data1 = pd.read_table(filename1,header=None)
colnames = list(data1)
# start1, start2, value = data1[colnames[0]], data1[colnames[1]], data1[colnames[2]]
t_data = pd.DataFrame(columns=colnames1)
n1 = data1.shape[0]
str1 = 'chr%d'%(chrom_id)
t_data[colnames1[0]] = [str1]*n1
for j in range(0,3):
t_data[colnames1[j+1]] = data1[colnames[j]]
if i==0:
data_1 = t_data
else:
data_1 = data_1.append(t_data)
data_1.to_csv(output_filename1,header=False,index=False,na_rep='NAN',sep='\t')
return True
def merge_estimate_file(path1, species_vec, output_filename1):
# filename1 = 'merge_contact_file.txt'
chrom_vec = np.asarray(range(1,23))
colnames1 = ['chrom','start1','start2','value']
# 17 250000 300000 17 1900000 1950000 8 1.6882 1.4702 1.7545 0.9343
num1 = len(chrom_vec)
for i in range(0,num1):
chrom_id = chrom_vec[i]
print chrom_id
filename1 = '%s/test%d.txt'%(path1,chrom_id)
data1 = pd.read_table(filename1,header=None)
colnames = list(data1)
sub_colnames = [colnames[0],colnames[1],colnames[4],colnames[7],colnames[8],colnames[9],colnames[10]]
# start1, start2, value = data1[colnames[0]], data1[colnames[1]], data1[colnames[2]]
# t_data = pd.DataFrame(columns=colnames1)
t_data = data1.loc[:,sub_colnames]
n1 = t_data.shape[0]
str1 = 'chr%d'%(chrom_id)
t_data[colnames[0]] = [str1]*n1
if i==0:
data_1 = t_data
else:
data_1 = data_1.append(t_data)
data_1.to_csv(output_filename1,header=False,index=False,sep='\t')
# species_vec = ['hg38','panTro5','panPan2','gorGor4']
num2 = len(species_vec)
for i in range(0,num2):
sub_colnames = [colnames[0],colnames[1],colnames[4],colnames[7+i]]
data_2 = data_1.loc[:,sub_colnames]
filename1 = 'estimate_%s.txt'%(species_vec[i])
data_2.to_csv(filename1,header=False,index=False,sep='\t')
return True
def intersect_region(file1, file2):
data1 = pd.read_table(file1,header=None)
data2 = pd.read_table(file2,header=None)
chrom1, chrom2 = data1[0], data2[0]
start1, stop1, start2, stop2 = data1[1], data1[2], data2[1], data2[2]
serial1, serial2 = data1[3], data2[3]
num1 = len(serial2)
matched_Idx = -np.ones(num1)
t_chrom1, t_start1, t_stop1 = chrom1[serial2], start1[serial2], stop1[serial2]
flag = (t_chrom1==chrom2)&(t_start1<stop2)&(t_stop1>start2)
b = np.where(flag==True)[0]
matched_Idx = serial2[b]
print "matched_Idx", len(matched_Idx), len(matched_Idx)*1.0/len(serial1)
return matched_Idx, serial2
def write_tobed(filename,output_filename):
data1 = pd.read_table(filename,header=None)
chrom, start, stop = data1[0], data1[1], data1[2]
serial = np.asarray(range(0,len(chrom)))
colnames = ['chrom','start','stop','serial']
data2 = pd.DataFrame(columns=colnames)
data2['chrom'], data2['start'], data2['stop'], data2['serial'] = chrom, start, stop, serial
data2.to_csv(output_filename,header=False,index=False,sep='\t')
return True
def state_enrichment(chrom1, state_vec, filename1, filename2):
chrom_vec = np.unique(chrom1)
state_vec_unique = np.unique(state_vec)
chrom_num = len(chrom_vec)
state_num_unique = len(state_vec_unique)
mtx1 = np.zeros((chrom_num,state_num_unique))
fold_change = mtx1.copy()
num1 = len(state_vec)
ratio_vec = np.zeros(state_num_unique)
for j in range(0,state_num_unique):
b = np.where(state1==state_vec_unique[j])
ratio_vec[j] = len(b)*1.0/num1
for i in range(0,chrom_num):
b = np.where(chrom1==chrom_vec[i])
state1 = state_vec[b]
t_num1 = length(state1)
for j in range(0,state_num_unique):
b = np.where(state1==state_vec_unique[j])
mtx1[i,j] = len(b)*1.0/t_num1
fold_change[i,j] = mtx1[i,j]/ratio_vec[j]
eps = 1e-16
return np.log2(fold_change+eps), fold_change
def find_region(filename1, threshold):
fid = open(filename1,'r')
lines = fid.readlines()
# close the file after reading the lines.
fid.close()
num1 = len(lines)
i = 0
mdict = {}
mdict1 = {}
# threshold = 50*50000
while i<num1:
print i
if lines[i][0]!='>' and i+4<num1 and lines[i].find(':')>=0:
segment = lines[i:i+4]
t_chrom_vec = []
t_len_vec = []
for k in range(0,4):
if segment[k].find(':')<0:
print segment[k]
return False
vec1 = segment[k].split(' ')
vec1 = vec1[0].split(':')
t1 = vec1[0].split('.')
t2 = vec1[1].split('-')
t_chrom_vec.append(t1[1])
start, stop = int(t2[0]), int(t2[1])
len1 = stop-start
t_len_vec.append([start,stop,len1])
print t_chrom_vec, t_len_vec
t_len_vec1 = np.asarray(t_len_vec)
flag = find_region1(t_chrom_vec, t_len_vec1[:,-1], threshold)
print i,flag
if flag==True:
chrom = t_chrom_vec[0]
if chrom in mdict.keys():
mdict[chrom].extend(t_len_vec)
mdict1[chrom].append(t_len_vec[0])
else:
mdict[chrom] = t_len_vec
mdict1[chrom] = [t_len_vec[0]]
i = i+4
else:
i+=1
return mdict, mdict1
def find_region1(chrom_vec, len_vec, threshold):
num1 = len(chrom_vec)
chrom = chrom_vec[0]
for i in range(1,num1):
if chrom=='chr2':
if chrom_vec[i]!='chr2A' and chrom_vec[i]!='chr2B' and chrom_vec[i]!='chr2':
return False
else:
if chrom_vec[i]!=chrom:
return False
if min(len_vec)<threshold:
return False
return True
def cnt_estimate(x, state, n_components):
# x = np.load(filename1)
n_features = x.shape[0]
cnt_vec = np.zeros(n_components)
state_vec = np.unique(state)
threshold1 = [0.003,0.25,0.5,0.75,0.997]
m_vec1 = []
num1 = len(state_vec)
for i in range(0,num1):
state1 = state_vec[i]
b1 = np.where(state==state1)[0]
cnt_vec[state1] = len(b1)
x1 = x[b]
for j in range(0,n_features):
t_x1 = x1[:,j]
temp1 = np.quantile(t_x1,threshold1)
temp2 = [state1]
temp2.extend(list(temp1))
m_vec1.append(temp2)
return cnt_vec, np.asarray(m_vec1)
def load_data_chromosome2(chrom_vec, x_max, x_min, resolution, num_neighbor, filter_mode, sigma, diagonal_typeId,
ref_filename, filename_list, species, data_path, annotation):
edge_list_vec = []
samples = []
# sample_id = []
len_vec = []
id1, id2 = 0, 0
start = time.time()
queue1 = mp.Queue()
# chrom_vec = range(20,22)
# chrom_vec = [1,9,10]
print("processes")
start = time.time()
# processes = [mp.Process(target=self._compute_posteriors_graph_test, args=(len_vec, X, region_id,self.posteriors_test,self.posteriors_test1,self.queue)) for region_id in range(0,num_region)]
processes = [mp.Process(target=load_data_chromosome_sub1_2,
args=(chrom_id, x_max, x_min, resolution, num_neighbor, filter_mode, sigma, diagonal_typeId,
ref_filename, filename_list, species, data_path, queue1)) for chrom_id in chrom_vec]
# Run processes
for p in processes:
p.start()
results = [queue1.get() for p in processes]
print(len(results))
# Exit the completed processes
print("join")
for p in processes:
p.join()
end = time.time()
print("use time load chromosomes: %s %s %s"%(start, end, end-start))
chrom_num = len(chrom_vec)
chrom_vec1 = np.zeros(chrom_num)
for i in range(0,chrom_num):
vec1 = results[i]
chrom_vec1[i] = vec1[0]
sort_idx = np.argsort(chrom_vec1)
samples = []
len_vec = []
edge_list_vec = []
n_samples_accumulate = 0
id_1 = 0
id_2 = 0
for id1 in sort_idx:
vec1 = results[id1]
t_samples, t_lenvec, t_edgelistVec = vec1[1], vec1[2], vec1[3]
samples.extend(t_samples)
for temp1 in t_lenvec:
temp1[1] += n_samples_accumulate
temp1[2] += n_samples_accumulate
len_vec.append(temp1)
n_samples = t_samples.shape[0]
n_samples_accumulate += n_samples
print "chr%s: %d"%(vec1[0],n_samples)
edge_list_vec.extend(t_edgelistVec)
return np.asarray(samples), len_vec, edge_list_vec
# load data for diagonal regions and off-diagonal regions
def load_data_chromosome_sub1_2(chrom_id, x_max, x_min, resolution, num_neighbor, filter_mode,
sigma, diagonal_typeId, ref_filename, filename_list, species, data_path, m_queue):
# resolution = 50000
chrom = str(chrom_id)
# write contact frequency of different species into an array (n_samples*(n_position+n_species))
# ref_species = 'hg38'
type_id = 0
# output_filename = "%s_test1.txt"%(chrom)
output_filename = "" # if want to save the aligned contact files, please specify the filename
# multi_contact_matrix3A(chrom, resolution, output_filename, type_id)
data_ori = multi_contact_matrix3A(chrom, resolution, ref_filename, filename_list, species, output_filename, type_id)
species_num = len(species)
# filename1 = output_filename
# data_ori = pd.read_table(filename1) # load DataFrame file
colnames = list(data_ori)
position = np.asarray(data_ori.loc[:,colnames[0:3]])
x1 = np.asarray(data_ori.loc[:,colnames[3:]])
# print x1.shape
# print x1[0:10]
x1, vec1, x_min, x_max = normalize_feature(x1,x_min,x_max)
# print np.max(x1,axis=0), np.min(x1,axis=0), np.std(x1,axis=0)
# print vec1
# log transformation
x = np.log(1+x1)
# region_list = []
region_points = []
# data_path = "inferCars/DATA/chrom"
# filename3 = "%s/chr%s.synteny.50.hg38.txt"%(data_path,chrom)
filename3 = "%s/chr%s.synteny.txt"%(data_path,chrom)
# t_lenvec = np.loadtxt(filename3, dtype='int', delimiter='\t') # load *.txt file
# temp1 = np.ravel(t_lenvec)
# if len(temp1)<6:
# region_list.append(t_lenvec)
# region_num = 1
# else:
# region_num = len(t_lenvec)
# for i in range(0,region_num):
# region_list.append(t_lenvec[i])
# print region_list
# handle the large synteny block size of chr3 and chr6 in genome hg38
# region_points_vec stores the centromere positions of chr3 and chr6 in genome hg38
# the large-size synteny blocks on chr3 and chr6 are diveided into smaller parts according to the centromere positions
# this only applies if the reference genome is genome hg38
region_points_vec = np.asarray([[3,90279522,93797661],[6,57542947,61520508]])
b1 = np.where(region_points_vec[:,0]==chrom_id)[0]
if len(b1)>0:
for id1 in b1:
region_points.append(region_points_vec[id1,1:])
print "region_points 1", region_points
# region_list1: start, stop, length, region_id
# region_list2: position1,position2,position1,position2,length,length,region_id,region_id1,chrom_id
region_list1, region_list2_ori = subregion1(filename3, chrom_id, resolution, region_points, type_id)
num1 = len(region_list2_ori)
region_list2 = []
if diagonal_typeId==1:
temp1 = np.asarray(region_list2_ori)
temp2 = (temp1[:,0]==temp1[:,2])&(temp1[:,1]==temp1[:,3])
b = np.where(temp2==True)[0]
region_list2 = [region_list2_ori[idx] for idx in b]
else:
region_list2 = region_list2_ori
# print "diagonal_typeId, region_list2", diagonal_typeId, region_list2
filter_param1, filter_param2 = -1, -1
start = time.time()
if filter_mode==0:
filter_param1, filter_param2 = 5, 50
param_vec = [resolution, num_neighbor, filter_mode, filter_param1, filter_param2, sigma]
region_num = len(region_list2)
queue1 = mp.Queue()
print("processes")
start = time.time()
# processes = [mp.Process(target=self._compute_posteriors_graph_test, args=(len_vec, X, region_id,self.posteriors_test,self.posteriors_test1,self.queue)) for region_id in range(0,num_region)]
processes = [mp.Process(target=load_data_chromosome_sub3,
args=(region_id, chrom_id, region_list2, x, position, param_vec, queue1)) for region_id in range(0,region_num)]
# Run processes
for p in processes:
p.start()
results = [queue1.get() for p in processes]
print(len(results))
# Exit the completed processes
print("join")
for p in processes:
p.join()
region_vec1 = np.zeros(region_num)
for i in range(0,region_num):
vec1 = results[i]
region_vec1[i] = vec1[0]
sort_idx = np.argsort(region_vec1)
samples = []
len_vec = []
edge_list_vec = []
id_1 = 0
id_2 = 0
for id1 in sort_idx:
vec1 = results[id1]
print "region %d"%(vec1[0])
t_samples, t_lenvec, t_edgelist = vec1[1], vec1[2], vec1[3]
n_samples = t_samples.shape[0]
id_2 = id_1 + n_samples
t_lenvec.insert(1,id_2)
t_lenvec.insert(1,id_1)
id_1 = id_2
print t_lenvec
samples.extend(t_samples)
len_vec.append(t_lenvec)
edge_list_vec.append(t_edgelist)
m_queue.put((chrom_id, np.asarray(samples), len_vec, edge_list_vec))
end = time.time()
print("use time load chromosome %d: %s %s %s"%(chrom_id, start, end, end-start))
return True
def load_data_chromosome_sub3(region_id, chrom_id, region_list, x, position, param_vec, m_queue):
print "select regions..."
chrom = str(chrom_id)
start = time.time()
t_position1 = region_list[region_id]
position1, position2, position1a, position2a = t_position1[0], t_position1[1], t_position1[2], t_position1[3]
# region_id, type_id1 = t_position[6], t_position[7]
region_id1, region_id2 = t_position1[6], t_position1[7]
resolution, num_neighbor, filter_mode, filter_param1, filter_param2, sigma = param_vec[0], param_vec[1], param_vec[2], param_vec[3], param_vec[4], param_vec[5]
type_id1 = 0
if (position1==position1a) and (position2==position2a):
type_id1 = 1
# print position1, position2, position1a, position2a, region_id, type_id1
# output_filename3 = "%s/chr%s.%dKb.select2.%s.%d.%d.R5.test.1.txt"%(output_path,chrom,int(resolution/1000),annot1,position1,position2)
output_filename = ""
# x1, idx = utility1.select_valuesPosition1(position, x, output_filename3, position1, position2, resolution)
border_type = 0
x1, idx = select_valuesPosition1_2(position, x, output_filename, position1, position2, position1a, position2a, resolution, border_type)
t_position = position[idx,:]
# output_filename1 = "data1_mtx.test.%s.R5.test.txt"%(annot2)
output_path = "."
output_filename1 = ""
output_filename2 = "%s/chr%s.%dKb.edgeList.txt"%(output_path,chrom,int(resolution/1000))
if(os.path.exists(output_filename1)==True):
output_filename1 = ""
if(os.path.exists(output_filename2)==True):
output_filename2 = ""
if type_id1==1:
# x1, mtx1, t_position, edge_list_1 = utility1.write_matrix_image_Ctrl_v2(x1,t_position,output_filename1,output_filename2,
# num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
type_id = 1
print "write_matrix_image_Ctrl_unsym1"
x1, mtx1, t_position, edge_list_1 = write_matrix_image_Ctrl_unsym1(x1,t_position,output_filename1,output_filename2,
num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
start_region1 = np.min(t_position)
start_region2 = start_region1
else:
type_id = 0
print "write_matrix_image_Ctrl_sym1"
x1, mtx1, t_position, edge_list_1 = write_matrix_image_Ctrl_sym1(x1,t_position,output_filename1,output_filename2,
num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
temp1 = np.min(t_position,0)
start_region1, start_region2 = temp1[0], temp1[1]
n_samples = x1.shape[0]
# type_id1=1: diagonal type; type_id1=0: off-diagonal type
t_lenvec = [n_samples,mtx1.shape[0],mtx1.shape[1],start_region1,start_region2,region_id1,type_id1,chrom_id]
m_queue.put((region_id, x1, t_lenvec, edge_list_1))
end = time.time()
print "select regions use time %s %d: %s"%(chrom, region_id, (end-start))
return True
def load_data_chromosome_sub3_position(region_id, chrom_id, region_list, x, position, param_vec, m_queue):
print "select regions..."
chrom = str(chrom_id)
start = time.time()
t_position1 = region_list[region_id]
position1, position2, position1a, position2a = t_position1[0], t_position1[1], t_position1[2], t_position1[3]
# region_id, type_id1 = t_position[6], t_position[7]
region_id1, region_id2 = t_position1[6], t_position1[7]
resolution, num_neighbor, filter_mode, filter_param1, filter_param2, sigma = param_vec[0], param_vec[1], param_vec[2], param_vec[3], param_vec[4], param_vec[5]
type_id1 = 0
if (position1==position1a) and (position2==position2a):
type_id1 = 1
# print position1, position2, position1a, position2a, region_id, type_id1
# output_filename3 = "%s/chr%s.%dKb.select2.%s.%d.%d.R5.test.1.txt"%(output_path,chrom,int(resolution/1000),annot1,position1,position2)
output_filename = ""
# x1, idx = utility1.select_valuesPosition1(position, x, output_filename3, position1, position2, resolution)
border_type = 0
x1, idx = select_valuesPosition1_2(position, x, output_filename, position1, position2, position1a, position2a, resolution, border_type)
t_position = position[idx,:]
output_path = "."
# output_filename1 = "data1_mtx.test.%s.R5.test.txt"%(annot2)
output_filename1 = ""
output_filename2 = "%s/chr%s.%dKb.edgeList.txt"%(output_path,chrom,int(resolution/1000))
if(os.path.exists(output_filename1)==True):
output_filename1 = ""
if(os.path.exists(output_filename2)==True):
output_filename2 = ""
if type_id1==1:
# x1, mtx1, t_position, edge_list_1 = utility1.write_matrix_image_Ctrl_v2(x1,t_position,output_filename1,output_filename2,
# num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
type_id = 1
print "write_matrix_image_Ctrl_unsym1"
x1, mtx1, t_position, edge_list_1 = write_matrix_image_Ctrl_unsym1_position(x1,t_position,output_filename1,output_filename2,
num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
start_region1 = np.min(t_position)
start_region2 = start_region1
else:
type_id = 0
print "write_matrix_image_Ctrl_sym1"
x1, mtx1, t_position, edge_list_1 = write_matrix_image_Ctrl_sym1(x1,t_position,output_filename1,output_filename2,
num_neighbor,sigma,type_id,filter_mode,filter_param1,filter_param2)
temp1 = np.min(t_position,0)
start_region1, start_region2 = temp1[0], temp1[1]
n_samples = x1.shape[0]
# type_id1=1: diagonal type; type_id1=0: off-diagonal type
t_lenvec = [n_samples,mtx1.shape[0],mtx1.shape[1],start_region1,start_region2,region_id1,type_id1,chrom_id]
m_queue.put((region_id, x1, t_lenvec, edge_list_1, t_position))
end = time.time()
print "select regions use time %s %d: %s"%(chrom, region_id, (end-start))
return True
# symmetric matrix
def near_interpolation1(mtx, window_size):
window_size = 3
n1, n2 = mtx.shape[0], mtx.shape[1]
h = int((window_size-1)/2)
threshold = THRESH1
cnt1 = 0
cnt2 = 0
for i in range(2,n1-1):
for j in range(i,n2-1):
if mtx[i,j]<threshold:
cnt1 += 1
window = mtx[i-h:i+h+1,j-h:j+h+1]
window = window.ravel()
idx = range(0,window_size**2)
neighbor_idx = np.setdiff1d(idx,int((window_size**2-1)/2))
neighbor_feature = window[neighbor_idx]
m1 = np.median(neighbor_feature)
# m1 = np.median(window)
if m1>threshold:
cnt2 += 1
mtx[i,j] = m1
mtx[j,i] = m1
print "cnt1: %d cnt2: %d"%(cnt1,cnt2)
return mtx
# general matrix
def near_interpolation1a(mtx, window_size):
window_size = 3
n1, n2 = mtx.shape[0], mtx.shape[1]
h = int((window_size-1)/2)
threshold = THRESH1
cnt1 = 0
cnt2 = 0
for i in range(2,n1-1):
for j in range(2,n2-1):
if mtx[i,j]<threshold:
cnt1 += 1
window = mtx[i-h:i+h+1,j-h:j+h+1]
window = window.ravel()
idx = range(0,window_size**2)
neighbor_idx = np.setdiff1d(idx,int((window_size**2-1)/2))
neighbor_feature = window[neighbor_idx]
m1 = np.median(neighbor_feature)
# m1 = np.median(window)
if m1>threshold:
cnt2 += 1
mtx[i,j] = m1
# mtx[j,i] = m1
print "cnt1: %d cnt2: %d"%(cnt1,cnt2)
return mtx
def near_interpolation2(mtx, window_size):
window_size = 3
n1, n2 = mtx.shape[0], mtx.shape[1]
h = int((window_size-1)/2)
threshold = THRESH1
cnt1 = 0
cnt2 = 0
for i in range(2,n1-1):
for j in range(i,n2-1):
if mtx[i,j]<threshold:
cnt1 += 1
window = mtx[i-h:i+h+1,j-h:j+h+1]
window = window.ravel()
m1 = np.median(window)
if m1>threshold:
cnt2 += 1
mtx[i,j] = m1
mtx[j,i] = m1
print "cnt1: %d cnt2: %d"%(cnt1,cnt2)
return mtx
def cnt_estimate(state,n_components):
cnt_vec = np.zeros(n_components)
state_vec = np.unique(state)
num1 = len(state_vec)
for i in range(0,n_components):
if i<num1:
cnt_vec[i] = np.sum(state==state_vec[i])
# print cnt_vec
# print cnt_vec/sum(cnt_vec)
return cnt_vec, cnt_vec/sum(cnt_vec), state_vec
def symmetric_state(state):
dim1, dim2 = state.shape[0], state.shape[1]
for i in range(0,dim1):
for j in range(0,i):
state[i,j] = state[j,i]
return state
def symmetric_state1(state, window_size):
t_state1 = np.zeros((window_size,window_size))
id1 = symmetric_idx(window_size,window_size)
t_state1[id1] = state
state1 = symmetric_state(t_state1)
return state1
def symmetric_state1_vec(state_vecList, len_vec):
num1 = len_vec.shape[0]
state_vecList1 = []
for i in range(0,num1):
state1 = symmetric_state1(state_vecList[i])
state_vecList1.extend(state1)
return state_vecList1
def symmetric_idx(dim1,dim2):
a1 = np.ones(dim2).astype(int)
row_id = np.outer(range(0,dim1),a1)
a2 = np.ones(dim1).astype(int)
col_id = np.outer(a2,range(0,dim2))
row_id = row_id.ravel()
col_id = col_id.ravel()
idx = np.where(row_id<=col_id)[0]
return idx
def symmetric_idx1(dim1,dim2):
a1 = np.ones(dim2).astype(int)
row_id = np.outer(range(0,dim1),a1)
a2 = np.ones(dim1).astype(int)
col_id = np.outer(a2,range(0,dim2))
row_id = row_id.ravel()
col_id = col_id.ravel()
idx = np.where(row_id<=col_id)[0]
idx1 = np.where(row_id>=col_id)[0]
return idx,idx1
def meanvalue_state(x,state):
# data1 = pd.read_table(filename1,header=None)
vec1 = np.unique(state)
num1 = len(vec1) # the number of states
n_samples, n_features = x.shape[0], x.shape[1]
vec2 = [5,25,50,75,95]
num2 = len(vec2)
# stats = dict()
cnt_vec = np.zeros(num1)
m_vec1 = []
for i in range(0,num1):
print "state %d"%(vec1[i])
b = np.where(state==vec1[i])[0]
# m_vec1 = np.zeros((num2,n_features))
cnt = 0
for percentile in vec2:
# m_vec1[cnt] = np.percentile(b, percentile, axis=0)
print percentile
temp1 = np.percentile(x[b], percentile, axis=0)
print temp1
m_vec1.append(temp1)
cnt = cnt+1
# stats[i] = m_vec1
cnt_vec[i] = len(b)
stats = np.asarray(m_vec1)
return stats, cnt_vec
# compare two sets of labels
def compare_labeling(label1, label2):
nmi = normalized_mutual_info_score(label1, label2)
adj_mi = adjusted_mutual_info_score(label1, label2)
adj_ri = adjusted_rand_score(label1, label2)
label1_vec, label2_vec = np.unique(label1), np.unique(label2)
num1, num2 = label1_vec.shape[0], label2_vec.shape[0]
n1, n2 = label1.shape[0], label2.shape[0]
pair = np.c_[(label1,label2)]
tp = 0
for i in set(label1):
t1 = np.bincount(pair[pair[:,0]==i,1])
tp = tp + comb(t1,2).sum()
a = comb(np.bincount(label2),2).sum()
b = comb(np.bincount(label1),2).sum()
fp = a-tp # false positive
fn = b-tp # false negative
s1 = comb(n1,2)
tn = s1-tp-fp-fn
ri = (tp+tn)/s1
precision = tp/a
recall = tp/b
f1 = 2*precision*recall/(precision+recall)
return nmi, adj_mi, adj_ri, ri, precision, recall, f1
# find the indices of serial2 in serial1
# serial1 and serial2 need to be non-negative numbers
def mapping_Idx(serial1,serial2):
if len(np.unique(serial1))<len(serial1):
print("error! ref_serial not unique", len(np.unique(serial1)), len(serial1))
return
unique_flag = 1
t_serial2 = np.unique(serial2,return_inverse=True)
if len(t_serial2[0])<len(serial2):
# print("serial2 not unique!")
serial2_ori = serial2.copy()
serial2 = t_serial2[0]
unique_flag = 0
ref_serial = np.sort(serial1)
ref_sortedIdx = np.argsort(serial1)
ref_serial = np.int64(ref_serial)
map_serial = np.sort(serial2)
map_sortedIdx = np.argsort(serial2)
map_serial = np.int64(map_serial)
num1 = np.max((ref_serial[-1],map_serial[-1]))+1
vec1 = np.zeros((num1,2))
vec1[map_serial,0] = 1
b = np.where(vec1[ref_serial,0]>0)[0]
vec1[ref_serial,1] = 1
b1 = np.where(vec1[map_serial,1]>0)[0]
idx = ref_sortedIdx[b]
idx1 = -np.ones(len(map_serial))
# print(len(ref_serial),len(map_serial))
# print(len(vec1),ref_serial[-1],map_serial[-1])
# print(len(b),len(b1),len(idx))
idx1[map_sortedIdx[b1]] = idx
if unique_flag==0:
idx1 = idx1[t_serial2[1]]
return np.int64(idx1)
# normalize the feature to be in the same scale
# the feature values are non-negative
def normalize_feature(x1,x_min,x_max):
n1, n2 = x1.shape[0], x1.shape[1]
vec1 = []
for i in range(0,n2):
x = x1[:,i]
x[x<0] = 0
m1, m2 = np.min(x), np.max(x)
vec1.append([m1,m2])
vec1 = np.asarray(vec1)
min1, max1 = np.median(vec1[:,0]), np.median(vec1[:,1])
if x_min<0:
x_min = min1
# x_min = np.exp(min1)-1
if x_max<0:
x_max = max1
# x_max = np.exp(max1)-1
# print x_min, x_max
for i in range(0,n2):
x = x1[:,i]
x[x<0] = 0
m1, m2 = vec1[i,0], vec1[i,1]
x1[:,i] = x_min+(x-m1)*1.0*(x_max-x_min)/(m2-m1)
return x1, vec1, x_min, x_max
def normalize_feature2(position,x1,x_min,x_max,norm_typeId=0):
n1, n2 = x1.shape[0], x1.shape[1]
vec1 = []
for i in range(0,n2):
x = x1[:,i]
x[x<0] = 0
m1, m2 = np.min(x), np.max(x)
vec1.append([m1,m2])
vec1 = np.asarray(vec1)
min1, max1 = np.median(vec1[:,0]), np.median(vec1[:,1])
if x_min<0:
x_min = min1
# x_min = np.exp(min1)-1
if x_max<0:
x_max = max1
# x_max = np.exp(max1)-1
# print x_min, x_max
threshold1 = 0.997
threshold2 = 0.9545
b1 = np.where(position[:,0]==position[:,1])[0]
for i in range(0,n2):
x = x1[:,i]
x[x<0] = 0
# m1, m2 = vec1[i,0], vec1[i,1]
b2 = np.where(x[b1]>0)[0]
diagonal_x = x[b1[b2]]
print "diagonal_x", len(b1), len(b2)
if norm_typeId==0:
limit1 = np.quantile(diagonal_x,threshold1)
elif norm_typeId==1:
limit1 = np.quantile(diagonal_x,threshold2)
elif norm_typeId==2:
Q1,Q3 = np.quantile(diagonal_x,0.25), np.quantile(diagonal_x,0.75)
limit1 = Q3+(Q3-Q1)*1.5
else:
limit1 = np.max(x)
b_1 = np.where(x>limit1)[0]
ratio = len(b_1)*1.0/len(x)
# print "normalize %d %d %.2f %d %.2f"%(norm_typeId,i,limit1,len(b_1),ratio)
if len(b_1)>0:
x[b_1] = limit1
m1, m2 = vec1[i,0], limit1
x1[:,i] = x_min+(x-m1)*1.0*(x_max-x_min)/(m2-m1)
return x1, vec1, x_min, x_max
# normalize the feature to be in the same scale
def normalize_feature1(x1,x_min,x_max):
n1, n2 = x1.shape[0], x1.shape[1]
vec1 = []
for i in range(0,n2):
x = x1[:,i]
m1, m2 = np.min(x), np.max(x)
vec1.append([m1,m2])
x1[:,i] = x_min+(x-m1)*1.0*(x_max-x_min)/(m2-m1)
vec1 = np.asarray(vec1)
return x1, vec1
# input:
# filename1: estimated states
# filename2: color file
# sel_idx: selected column names
# output_filename: output file
def write_toRGB(filename1, filename2, output_filename):
data2 = pd.read_table(filename1,header=None)
colnames = list(data2)
pos1, pos2 = np.asarray(data2[colnames[0]]), np.asarray(data2[colnames[1]])
state1 = np.asarray(data2[colnames[-1]])
print state1[0:10]
start_region = np.min((np.min(pos1),np.min(pos2)))
stop_region = np.max((np.max(pos1),np.max(pos2)))
window_size = stop_region-start_region+1
print start_region, stop_region, window_size
n_components = max(state1)+1
state_id = range(1,n_components+1) # original states
n_sample = len(state1)
print n_sample
data3 = pd.read_table(filename2,header=None)
colnames1 = list(data3)
t_color = data3[colnames1[-1]]
color_vec = list(set(t_color))