forked from QuKunLab/ATAC-pipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmscentipede.pyx
1471 lines (1103 loc) · 46.7 KB
/
mscentipede.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
cimport numpy as np
import cython
cimport cython
import cvxopt as cvx
from cvxopt import solvers
from scipy.special import digamma, gammaln, polygamma
import scipy.optimize as spopt
import sys, time, math, pdb
# suppress optimizer output
solvers.options['show_progress'] = False
solvers.options['maxiters'] = 20
# defining some constants
EPS = np.finfo(np.double).tiny
MAX = np.finfo(np.double).max
# defining some simple functions
logistic = lambda x: 1./(1+np.exp(x))
insum = lambda x,axes: np.apply_over_axes(np.sum,x,axes)
def nplog(x):
"""Compute the natural logarithm, handling very
small floats appropriately.
"""
try:
x[x<EPS] = EPS
except TypeError:
x = max([x,EPS])
return np.log(x)
cdef class Data:
"""
A data structure to store a multiscale representation of
chromatin accessibility read counts across `N` genomic windows of
length `L` in `R` replicates.
Arguments
reads : array
"""
def __cinit__(self):
self.N = 0
self.L = 0
self.R = 0
self.J = 0
self.valueA = dict()
self.valueB = dict()
self.total = dict()
cdef transform_to_multiscale(self, np.ndarray[np.float64_t, ndim=3] reads):
"""Transform a vector of read counts
into a multiscale representation.
.. note::
See msCentipede manual for more details.
"""
cdef long k, j, size
self.N = reads.shape[0]
self.L = reads.shape[1]
self.R = reads.shape[2]
self.J = math.frexp(self.L)[1]-1
for j from 0 <= j < self.J:
size = self.L/(2**(j+1))
self.total[j] = np.array([reads[:,k*size:(k+2)*size,:].sum(1) for k in xrange(0,2**(j+1),2)]).T
self.valueA[j] = np.array([reads[:,k*size:(k+1)*size,:].sum(1) for k in xrange(0,2**(j+1),2)]).T
self.valueB[j] = self.total[j] - self.valueA[j]
def inverse_transform(self):
"""Transform a multiscale representation of the data or parameters,
into vector representation.
"""
if self.data:
profile = np.array([val for k in xrange(2**self.J) \
for val in [self.value[self.J-1][k][0],self.value[self.J-1][k][1]-self.value[self.J-1][k][0]]])
else:
profile = np.array([1])
for j in xrange(self.J):
profile = np.array([p for val in profile for p in [val,val]])
vals = np.array([i for v in self.value[j] for i in [v,1-v]])
profile = vals*profile
return profile
def copy(self):
""" Create a copy of the class instance
"""
cdef long j
newcopy = Data()
newcopy.J = self.J
newcopy.N = self.N
newcopy.L = self.L
newcopy.R = self.R
for j from 0 <= j < self.J:
newcopy.valueA[j] = self.valueA[j]
newcopy.valueB[j] = self.valueB[j]
newcopy.total[j] = self.total[j]
return newcopy
cdef class Zeta:
"""
Inference class to store and update (E-step) the posterior
probability that a transcription factor is bound to a motif
instance.
Arguments
data : Data
totalreads : array
"""
def __cinit__(self, np.ndarray[np.float64_t, ndim=2] totalreads, long N, bool infer):
cdef np.ndarray order, indices
self.N = N
self.total = totalreads
if infer:
self.prior_log_odds = np.zeros((self.N,1), dtype=float)
self.footprint_log_likelihood_ratio = np.zeros((self.N,1), dtype=float)
self.total_log_likelihood_ratio = np.zeros((self.N,1), dtype=float)
self.posterior_log_odds = np.zeros((self.N,1), dtype=float)
else:
self.estim = np.zeros((self.N, 2),dtype=float)
order = np.argsort(self.total.sum(1))
indices = order[:self.N/2]
self.estim[indices,1:] = -MAX
indices = order[self.N/2:]
self.estim[indices,1:] = MAX
self.estim = np.exp(self.estim - np.max(self.estim,1).reshape(self.N,1))
self.estim = self.estim / insum(self.estim,[1])
cdef update(self, Data data, np.ndarray[np.float64_t, ndim=2] scores, \
Pi pi, Tau tau, Alpha alpha, Beta beta, Omega omega, \
Pi pi_null, Tau tau_null, str model):
cdef long j
cdef np.ndarray[np.float64_t, ndim=2] footprint_logodds, prior_logodds, negbin_logodds
cdef Data lhoodA, lhoodB
footprint_logodds = np.zeros((self.N,1), dtype=float)
lhoodA, lhoodB = compute_footprint_likelihood(data, pi, tau, pi_null, tau_null, model)
for j from 0 <= j < data.J:
footprint_logodds += insum(lhoodA.valueA[j] - lhoodB.valueA[j],[1])
prior_logodds = insum(beta.estim * scores, [1])
negbin_logodds = insum(gammaln(self.total + alpha.estim.T[1]) \
- gammaln(self.total + alpha.estim.T[0]) \
+ gammaln(alpha.estim.T[0]) - gammaln(alpha.estim.T[1]) \
+ alpha.estim.T[1] * nplog(omega.estim.T[1]) - alpha.estim.T[0] * nplog(omega.estim.T[0]) \
+ self.total * (nplog(1 - omega.estim.T[1]) - nplog(1 - omega.estim.T[0])),[1])
self.estim[:,1:] = prior_logodds + footprint_logodds + negbin_logodds
self.estim[:,0] = 0.
self.estim[self.estim==np.inf] = MAX
self.estim = np.exp(self.estim-np.max(self.estim,1).reshape(self.N,1))
self.estim = self.estim/insum(self.estim,[1])
cdef infer(self, Data data, np.ndarray[np.float64_t, ndim=2] scores, \
Pi pi, Tau tau, Alpha alpha, Beta beta, Omega omega, \
Pi pi_null, Tau tau_null, str model):
cdef long j
cdef Data lhoodA, lhoodB
lhoodA, lhoodB = compute_footprint_likelihood(data, pi, tau, pi_null, tau_null, model)
for j from 0 <= j < data.J:
self.footprint_log_likelihood_ratio += insum(lhoodA.valueA[j] - lhoodB.valueA[j],[1])
self.footprint_log_likelihood_ratio = self.footprint_log_likelihood_ratio / np.log(10)
self.prior_log_odds = insum(beta.estim * scores, [1]) / np.log(10)
self.total_log_likelihood_ratio = insum(gammaln(self.total + alpha.estim.T[1]) \
- gammaln(self.total + alpha.estim.T[0]) \
+ gammaln(alpha.estim.T[0]) - gammaln(alpha.estim.T[1]) \
+ alpha.estim.T[1] * nplog(omega.estim.T[1]) - alpha.estim.T[0] * nplog(omega.estim.T[0]) \
+ self.total * (nplog(1 - omega.estim.T[1]) - nplog(1 - omega.estim.T[0])),[1])
self.total_log_likelihood_ratio = self.total_log_likelihood_ratio / np.log(10)
self.posterior_log_odds = self.prior_log_odds \
+ self.footprint_log_likelihood_ratio \
+ self.total_log_likelihood_ratio
cdef class Pi:
"""
Class to store and update (M-step) the parameter `p` in the
msCentipede model. It is also used for the parameter `p_o` in
the msCentipede-flexbg model.
Arguments
J : int
number of scales
"""
def __cinit__(self, long J):
cdef long j
self.J = J
self.value = dict()
for j from 0 <= j < self.J:
self.value[j] = np.empty((2**j,), dtype='float')
def __reduce__(self):
return (rebuild_Pi, (self.J,self.value))
def update(self, Data data, Zeta zeta, Tau tau):
"""Update the estimates of parameter `p` (and `p_o`) in the model.
"""
zetaestim = zeta.estim[:,1].sum()
# call optimizer
for j in xrange(self.J):
# initialize optimization variable
xo = self.value[j].copy()
X = xo.size
# set constraints for optimization variable
xmin = 1./tau.estim[j]*np.ones((X,1),dtype=float)
xmax = (1-1./tau.estim[j])*np.ones((X,1),dtype=float)
G = np.vstack((np.diag(-1*np.ones((X,), dtype=float)), \
np.diag(np.ones((X,), dtype=float))))
h = np.vstack((-1*xmin,xmax))
# additional arguments
args = dict([('G',G),('h',h),('data',data),('zeta',zeta),('tau',tau),('zetaestim',zetaestim),('j',j)])
# call optimizer
x_final = optimizer(xo, pi_function_gradient, pi_function_gradient_hessian, args)
if np.isnan(x_final).any():
print "Nan in Pi"
raise ValueError
if np.isinf(x_final).any():
print "Inf in Pi"
raise ValueError
# store optimum in data structure
self.value[j] = x_final
def rebuild_Pi(J, value):
pi = Pi(J)
pi.value = value
return pi
cpdef tuple pi_function_gradient(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `pi`, along with its gradient
"""
cdef Data data
cdef Zeta zeta
cdef Tau tau
cdef long j, J, r
cdef double f, zetaestim
cdef np.ndarray func, F, Df, df, alpha, beta, data_alpha, data_beta
data = args['data']
zeta = args['zeta']
tau = args['tau']
zetaestim = args['zetaestim']
j = args['j']
J = 2**j
func = np.zeros((data.N,J), dtype=float)
df = np.zeros((data.N,J), dtype=float)
alpha = x * tau.estim[j]
beta = (1-x) * tau.estim[j]
for r from 0 <= r < data.R:
data_alpha = data.valueA[j][r] + alpha
data_beta = data.valueB[j][r] + beta
func += gammaln(data_alpha) + gammaln(data_beta)
df += digamma(data_alpha) - digamma(data_beta)
F = np.sum(func,1) - np.sum(gammaln(alpha) + gammaln(beta)) * data.R
Df = tau.estim[j] * (np.sum(zeta.estim[:,1:] * df,0) \
- zetaestim * (digamma(alpha) - digamma(beta)) * data.R)
f = -1. * np.sum(zeta.estim[:,1] * F)
Df = -1. * Df
return f, Df
cpdef tuple pi_function_gradient_hessian(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `pi`, along with its gradient and hessian
"""
cdef Data data
cdef Zeta zeta
cdef Tau tau
cdef long j, J, r
cdef double f, zetaestim
cdef np.ndarray func, F, Df, df, hf, hess, Hf
data = args['data']
zeta = args['zeta']
tau = args['tau']
zetaestim = args['zetaestim']
j = args['j']
hess = np.zeros((x.size,), dtype=float)
J = 2**j
func = np.zeros((data.N,J), dtype=float)
df = np.zeros((data.N,J), dtype=float)
hf = np.zeros((data.N,J), dtype=float)
alpha = x * tau.estim[j]
beta = (1-x) * tau.estim[j]
for r from 0 <= r < data.R:
data_alpha = data.valueA[j][r] + alpha
data_beta = data.valueB[j][r] + beta
func += gammaln(data_alpha) + gammaln(data_beta)
df += digamma(data_alpha) - digamma(data_beta)
hf += polygamma(1, data_alpha) + polygamma(1, data_beta)
F = np.sum(func,1) - np.sum(gammaln(alpha) + gammaln(beta)) * data.R
Df = tau.estim[j] * (np.sum(zeta.estim[:,1:] * df,0) \
- zetaestim * (digamma(alpha) - digamma(beta)) * data.R)
hess = tau.estim[j]**2 * (np.sum(zeta.estim[:,1:] * hf,0) \
- zetaestim * (polygamma(1, alpha) + polygamma(1, beta)) * data.R)
f = -1. * np.sum(zeta.estim[:,1] * F)
Df = -1. * Df
Hf = np.diag(-1.*hess)
return f, Df, Hf
cdef class Tau:
"""
Class to store and update (M-step) the parameter `tau` in the
msCentipede model. It is also used for the parameter `tau_o` in
the msCentipede-flexbg model.
Arguments
J : int
number of scales
"""
def __cinit__(self, long J):
self.J = J
self.estim = np.empty((self.J,), dtype='float')
def __reduce__(self):
return (rebuild_Tau, (self.J,self.estim))
def update(self, Data data, Zeta zeta, Pi pi):
"""Update the estimates of parameter `tau` (and `tau_o`) in the model.
"""
zetaestim = np.sum(zeta.estim[:,1])
for j in xrange(self.J):
# initialize optimization variables
xo = self.estim[j:j+1]
# set constraints for optimization variables
minj = 1./min([np.min(pi.value[j]), np.min(1-pi.value[j])])
xmin = np.array([minj])
G = np.diag(-1 * np.ones((1,), dtype=float))
h = -1*xmin.reshape(1,1)
# additional arguments
args = dict([('j',j),('G',G),('h',h),('data',data),('zeta',zeta),('pi',pi),('zetaestim',zetaestim)])
# call optimizer
try:
x_final = optimizer(xo, tau_function_gradient, tau_function_gradient_hessian, args)
except ValueError:
xo = xmin+100*np.random.rand()
bounds = [(minj, None)]
solution = spopt.fmin_l_bfgs_b(tau_function_gradient, xo, \
args=(args,), bounds=bounds)
x_final = solution[0]
self.estim[j:j+1] = x_final
if np.isnan(self.estim).any():
print "Nan in Tau"
raise ValueError
if np.isinf(self.estim).any():
print "Inf in Tau"
raise ValueError
def rebuild_Tau(J, estim):
tau = Tau(J)
tau.estim = estim
return tau
cpdef tuple tau_function_gradient(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `tau`, and its gradient.
"""
cdef Data data
cdef Zeta zeta
cdef Pi pi
cdef long j, J, r, left, right
cdef double F, ffunc, dff, zetaestim
cdef np.ndarray func, ff, Df, df, alpha, beta, data_alpha, data_beta, data_x
data = args['data']
zeta = args['zeta']
pi = args['pi']
zetaestim = args['zetaestim']
j = args['j']
func = np.zeros((zeta.N,), dtype=float)
ffunc = 0
Df = np.zeros((x.size,), dtype=float)
alpha = pi.value[j] * x
beta = (1 - pi.value[j]) * x
ffunc = ffunc + data.R * np.sum(gammaln(x) - gammaln(alpha) - gammaln(beta))
dff = data.R * np.sum(digamma(x) - pi.value[j] * digamma(alpha) - (1 - pi.value[j]) * digamma(beta))
df = np.zeros((zeta.N,), dtype=float)
# loop over replicates
for r from 0 <= r < data.R:
data_alpha = data.valueA[j][r] + alpha
data_beta = data.valueB[j][r] + beta
data_x = data.total[j][r] + x
func = func + np.sum(gammaln(data_alpha),1) \
+ np.sum(gammaln(data_beta),1) - np.sum(gammaln(data_x),1)
df = df + np.sum(pi.value[j]*digamma(data_alpha),1) \
+ np.sum((1-pi.value[j])*digamma(data_beta),1) \
- np.sum(digamma(data_x),1)
Df[0] = -1. * (np.sum(zeta.estim[:,1] * df) + zetaestim * dff)
F = -1. * (np.sum(zeta.estim[:,1] * func) + zetaestim * ffunc)
return F, Df
cpdef tuple tau_function_gradient_hessian(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `tau`, and its gradient and hessian.
"""
cdef Data data
cdef Zeta zeta
cdef Pi pi
cdef long j, r, left, right
cdef double F, ffunc, dff, hff, zetaestim
cdef np.ndarray func, ff, Df, df, hf, hess, Hf, alpha, beta, data_alpha, data_beta, data_x
data = args['data']
zeta = args['zeta']
pi = args['pi']
zetaestim = args['zetaestim']
j = args['j']
func = np.zeros((zeta.N,), dtype=float)
ffunc = 0
Df = np.zeros((x.size,), dtype=float)
hess = np.zeros((x.size,), dtype=float)
# loop over each scale
alpha = pi.value[j] * x
beta = (1 - pi.value[j]) * x
ffunc = ffunc + data.R * np.sum(gammaln(x) - gammaln(alpha) - gammaln(beta))
dff = data.R * np.sum(digamma(x) - pi.value[j] * digamma(alpha) - (1 - pi.value[j]) * digamma(beta))
hff = data.R * np.sum(polygamma(1, x) - pi.value[j]**2 * polygamma(1, alpha) \
- (1-pi.value[j])**2 * polygamma(1, beta))
df = np.zeros((zeta.N,), dtype=float)
hf = np.zeros((zeta.N,), dtype=float)
# loop over replicates
for r from 0 <= r < data.R:
data_alpha = data.valueA[j][r] + alpha
data_beta = data.valueB[j][r] + beta
data_x = data.total[j][r] + x
func = func + np.sum(gammaln(data_alpha),1) + np.sum(gammaln(data_beta),1) - np.sum(gammaln(data_x),1)
df = df + np.sum(pi.value[j]*digamma(data_alpha),1) \
+ np.sum((1-pi.value[j])*digamma(data_beta),1) \
- np.sum(digamma(data_x),1)
hf = hf + np.sum(pi.value[j]**2 * polygamma(1,data_alpha),1) \
+ np.sum((1 - pi.value[j])**2 * polygamma(1,data_beta),1) \
- np.sum(polygamma(1,data_x),1)
Df[0] = -1 * (np.sum(zeta.estim[:,1] * df) + zetaestim * dff)
hess[0] = -1 * (np.sum(zeta.estim[:,1] * hf) + zetaestim * hff)
F = -1. * (np.sum(zeta.estim[:,1] * func) + zetaestim * ffunc)
Hf = np.diag(hess)
return F, Df, Hf
cdef class Alpha:
"""
Class to store and update (M-step) the parameter `alpha` in negative
binomial part of the msCentipede model. There is a separate parameter
for bound and unbound states, for each replicate.
Arguments
R : int
number of replicate measurements
"""
def __cinit__(self, long R):
self.R = R
self.estim = np.random.rand(self.R,2)*10
def __reduce__(self):
return (rebuild_Alpha, (self.R,self.estim))
def update(self, Zeta zeta, Omega omega):
"""Update the estimates of parameter `alpha` in the model.
"""
cdef np.ndarray zetaestim, constant, xo, G, h, x_final
zetaestim = np.sum(zeta.estim,0)
constant = zetaestim*nplog(omega.estim)
# initialize optimization variables
xo = self.estim.ravel()
# set constraints for optimization variables
G = np.diag(-1 * np.ones((2*self.R,), dtype=float))
h = np.zeros((2*self.R,1), dtype=float)
args = dict([('G',G),('h',h),('omega',omega),('zeta',zeta),('constant',constant),('zetaestim',zetaestim)])
# call optimizer
x_final = optimizer(xo, alpha_function_gradient, alpha_function_gradient_hessian, args)
self.estim = x_final.reshape(self.R,2)
if np.isnan(self.estim).any():
print "Nan in Alpha"
raise ValueError
if np.isinf(self.estim).any():
print "Inf in Alpha"
raise ValueError
def rebuild_Alpha(R, estim):
alpha = Alpha(R)
alpha.estim = estim
return alpha
cpdef tuple alpha_function_gradient(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `alpha`, and its gradient
"""
cdef long r
cdef double f, func
cdef Zeta zeta
cdef Omega omega
cdef np.ndarray df, Df, constant, zetaestim, xzeta
zeta = args['zeta']
omega = args['omega']
constant = args['constant']
zetaestim = args['zetaestim']
func = 0
df = np.zeros((2*omega.R,), dtype='float')
for r from 0 <= r < omega.R:
xzeta = zeta.total[:,r:r+1] + x[2*r:2*r+2]
func = func + np.sum(np.sum(gammaln(xzeta) * zeta.estim, 0) \
- gammaln(x[2*r:2*r+2]) * zetaestim + constant[r] * x[2*r:2*r+2])
df[2*r:2*r+2] = np.sum(digamma(xzeta) * zeta.estim, 0) \
- digamma(x[2*r:2*r+2]) * zetaestim + constant[r]
f = -1.*func
Df = -1. * df
return f, Df
cpdef tuple alpha_function_gradient_hessian(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `alpha`, and its gradient and hessian
"""
cdef long r
cdef double f, func
cdef Zeta zeta
cdef Omega omega
cdef np.ndarray df, Df, hf, Hf, constant, zetaestim, xzeta
zeta = args['zeta']
omega = args['omega']
zetaestim = args['zetaestim']
constant = args['constant']
func = 0
df = np.zeros((2*omega.R,), dtype='float')
hess = np.zeros((2*omega.R,), dtype='float')
for r from 0 <= r < omega.R:
xzeta = zeta.total[:,r:r+1] + x[2*r:2*r+2]
func = func + np.sum(np.sum(gammaln(xzeta) * zeta.estim, 0) \
- gammaln(x[2*r:2*r+2]) * zetaestim + constant[r] * x[2*r:2*r+2])
df[2*r:2*r+2] = np.sum(digamma(xzeta) * zeta.estim, 0) \
- digamma(x[2*r:2*r+2]) * zetaestim + constant[r]
hess[2*r:2*r+2] = np.sum(polygamma(1, xzeta) * zeta.estim, 0) \
- polygamma(1, x[2*r:2*r+2]) * zetaestim
f = -1. * func
Df = -1. * df
Hf = -1. * np.diag(hess)
return f, Df, Hf
cdef class Omega:
"""
Class to store and update (M-step) the parameter `omega` in negative
binomial part of the msCentipede model. There is a separate parameter
for bound and unbound states, for each replicate.
Arguments
R : int
number of replicate measurements
"""
def __cinit__(self, long R):
self.R = R
self.estim = np.random.rand(self.R,2)
self.estim[:,1] = self.estim[:,1]/100
def __reduce__(self):
return (rebuild_Omega, (self.R,self.estim))
cdef update(self, Zeta zeta, Alpha alpha):
"""Update the estimates of parameter `omega` in the model.
"""
cdef np.ndarray numerator, denominator
numerator = np.sum(zeta.estim,0) * alpha.estim
denominator = np.array([np.sum(zeta.estim * (estim + zeta.total[:,r:r+1]), 0) \
for r,estim in enumerate(alpha.estim)])
self.estim = numerator / denominator
if np.isnan(self.estim).any():
print "Nan in Omega"
raise ValueError
if np.isinf(self.estim).any():
print "Inf in Omega"
raise ValueError
def rebuild_Omega(R, estim):
omega = Omega(R)
omega.estim = estim
return omega
cdef class Beta:
"""
Class to store and update (M-step) the parameter `beta` in the logistic
function in the prior of the msCentipede model.
Arguments
scores : array
an array of scores for each motif instance. these could include
PWM score, conservation score, a measure of various histone
modifications, outputs from other algorithms, etc.
"""
def __cinit__(self, long S):
self.S = S
self.estim = np.random.rand(self.S)
def __reduce__(self):
return (rebuild_Beta, (self.S,self.estim))
def update(self, np.ndarray[np.float64_t, ndim=2] scores, Zeta zeta):
"""Update the estimates of parameter `beta` in the model.
"""
xo = self.estim.copy()
args = dict([('scores',scores),('zeta',zeta)])
try:
self.estim = optimizer(xo, beta_function_gradient, beta_function_gradient_hessian, args)
except (ValueError, OverflowError):
pass
if np.isnan(self.estim).any():
print "Nan in Beta"
raise ValueError
if np.isinf(self.estim).any():
print "Inf in Beta"
raise ValueError
def rebuild_Beta(S, estim):
beta = Beta(S)
beta.estim = estim
return beta
cpdef tuple beta_function_gradient(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `beta`, and its gradient.
"""
scores = args['scores']
zeta = args['zeta']
arg = insum(x * scores,[1])
func = arg * zeta.estim[:,1:] - nplog(1 + np.exp(arg))
f = -1. * func.sum()
Df = -1 * np.sum(scores * (zeta.estim[:,1:] - logistic(-arg)),0)
return f, Df
cpdef tuple beta_function_gradient_hessian(np.ndarray[np.float64_t, ndim=1] x, dict args):
"""Computes part of the likelihood function that has
terms containing `beta`, and its gradient and hessian.
"""
scores = args['scores']
zeta = args['zeta']
arg = insum(x * scores,[1])
func = arg * zeta.estim[:,1:] - nplog(1 + np.exp(arg))
f = -1. * func.sum()
Df = -1 * np.sum(scores * (zeta.estim[:,1:] - logistic(-arg)),0)
larg = scores * logistic(arg) * logistic(-arg)
Hf = np.dot(scores.T, larg)
return f, Df, Hf
def optimizer(np.ndarray[np.float64_t, ndim=1] xo, function_gradient, function_gradient_hessian, dict args):
"""Calls the appropriate nonlinear convex optimization solver
in the package `cvxopt` to find optimal values for the relevant
parameters, given subroutines that evaluate a function,
its gradient, and hessian, this subroutine
Arguments
function : function object
evaluates the function at the specified parameter values
gradient : function object
evaluates the gradient of the function
hessian : function object
evaluates the hessian of the function
"""
def F(x=None, z=None):
"""A subroutine that the cvxopt package can call to get
values of the function, gradient and hessian during
optimization.
"""
if x is None:
return 0, cvx.matrix(x_init)
xx = np.array(x).ravel().astype(np.float64)
if z is None:
# compute likelihood function and gradient
f, Df = function_gradient(xx, args)
# check for infs and nans in function and gradient
if np.isnan(f) or np.isinf(f):
f = np.array([np.finfo('float32').max]).astype('float')
else:
f = np.array([f]).astype('float')
if np.isnan(Df).any() or np.isinf(Df).any():
Df = -1 * np.finfo('float32').max * np.ones((1,xx.size), dtype=float)
else:
Df = Df.reshape(1,xx.size)
return cvx.matrix(f), cvx.matrix(Df)
else:
# compute likelihood function, gradient, and hessian
f, Df, hess = function_gradient_hessian(xx, args)
# check for infs and nans in function and gradient
if np.isnan(f) or np.isinf(f):
f = np.array([np.finfo('float32').max]).astype('float')
else:
f = np.array([f]).astype('float')
if np.isnan(Df).any() or np.isinf(Df).any():
Df = -1 * np.finfo('float32').max * np.ones((1,xx.size), dtype=float)
else:
Df = Df.reshape(1,xx.size)
Hf = z[0] * hess
return cvx.matrix(f), cvx.matrix(Df), cvx.matrix(Hf)
# warm start for the optimization
V = xo.size
x_init = xo.reshape(V,1)
# call the optimization subroutine in cvxopt
if args.has_key('G'):
# call a constrained nonlinear solver
solution = solvers.cp(F, G=cvx.matrix(args['G']), h=cvx.matrix(args['h']))
else:
# call an unconstrained nonlinear solver
solution = solvers.cp(F)
x_final = np.array(solution['x']).ravel()
return x_final
cdef tuple compute_footprint_likelihood(Data data, Pi pi, Tau tau, Pi pi_null, Tau tau_null, str model):
"""Evaluates the likelihood function for the
footprint part of the bound model and background model.
Arguments
data : Data
transformed read count data
pi : Pi
estimate of mean footprint parameters at bound sites
tau : Tau
estimate of footprint heterogeneity at bound sites
pi_null : Pi
estimate of mean cleavage pattern at unbound sites
tau_null : Tau or None
estimate of cleavage heterogeneity at unbound sites
model : string
{msCentipede, msCentipede-flexbgmean, msCentipede-flexbg}
"""
cdef long j, r
cdef np.ndarray valueA, valueB
cdef Data lhood_bound, lhood_unbound
lhood_bound = Data()
lhood_unbound = Data()
for j from 0 <= j < data.J:
valueA = np.sum(data.valueA[j],0)
valueB = np.sum(data.valueB[j],0)
lhood_bound.valueA[j] = np.sum([gammaln(data.valueA[j][r] + pi.value[j] * tau.estim[j]) \
+ gammaln(data.valueB[j][r] + (1 - pi.value[j]) * tau.estim[j]) \
- gammaln(data.total[j][r] + tau.estim[j]) + gammaln(tau.estim[j]) \
- gammaln(pi.value[j] * tau.estim[j]) - gammaln((1 - pi.value[j]) * tau.estim[j]) \
for r in xrange(data.R)],0)
if model in ['msCentipede','msCentipede_flexbgmean']:
lhood_unbound.valueA[j] = valueA * nplog(pi_null.value[j]) \
+ valueB * nplog(1 - pi_null.value[j])
elif model=='msCentipede_flexbg':
lhood_unbound.valueA[j] = np.sum([gammaln(data.valueA[j][r] + pi_null.value[j] * tau_null.estim[j]) \
+ gammaln(data.valueB[j][r] + (1 - pi_null.value[j]) * tau_null.estim[j]) \
- gammaln(data.total[j][r] + tau_null.estim[j]) + gammaln(tau_null.estim[j]) \
- gammaln(pi_null.value[j] * tau_null.estim[j]) - gammaln((1 - pi_null.value[j]) * tau_null.estim[j]) \
for r in xrange(data.R)],0)
return lhood_bound, lhood_unbound
cdef double likelihood(Data data, np.ndarray[np.float64_t, ndim=2] scores, \
Zeta zeta, Pi pi, Tau tau, Alpha alpha, Beta beta, \
Omega omega, Pi pi_null, Tau tau_null, str model):
"""Evaluates the likelihood function of the full
model, given estimates of model parameters.
Arguments
data : Data
transformed read count data
scores : array
an array of scores for each motif instance. these could include
PWM score, conservation score, a measure of various histone
modifications, outputs from other algorithms, etc.
zeta : zeta
expected value of factor binding state for each site.
pi : Pi
estimate of mean footprint parameters at bound sites
tau : Tau
estimate of footprint heterogeneity at bound sites
alpha : Alpha
estimate of negative binomial parameters for each replicate
beta : Beta
weights for various scores in the logistic function
omega : Omega
estimate of negative binomial parameters for each replicate
pi_null : Pi
estimate of mean cleavage pattern at unbound sites
tau_null : Tau or None
estimate of cleavage heterogeneity at unbound sites
model : string
{msCentipede, msCentipede-flexbgmean, msCentipede-flexbg}
"""
cdef long j
cdef double L
cdef np.ndarray apriori, footprint, null, P_1, P_0, LL
cdef Data lhoodA, lhoodB
apriori = insum(beta.estim * scores,[1])
lhoodA, lhoodB = compute_footprint_likelihood(data, pi, tau, pi_null, tau_null, model)
footprint = np.zeros((data.N,1),dtype=float)
for j from 0 <= j < data.J:
footprint += insum(lhoodA.valueA[j],[1])
P_1 = footprint + insum(gammaln(zeta.total + alpha.estim[:,1]) - gammaln(alpha.estim[:,1]) \
+ alpha.estim[:,1] * nplog(omega.estim[:,1]) + zeta.total * nplog(1 - omega.estim[:,1]), [1])
P_1[P_1==np.inf] = MAX
P_1[P_1==-np.inf] = -MAX
null = np.zeros((data.N,1), dtype=float)
for j from 0 <= j < data.J:
null += insum(lhoodB.valueA[j],[1])
P_0 = null + insum(gammaln(zeta.total + alpha.estim[:,0]) - gammaln(alpha.estim[:,0]) \
+ alpha.estim[:,0] * nplog(omega.estim[:,0]) + zeta.total * nplog(1 - omega.estim[:,0]), [1])
P_0[P_0==np.inf] = MAX
P_0[P_0==-np.inf] = -MAX
LL = P_0 * zeta.estim[:,:1] + P_1 * zeta.estim[:,1:] + apriori * (1 - zeta.estim[:,:1]) \
- nplog(1 + np.exp(apriori)) - insum(zeta.estim * nplog(zeta.estim),[1])
L = LL.sum() / data.N
if np.isnan(L):
print "Nan in LogLike"
return -np.inf
if np.isinf(L):
print "Inf in LogLike"
return -np.inf