-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsmTsetOpt.py
1332 lines (1250 loc) · 49.1 KB
/
msmTsetOpt.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
#!/usr/bin/env python
"""
Collection of target set optimization functions and utilities for Hi-C analysis
Part of ChromaWalker package
"""
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import random
import copy
from time import time
import hicutils as hcu
import plotutils as plu
import hicFileIO as hfio
import dataFileReader as dfr
import msmTPT as mt
from operator import itemgetter
# Target set optimization
def _trynewtarget_construct(cmat, targetset, rhofunc=mt._rhoindex):
nbins = len(cmat)
tset = list(targetset)
scores = []
for trial in range(nbins):
if trial in targetset:
scores.append(np.nan)
continue
trialset = tset + [trial]
scores.append(rhofunc(cmat, np.array(trialset)))
scores = np.array(scores)
minarg = np.isfinite(scores).nonzero()[0][
np.argmin(scores[np.isfinite(scores)])]
return minarg, scores[minarg]
def _choosesteppers(initial, pstep, minstep=1):
"""
Utility for MC move chooser: Select points to step.
Note: Requires initial to be a 1D list / array.
"""
npts = len(initial)
pstep2 = max(float(minstep) / npts, pstep)
while True:
trialstep = np.random.uniform(size=npts) < pstep2
nstep = np.sum(trialstep)
if nstep > 0:
break
stepfrom = list(np.array(initial)[trialstep])
stayat = list(np.array(initial)[np.array(1 - trialstep, dtype='bool')])
return stayat, stepfrom
def _trialstep_vectormap(stayat, stepfrom, allchoices, vectormap):
"""
Utility for MC move chooser: Step from selected points,
adding random points if overlap occurs.
"""
npts = len(stayat) + len(stepfrom)
stepto = np.array(vectormap)[np.array(stepfrom)]
trialset = list(set().union(stayat, stepto))
deficit = npts - len(trialset)
if deficit > 0:
choices = list(set(allchoices) - set(trialset))
random.shuffle(choices)
trialset = trialset + choices[:deficit]
return trialset
def _trialstep_random(stayat, stepfrom, allchoices):
"""
Utility for MC move chooser: Step from selected points,
adding random points if overlap occurs.
"""
npts = len(stayat) + len(stepfrom)
choices = list(set(allchoices) - set(stayat) - set(stepfrom))
random.shuffle(choices)
stepto = choices[:len(stepfrom)]
trialset = list(set().union(stayat, stepto))
deficit = npts - len(trialset)
if deficit > 0:
choices = list(set(allchoices) - set(trialset))
random.shuffle(choices)
trialset = trialset + choices[:deficit]
return trialset
def _stepping_gammamax(targetset, cmat, bestrho, besttset, gammamaxmap,
allchoices, nstep, pstep, kT, minstep=1, rhofunc=mt._rhoindex):
#print targetset
for j in range(nstep):
# Choose which ones to step: Require at least 1 step
stayat, stepfrom = _choosesteppers(targetset,
pstep, minstep=minstep)
# Trial step
if not set(stepfrom).issubset(set(allchoices)):
print len(cmat), stepfrom, stayat
trialset = _trialstep_vectormap(stayat, stepfrom,
allchoices, gammamaxmap)
# Metropolis criterion for deciding whether or not to move
thisrho = rhofunc(cmat, targetset)
trialrho = rhofunc(cmat, trialset)
if _Metropolis_decision(thisrho, trialrho, kT):
targetset = copy.deepcopy(trialset)
if trialrho < bestrho:
#print 'Gamma move', j, 'good'
bestrho = trialrho
besttset = copy.deepcopy(trialset)
return targetset, bestrho, besttset
def _stepping_random(targetset, cmat, bestrho, besttset,
allchoices, nstep, pstep, kT, minstep=1, rhofunc=mt._rhoindex):
for j in range(nstep):
# Choose which ones to step: Require at least 1 step
stayat, stepfrom = _choosesteppers(targetset,
pstep, minstep=1)
# Trial step
trialset = _trialstep_random(stayat, stepfrom, allchoices)
thisrho = rhofunc(cmat, targetset)
trialrho = rhofunc(cmat, trialset)
if _Metropolis_decision(thisrho, trialrho, kT):
targetset = copy.deepcopy(trialset)
if trialrho < bestrho:
#print 'Random move', j, 'good'
bestrho = trialrho
besttset = copy.deepcopy(trialset)
return targetset, bestrho, besttset
def _Metropolis_decision(initialscore, finalscore, kT):
"""
Utility for MC decision based on Metropolis criterion.
Accept if finalscore < initialscore, or with probability
exp((initialscore - finalscore) / kT)...
"""
return (finalscore < initialscore or
np.random.uniform() < np.exp((initialscore - finalscore) / kT))
def _ConstructTset_optimize2(cmat, rhofunc=mt._rhoindex):
"""
Optimize 2-target set by exhaustive combinatorial search.
"""
nbins = len(cmat)
st = time()
targetset = [0, 1]
bestrho = rhofunc(cmat, targetset)
for i in range(nbins):
for j in range(i + 1, nbins):
trialset = [i, j]
thisrho = rhofunc(cmat, trialset)
if thisrho < bestrho:
bestrho = thisrho
targetset = trialset
en = time()
print 2, ('(%.2e secs):' % (en - st)), bestrho
return bestrho, targetset
def _ConstructTset_dictpivec2(pars, rhomode='frac'):
"""
Select 2-target set by taking from data dict, or initializing from
stationary probabilities pi.
"""
res = pars['res']
resname = str(res / 1000) + 'kb'
beta = pars['beta']
dataset = dfr._get_tsetdataset2(pars)
chrfullname = pars['cname']
region = pars['region']
tsetdatadir = pars['tsetdatadir']
tsetdataprefix = pars['tsetdataprefix']
rhomodesfx = mt._get_rhomodesfx(rhomode)
rhodict0, tsetdict0 = dfr._get_rhotsetdicts_20160801(tsetdatadir,
tsetdataprefix, chrfullname, region, res, dataset,
rhomodesfx=rhomodesfx)
key = (beta, 2)
if key in rhodict0:
if key in tsetdict0:
bestrho = rhodict0[key]
targetset = tsetdict0[key]
else:
print 'Rhodict error: Erase entry', key
del(rhodict0[key])
dirname = os.path.join(tsetdatadir, tsetdataprefix,
chrfullname, region, resname)
rfname = os.path.join(dirname, dataset + '-rhodict' +
rhomodesfx + '.p')
hfio._pickle_securedump(rfname, rhodict0, freed=True)
if key in rhodict0:
print 'Load 2-target state from data'
bestrho = rhodict0[key]
targetset = tsetdict0[key]
else:
print 'Seed 2-target state from pivec'
fmat, _, cmat, _ = dfr._get_arrays(dfr._get_runbinarydir(pars),
norm=pars['norm'])
pivec = np.sum(fmat, axis=1)
targetset = [np.argmax(pivec)]
newtarget, bestrho = _trynewtarget_construct(cmat, targetset)
targetset = targetset + [newtarget]
del rhodict0, tsetdict0
return bestrho, targetset
def _ConstructTset_dictpivec2_indict(beta, arrays, indicts):
"""
Select 2-target set by taking from data dict, or initializing from
stationary probabilities pi.
"""
fmat, cmat = arrays
rhodict0, tsetdict0 = indicts
key = (beta, 2)
if key in rhodict0:
if key in tsetdict0:
bestrho = rhodict0[key]
targetset = tsetdict0[key]
else:
print 'Rhodict error: Erase entry', key
del(rhodict0[key])
if key in rhodict0:
print 'Load 2-target state from data'
bestrho = rhodict0[key]
targetset = tsetdict0[key]
else:
print 'Seed 2-target state from pivec'
pivec = np.sum(fmat, axis=1)
targetset = [np.argmax(pivec)]
newtarget, bestrho = _trynewtarget_construct(cmat, targetset)
targetset = targetset + [newtarget]
del rhodict0, tsetdict0
return bestrho, targetset
def _ConstructTset_MCn(steppars, newrho, targetset, allchoices, cmat,
gammamaxmap, rhofunc=mt._rhoindex):
"""
MC steps, starting from preliminary target set.
"""
#print targetset
nstep_gammamax, pstep_gammamax, nstep_random, pstep_random, kT = steppars
### Start MC with candidate:
bestrho = newrho
besttset = copy.deepcopy(targetset)
#### Follow cmat-maximizing trajectory
targetset, bestrho, besttset = _stepping_gammamax(targetset, cmat,
bestrho, besttset, gammamaxmap, allchoices,
nstep_gammamax, pstep_gammamax, kT, minstep=1, rhofunc=rhofunc)
#### Random trials
targetset, bestrho, besttset = _stepping_random(targetset,
cmat, bestrho, besttset, allchoices,
nstep_random, pstep_random, kT, minstep=1, rhofunc=rhofunc)
return bestrho, besttset
def run_ConstructMC_fullarray(pars, steppars, meansize=1.333, initmode=False,
exhaustive=False, rhomode='frac'):
"""
Run Construct-MC optimization for rho on a range of ntarget: [2, ntargetmax]
Set ntargetmax / mappedlength ~ 0.75 Mb^-1
Method explained in Chromatin manuscript: basically using "guided" Monte
Carlo and "random" Monte Carlo in succession, with
parameters defined by steppars.
"""
res = pars['res']
beta = pars['beta']
norm = pars['norm']
nstep_gammamax, pstep_gammamax, nstep_random, pstep_random, kT = steppars
rhodata = {}
tsetdata = {}
# Rho mode
rhofunc = mt._get_rhofunc(rhomode)
# Read cmat, fmat, mmat, mapping
fmat, mmat, cmat, (mapping, _) = dfr._get_arrays(
dfr._get_runbinarydir(pars), norm=norm)
nbins = len(cmat)
allchoices = range(nbins)
# Find gamma-maximizing mapping
gammamaxmap = np.array([np.argmax(v) for v in cmat])
# Find ntargetmax
if initmode:
ntargetmax = 3
else:
mappedlen = (nbins * res) / 1.0e6
ntargetmax = int(np.ceil(1.0 / meansize * mappedlen))
if len(cmat) <= ntargetmax:
print 'Skip...'
return {}, {}
print 'ntargetmax =', ntargetmax
print
#############################
# Find seed target pair: Optimal from current data, or pivec-seeded
if initmode and exhaustive:
bestrho, targetset = _ConstructTset_optimize2(cmat, rhofunc=rhofunc)
if len(targetset) != 2:
print 'Error! ntarget mismatch 0.0!'
sys.exit()
key = (beta, 2)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
else:
st = time()
newrho, targetset = _ConstructTset_dictpivec2(pars, rhomode=rhomode)
if len(targetset) != 2:
print 'Error! ntarget mismatch 0.2!'
sys.exit()
bestrho, besttset = _ConstructTset_MCn(steppars, newrho,
targetset, allchoices, cmat, gammamaxmap,
rhofunc=rhofunc)
targetset = list(besttset)
if len(targetset) != 2:
print 'Error! ntarget mismatch 0.5!'
sys.exit()
key = (beta, 2)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
en = time()
print 2, ('(%.2e secs):' % (en - st)), bestrho
#############################
## For each new target:
#print type(targetset), targetset
for i in range(2, ntargetmax):
ntarget = i + 1
st = time()
### Optimize new target
newtarget, newrho = _trynewtarget_construct(cmat, targetset,
rhofunc=rhofunc)
targetset.append(newtarget)
if len(targetset) != ntarget:
print 'Error! ntarget mismatch 1!'
sys.exit()
bestrho, besttset = _ConstructTset_MCn(steppars, newrho,
targetset, allchoices, cmat, gammamaxmap,
rhofunc=rhofunc)
### Record rhodata, targetsetdata
targetset = besttset
if len(targetset) != ntarget:
print 'Error! ntarget mismatch 2!'
sys.exit()
key = (beta, ntarget)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
en = time()
print i + 1, ('(%.2e secs):' % (en - st)), bestrho
#print targetset
return rhodata, tsetdata
def run_PertSnap_fullarray(pars, pertpars, meansize=1.333, initmode=False,
exhaustive=False, rhomode='frac'):
"""
Run PertSnap optimization for rho on a range of ntarget: [2, ntargetmax]
Set ntargetmax / mappedlength ~ 0.75 Mb^-1
Fine-tuning step in addition to what's explained in Chromatin manuscript.
Basically, randomly select a single target to perturb left/right
along the chromosome to see if rho improves.
For each selected target, we try positions within +-nstep bins
of the original. Then perform this random selection ntrials times.
"""
res = pars['res']
beta = pars['beta']
norm = pars['norm']
tsetdatadir = pars['tsetdatadir']
tsetdataprefix = pars['tsetdataprefix']
chrfullname = pars['cname']
region = pars.get('region', 'full')
rhomodesfx = mt._get_rhomodesfx(rhomode)
ntrials, nstep = pertpars
newrhodict = {}
newtsetdict = {}
rhodict, tsetdict = hcu._get_rhotsetdicts_20160801(tsetdatadir,
tsetdataprefix, chrfullname, region, res,
hcu._get_tsetdataset2(pars), rhomodesfx=rhomodesfx)
# Rho mode
rhofunc = mt._get_rhofunc(rhomode)
# Read cmat, fmat, mmat, mapping
fmat, mmat, cmat, (mapping, _) = dfr._get_arrays(
dfr._get_runbinarydir(pars), norm=norm)
nbins = len(cmat)
# Find ntargetmax
if initmode:
ntargetmax = 3
else:
mappedlen = (nbins * res) / 1.0e6
ntargetmax = int(np.ceil(1.0 / meansize * mappedlen))
if len(cmat) <= ntargetmax:
print 'Skip...'
return {}, {}
print 'ntargetmax =', ntargetmax
print
for ntarget in range(2, ntargetmax):
print 'ntarget', ntarget, '...',
st = time()
key = (beta, ntarget)
if key not in rhodict:
print 'break!'
break
if key in rhodict and key not in tsetdict:
print 'break: bad tset!'
break
bestrho = rhodict[key]
initrho = bestrho
tset = tsetdict[key]
moved = False
for i in range(ntrials):
testind = np.random.randint(0, ntarget)
testtset0 = np.array(tset).copy()
for step in range(1, nstep + 1):
testtset = testtset0.copy()
testtset[testind] = max(0, testtset[testind] - step)
if len(np.unique(testtset)) < ntarget:
continue
testrho = rhofunc(cmat, testtset)
if testrho < bestrho:
rho12 = testrho, initrho
moved = True
tset = testtset.copy()
bestrho = testrho
for i in range(ntrials):
testind = np.random.randint(0, ntarget)
testtset0 = np.array(tset).copy()
for step in range(1, nstep + 1):
testtset = testtset0.copy()
testtset[testind] = min(ntarget - 1,
testtset[testind] + step)
if len(np.unique(testtset)) < ntarget:
continue
testrho = rhofunc(cmat, testtset)
if testrho < bestrho:
rho12 = testrho, initrho
moved = True
tset = testtset.copy()
bestrho = testrho
en = time()
print (': %.3e secs' % (en - st)),
if moved:
print 'moved! %.3e' % bestrho
newtsetdict[key] = tset
newrhodict[key] = bestrho
else:
print
return newrhodict, newtsetdict
# Merge old and new rho/tset dicts
def _combine_rhotsetdicts(r1, t1, r2, t2):
rhodict = {}
tsetdict = {}
for k in r1:
if k in r2 and r2[k] < r1[k]:
rhodict[k] = r2[k]
tsetdict[k] = t2[k]
else:
rhodict[k] = r1[k]
tsetdict[k] = t1[k]
for k in r2:
if k not in r1:
rhodict[k] = r2[k]
tsetdict[k] = t2[k]
return rhodict, tsetdict
# Automatically finding optimal levels
def _find_goodLevels(rholist, ntargetlist, mappedchrlen, rhomax=0.8,
skipfirst=None):
"""
Define optimal levels of structural hierarchy (minima in rho) below rhomax.
Returns list of ntarget values.
If skipfirst is True, skip first minimum after ntarget = 2.
If None, set skipfirst to True if mappedchrlen > 200Mbp.
"""
if skipfirst is None:
skipfirst = (mappedchrlen > 2e8)
rhoarr = np.array(rholist)
ntarr = np.array(ntargetlist)
# Find minima: Ignore first and last ntarget values
nextgreater = rhoarr[1:] > rhoarr[:-1]
prevgreater = rhoarr[:-1] > rhoarr[1:]
minmask = np.array(nextgreater[1:] * prevgreater[:-1], dtype=bool)
minmask = np.array(minmask * (rhoarr[1:-1] < rhomax), dtype=bool)
ntmin = ntarr[1:-1][minmask]
if skipfirst:
ntmin = ntmin[1:]
return np.array(ntmin)
def _find_optimalLevels(rholist, ntargetlist, mappedchrlen, rhomax=0.8,
skipfirst=None):
"""
Define optimal levels of structural hierarchy (minima in rho) below rhomax.
Returns list of ntarget values.
If skipfirst is True, skip first minimum after ntarget = 2.
If None, set skipfirst to True if mappedchrlen > 200Mbp.
"""
#if skipfirst is None:
#skipfirst = (mappedchrlen > 2e8)
#rhoarr = np.array(rholist)
#ntarr = np.array(ntargetlist)
## Find minima: Ignore first and last ntarget values
#nextgreater = rhoarr[1:] > rhoarr[:-1]
#prevgreater = rhoarr[:-1] > rhoarr[1:]
#minmask = np.array(nextgreater[1:] * prevgreater[:-1], dtype=bool)
#minmask = np.array(minmask * (rhoarr[1:-1] < rhomax), dtype=bool)
#ntmin = ntarr[1:-1][minmask]
#if skipfirst:
#ntmin = ntmin[1:]
ntmin = _find_goodLevels(rholist, ntargetlist, mappedchrlen, rhomax=rhomax,
skipfirst=skipfirst)
# Set ntmin[i+1] > 2*ntmin[i]
ntmin = list(ntmin)
print ntmin
i = 0
while True:
thismin = ntmin[i]
while True:
if len(ntmin) == i + 1:
break
nextmin = ntmin[i + 1]
if nextmin < 2 * thismin:
ntmin.pop(ntmin.index(nextmin))
else:
i += 1
break
if i + 1 >= len(ntmin):
break
return np.array(ntmin)
################################################
# To deprecate...
def run_ConstructMC_arbarray(fmat, cmat, datalabel, tsetdatadir,
tsetdataprefix, steppars, ntargetmax=None, optimize2=False):
"""
Run Construct-MC optimization for rho on a range of ntarget: [2, ntargetmax]
"""
# Unpack parameters
nstep_gammamax, pstep_gammamax, nstep_random, pstep_random, kT = steppars
nbins = len(fmat)
# Set ntargetmax, if None, to len(fmat) - 1
if ntargetmax is None:
ntargetmax = nbins - 1
print 'ntargetmax =', ntargetmax
rhodata = {}
tsetdata = {}
# Read cmat, fmat, mmat, mapping
nbins = len(cmat)
allchoices = range(nbins)
plttitle = 'Arbitrary array'
# Find gamma-maximizing mapping
gammamaxmap = np.array([np.argmax(v) for v in cmat])
print
# Find seed target pair: Optimal from current data, or pivec-seeded
if optimize2:
st = time()
targetset = [0, 1]
bestrho = mt._rhoindex(cmat, targetset)
for i in range(nbins):
for j in range(i + 1, nbins):
trialset = [i, j]
thisrho = mt._rhoindex(cmat, trialset)
if thisrho < bestrho:
bestrho = thisrho
targetset = trialset
key = (datalabel, 2)
rhodata[key] = bestrho
tsetdata[key] = targetset
en = time()
print 2, ('(%.2e secs):' % (en - st)), bestrho
else:
st = time()
rhodict0, tsetdict0 = hcu._get_rhotsetdicts(tsetdatadir,
tsetdataprefix)
key = (datalabel, 2)
if key in rhodict0:
print 'Load 2-target state from data'
newrho = rhodict0[key]
targetset = tsetdict0[key]
else:
print 'Seed 2-target state from pivec'
pivec = np.sum(fmat, axis=1)
targetset = [np.argmax(pivec)]
newtarget, newrho = _trynewtarget_construct(cmat, targetset)
targetset = targetset + [newtarget]
del rhodict0, tsetdict0
### Start MC with candidate:
bestrho = newrho
besttset = copy.deepcopy(targetset)
#### Follow cmat-maximizing trajectory
ntarget = len(besttset)
targetset, bestrho, besttset = _stepping_gammamax(targetset, cmat,
bestrho, besttset, gammamaxmap, allchoices,
nstep_gammamax, pstep_gammamax, kT, minstep=1)
#### Random trials
targetset, bestrho, besttset = _stepping_random(targetset,
cmat, bestrho, besttset, allchoices,
nstep_random, pstep_random, kT, minstep=1)
### Record rhodata, targetsetdata
targetset = besttset
rhodata[key] = bestrho
tsetdata[key] = targetset
en = time()
print 2, ('(%.2e secs):' % (en - st)), bestrho
#print targetset
## For each new target:
f, x = plt.subplots(1, 1)
trackrho = [bestrho]
for i in range(2, ntargetmax):
st = time()
### Optimize new target
newtarget, newrho = _trynewtarget_construct(cmat, targetset)
targetset = targetset + [newtarget]
### Start MC with candidate:
bestrho = newrho
besttset = copy.deepcopy(targetset)
#### Follow cmat-maximizing trajectory
ntarget = len(besttset)
targetset, bestrho, besttset = _stepping_gammamax(targetset, cmat,
bestrho, besttset, gammamaxmap, allchoices,
nstep_gammamax, pstep_gammamax, kT, minstep=1)
#### Random trials
targetset, bestrho, besttset = _stepping_random(targetset,
cmat, bestrho, besttset, allchoices,
nstep_random, pstep_random, kT, minstep=1)
### Record rhodata, targetsetdata
targetset = besttset
key = (datalabel, ntarget)
rhodata[key] = bestrho
tsetdata[key] = targetset
trackrho.append(bestrho)
x.cla()
x.plot(np.arange(2, len(targetset) + 1), trackrho)
x.set_title(plttitle)
f.canvas.draw()
en = time()
print i + 1, ('(%.2e secs):' % (en - st)), bestrho
#print targetset
plt.close(f)
return rhodata, tsetdata
def run_ConstructMC_fullarray_trial(arrays, indicts, pars, steppars,
meansize=1.333, initmode=False, exhaustive=False, rhomode='frac'):
"""
Run Construct-MC optimization for rho on a range of ntarget: [2, ntargetmax]
Set ntargetmax / mappedlength ~ 0.75 Mb^-1
"""
fmat, cmat = arrays
res = pars['res']
beta = pars['beta']
nstep_gammamax, pstep_gammamax, nstep_random, pstep_random, kT = steppars
inrdict, intdict = indicts
rhodata = {}
tsetdata = {}
# Rho mode
rhofunc = mt._get_rhofunc(rhomode)
# Read cmat, fmat, mmat, mapping
nbins = len(cmat)
allchoices = range(nbins)
# Find gamma-maximizing mapping
gammamaxmap = np.array([np.argmax(v) for v in cmat])
# Find ntargetmax
if initmode:
ntargetmax = 2
else:
mappedlen = (nbins * res) / 1.0e6
ntargetmax = int(np.ceil(1.0 / meansize * mappedlen))
print 'ntargetmax =', ntargetmax
print
# Find seed target pair: Optimal from current data, or pivec-seeded
if initmode and exhaustive:
bestrho, targetset = _ConstructTset_optimize2(cmat, rhofunc=rhofunc)
if len(targetset) != 2:
sys.exit()
key = (beta, 2)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
else:
st = time()
newrho, targetset = _ConstructTset_dictpivec2_indict(
beta, arrays, indicts)
if len(targetset) != 2:
sys.exit()
bestrho, besttset = _ConstructTset_MCn(steppars, newrho,
targetset, allchoices, cmat, gammamaxmap,
rhofunc=rhofunc)
targetset = list(besttset)
if len(targetset) != 2:
sys.exit()
key = (beta, 2)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
en = time()
print 2, ('(%.2e secs):' % (en - st)), bestrho
## For each new target:
#print type(targetset), targetset
for i in range(2, ntargetmax):
ntarget = i + 1
st = time()
### Optimize new target
#print targetset, 'a'
newtarget, newrho = _trynewtarget_construct(cmat, targetset,
rhofunc=rhofunc)
#print targetset, 'b'
targetset.append(newtarget)
if len(targetset) != ntarget:
sys.exit()
#print targetset, 'c'
bestrho, besttset = _ConstructTset_MCn(steppars, newrho,
targetset, allchoices, cmat, gammamaxmap,
rhofunc=rhofunc)
### Record rhodata, targetsetdata
targetset = besttset
if len(targetset) != ntarget:
sys.exit()
key = (beta, ntarget)
rhodata[key] = bestrho
tsetdata[key] = copy.deepcopy(targetset)
en = time()
print i + 1, ('(%.2e secs):' % (en - st)), bestrho
#print targetset
return rhodata, tsetdata
# Consensus target set determination using equal size k-means clustering
def _samesizecluster(D):
""" in: point-to-cluster-centre distances D, Npt x C
e.g. from scipy.spatial.distance.cdist
out: xtoc, X -> C, equal-size clusters
method: sort all D, greedy
"""
# could take only the nearest few x-to-C distances
# add constraints to real assignment algorithm ?
Npt, C = D.shape
clustersize = (Npt + C - 1) / C
xcd = list(np.ndenumerate(D)) # ((0,0), d00), ((0,1), d01) ...
xcd.sort(key=itemgetter(1))
xtoc = np.ones(Npt, int) * -1
nincluster = np.zeros(C, int)
nall = 0
for (x, c), d in xcd:
if xtoc[x] < 0 and nincluster[c] < clustersize:
xtoc[x] = c
nincluster[c] += 1
nall += 1
if nall >= Npt:
break
return xtoc
def sameSizeCluster_1d(points, nclusters, errorcutoff=1.0, maxiter=1000):
"""
Equal-size k-means clustering of real numbers.
"""
newctrs = np.random.choice(points, size=nclusters, replace=False)
error = 100.0
niter = 0
while error > errorcutoff and niter < maxiter:
niter += 1
ctrs = newctrs.copy()
dists = np.array([[np.abs(c - p) for c in ctrs] for p in points])
clustering = _samesizecluster(dists)
newctrs = np.array([np.average(np.array(points)[clustering == i])
for i in range(nclusters)])
error = np.sum(np.abs(ctrs - newctrs))
return np.array([np.array(points)[clustering == i]
for i in range(nclusters)])
def ConsensusTset_kmeans(mappedtargets, ntargets, errorcutoff=1.0):
"""
Construct consensus target set by k-means clustering of mapped targets.
Return list of candidate targets
"""
clustering = sameSizeCluster_1d(mappedtargets, ntargets,
errorcutoff=errorcutoff)
candidates = [-1 for i in range(ntargets)]
for i, cluster in enumerate(clustering):
clusteruniq = list(set(cluster))
clusteruniq.sort()
clusterpoll = np.array([list(cluster).count(mt) for mt in clusteruniq])
# Select all target candidates with highest in-group poll
pollmax = np.max(clusterpoll)
candidates[i] = tuple(np.array(clusteruniq)[clusterpoll == pollmax])
sortinds = np.argsort(map(np.average, candidates))
candidates = map(tuple, np.array(candidates)[sortinds])
clustering = np.array(clustering)[sortinds]
return candidates, clustering
def ConsensusTset_kmeans_sort(mappedtargets, ntargets, errorcutoff=1.0):
"""
Sort k-means clustered targets by occurrence ranking. most frequent first.
"""
mappedtargetset = np.sort(list(set(mappedtargets)))
mappedtargetpoll = [mappedtargets.count(t) for t in mappedtargetset]
candidates, clustering = ConsensusTset_kmeans(mappedtargets, ntargets,
errorcutoff=errorcutoff)
rankedclustering = []
for thiscluster in clustering:
thisclusteruniq = np.unique(thiscluster)
thisranks = [mappedtargetpoll[list(mappedtargetset).index(t)]
for t in thisclusteruniq]
rankedclustering.append(thisclusteruniq[np.argsort(thisranks)[::-1]].copy())
return candidates, rankedclustering
#################################################################
# TargetsetOptimizer class:
# - Run ConstructMC / PertSnap routines
# - TODO: Comparison across beta values, consensus polling
class TargetOptimizer:
"""
Container to initialize / hold parameters pertaining to targetset
optimization in HiC analysis runs and simplify function calls.
TODO: Add consensus polling for defining reference tsets.
"""
def __init__(self, pars, DFR=None, conMCpars=None, pertpars=None):
"""
initialize TargetOptimizer instance.
"""
if DFR is None:
self.DFR= dfr.DataFileReader(pars)
else:
self.DFR = DFR
# Basic file directory / name info
self.rawdatadir = pars['rawdatadir']
self.genomedatadir = pars['genomedatadir']
self.genomeref = pars['genomeref']
self.rundir = pars['rundir']
self.dataformat = 'Liebermann-Aiden'
self.accession = pars['accession']
self.runlabel = pars['runlabel']
self.tsetdatadir = pars['tsetdatadir']
self.tsetdataprefix = pars['tsetdataprefix']
#############################
# Info about dataset / run:
## Which genomic regions?
if 'cnamelist' in pars:
self.cnamelist = pars['cnamelist']
self.cname = self.cnamelist[0]
else:
self.cnamelist = ['chr' + str(i) for i in range(1, 23)] + ['chrX']
self.cname = 'chr1'
self.region = pars.get('region', 'full')
## Data resolution?
self.baseres = pars['baseres']
self.res = pars.get('res', self.baseres)
## Include self-interactions (loops)? How many times?
self.nloop = pars.get('nloop', 0)
## Noise-filtering by thermal annealing
if 'betalist' in pars:
self.betalist = pars['betalist']
else:
self.betalist = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
self.beta = pars.get('beta', self.betalist[0])
## Data normalization by row-normalizing vectors or gaussian filter
self.norm = pars.get('norm', 'raw')
## Noise filtering by filtering out low-count pixels
### To deprecate
self.basethreshold = pars.get('threshold', 0.0)
## Noise filtering by filtering out low-count columns
### To deprecate
self.minrowsum = pars.get('minrowsum', 0.0)
## TPT optimizer function: Whoch rho to use?
### To deprecate
self.rhomode = pars.get('rhomode', 'frac')
## TPT optimization depth: Smallest average partition size in Mbp?
self.meansize = pars.get('meansize', 0.8)
## TPT partition definition: Partitions smaller than this size should
## be merged with neighbors (in Mbp)
self.minpartsize = pars.get('minpartsize', 0.5)
## TPT partition definition: Criterion for metastability index rho
self.rhomax = pars.get('rhomax', 0.8)
## TPT partition definition: Skip first minimum in rho?
self.skipfirst = pars.get('skipfirst', None)
## TPT Laplacian definition: Thermal annealing beta of interaction
## matrix used for Laplacian computation
self.fmatbeta = pars.get('fmatbeta', 1.0)
## TPT Laplacian definition: For binning mode, normalize matrix by
## partition sizes?
self.matnorm = pars.get('matnorm', 'sum')
#############################
# Create base pardicts
self.basepars = {'rawdatadir': self.rawdatadir,
'rawdatadir': self.rawdatadir,
'genomedatadir': self.genomedatadir,
'genomeref': self.genomeref,
'rundir': self.rundir,
'dataformat': self.dataformat,
'accession': self.accession,
'runlabel': self.runlabel,
'tsetdatadir': self.tsetdatadir,
'tsetdataprefix': self.tsetdataprefix,
'cname': self.cname,
'region': self.region,
'baseres': self.baseres,
'res': self.res,
'nloop': self.nloop,
'beta': self.beta,
'tsetbeta': self.beta,
'norm': self.norm,
'threshold': self.basethreshold,
'minrowsum': self.minrowsum,
'rhomode': self.rhomode,
'meansize': self.meansize,
'minpartsize': self.minpartsize,
'rhomax': self.rhomax,
'skipfirst': self.skipfirst,
'fmatbeta': self.fmatbeta
}
##############################
# ConMC / pSnap parameters
if conMCpars is None:
self.steppars = 100, 0.5, 500, 0.1, 1.0
else:
self.steppars = (conMCpars.get('nstep_gammamax', 100),
conMCpars.get('pstep_gammamax', 0.5),
conMCpars.get('nstep_random', 200),
conMCpars.get('pstep_random', 0.1),
conMCpars.get('kT', 1.0))
if pertpars is None:
self.pertpars = 200, 4
else:
self.pertpars = (pertpars.get('ntrials', 200),
pertpars.get('nstep', 4))
def seed(self, cname, beta, exhaustive=None):
"""
Find seed 2-target set for given case.
Parameter 'exhaustive' can be True/False/None.
If None, will perform exhaustive target-pair search only if matrix
size is no more than N = 1500.
"""
if exhaustive is None:
size = len(self.DFR.get_mappingdata(cname, beta)[0])
exhaustive = (size <= 1500)
thispar = copy.deepcopy(self.basepars)
thispar['cname'] = cname
thispar['beta'] = beta
rd, td = run_ConstructMC_fullarray(thispar, self.steppars,
meansize=self.meansize, initmode=True,
exhaustive=exhaustive, rhomode=self.rhomode)
self.DFR.update_datadicts(cname, rd, td)
def conMC(self, cname, beta):
"""
Perform targetset search / optimization using ConstructMC routine.
"""
thispar = copy.deepcopy(self.basepars)
thispar['cname'] = cname
thispar['beta'] = beta
rd, td = run_ConstructMC_fullarray(thispar, self.steppars,
meansize=self.meansize, rhomode=self.rhomode)
return self.DFR.update_datadicts(cname, rd, td)
def pSnap(self, cname, beta):
"""
Perform targetset search / optimization using PertSnap routine.
"""
thispar = copy.deepcopy(self.basepars)
thispar['cname'] = cname
thispar['beta'] = beta
rd, td = run_PertSnap_fullarray(thispar, self.pertpars,
meansize=self.meansize, rhomode='frac')
return self.DFR.update_datadicts(cname, rd, td)
def get_partitions(self, cname, beta, ntarget):
"""
Get partitioning information for given chromosome, with annealing beta,
with number of targets ntarget.
Each locus on the network at beta = fmatbeta will be assigned
to a partition. This is to ease computation of effective interactions
using the observed/base interaction matrix.
"""
# Get tset
rd, td = self.DFR.get_datadicts(cname)
_, tset = self.DFR.readout_datadicts(rd, td, beta, ntarget)
# Get hard, split and padded membership functions