-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathDRAGON.R
More file actions
412 lines (357 loc) · 12.9 KB
/
DRAGON.R
File metadata and controls
412 lines (357 loc) · 12.9 KB
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
# helper functions as in the netzooPy impl
# def Scale(X):
# X_temp = X
# X_std = np.std(X_temp, axis=0)
# X_mean = np.mean(X_temp, axis=0)
# return (X_temp - X_mean) / X_std
scale = function(x,bias=FALSE)
{
# sd does 1/(n-1), python does 1/n
# use the bias option for exact match with python
n = length(x)
if(bias)
{
n = length(x)
numer = (x-mean(x))
denom = sqrt((n-1)/n)*sd(x)
return(numer/denom)
}
return((x-mean(x))/sd(x))
}
# def VarS(X):
# xbar = np.mean(X, 0)
# n = X.shape[0]
# x_minus_xbar = X - xbar
# a = x_minus_xbar*x_minus_xbar
# wbar = np.cov(X.T, bias=True)#x_minus_xbar.T@x_minus_xbar/n
# varS = a.T@a
# varS += - n*wbar**2
# varS *= n/(n-1)**3
# return(varS)
# VarS calculates the unbiased estimate of the entries of
# S according to the formula in Appendix A of Schafer and Strimmer
# 2005
VarS = function(x)
{
# x is an n x p matrix of data
# xbar = np.mean(X, 0)
# n = X.shape[0]
n = nrow(x)
p = ncol(x)
# x_minus_xbar = X - xbar
x_minus_xbar = apply(x,2,function(x){x-mean(x)}) # center
# sanity check
apply(x_minus_xbar,2,mean)
a = x_minus_xbar*x_minus_xbar
varHat_s = n/((n-1)^3)* apply(a,2,sum)
wbar = 1/n*t(x_minus_xbar) %*% x_minus_xbar # this should be an outer product
# varS = a.T@a
# varS += - n*wbar**2
# varS *= n/(n-1)**3
# try doing this with an array instead of matrix multiplication
# xbar = apply(x,2,mean)
# p = ncol(x)
# w = array(dim=c(n,p,p))
# for(k in 1:n)
# {
# for(i in 1:p)
# {
# for(j in 1:p) # this will be symmetric, but leaving it now for clarity
# {
# w[k,i,j] = (x[k,i] - xbar[i])*(x[k,j]-xbar[j])
# }
# }
# }
#
# wbar = 1/n*apply(w,2:3,sum)
# summand = 0
# for(k in 1:n)
# summand = summand + (w[k,,]-wbar)^2
#
# varhat_s = n/((n-1)^3)*summand
varS = t(a) %*% a + -n*wbar^2
varHat_s = n/((n-1)^3)*varS
return(varHat_s)
# this code matches with the python output
}
# def EsqS(X):
# #xbar = np.mean(X, 0)
# n = X.shape[0]
# #x_minus_xbar = X - xbar
# wbar = np.cov(X.T, bias=True) #x_minus_xbar.T@x_minus_xbar/n
# ES2 = wbar**2*n**2/(n-1)**2 #
# return(ES2)
EsqS = function(x)
{
n = nrow(x)
wbar = (n-1)/n*cov(x)
ES2 = wbar^2*n^2/((n-1)^2)
return(ES2)
# this code matches with the python output
}
# def risk_orig(lam):
# R = const + (lam[0]*T1_1 + lam[1]*T1_2
# + lam[0]**2*T2_1 + lam[1]**2*T2_2
# + lam[0]*lam[1]*T3 + np.sqrt(1-lam[0])*np.sqrt(1-lam[1])*T4) #reparametrize lamx = 1-lamx**2 for better optimization
# return(R)
risk_orig = function(lambda1, lambda2, t11, t12, t21, t22, t3, t4)
{
print("[dragonR] risk_orig(): This is not the reparameterized version.")
return(lambda1*t11 + lambda2*t12 +
lambda1^2*t21 + lambda2^2*t22 +
lambda1*lambda2*t3 +
sqrt(1-lambda1)*sqrt(1-lambda2)*t4)
}
# def risk(lam):
# R = const + ((1.-lam[0]**2)*T1_1 + (1.-lam[1]**2)*T1_2
# + (1.-lam[0]**2)**2*T2_1 + (1.-lam[1]**2)**2*T2_2
# + (1.-lam[0]**2)*(1.-lam[1]**2)*T3 + lam[0]*lam[1]*T4) #reparametrize lamx = 1-lamx**2 for better optimization
# return(R)
# reparameterize gamma1 = (1-lambda1^2), gamma2 = (1-lambda2^2)
risk = function(gamma, const, t11, t12, t21, t22, t3, t4)
{
gamma1 = gamma[1]
gamma2 = gamma[2]
R = const + (1-gamma1^2)*t11 + (1-gamma2^2)*t12 +
(1-gamma1^2)^2*t21 + (1-gamma2^2)^2*t22 +
(1-gamma1^2)*(1-gamma2^2)*t3 + gamma1*gamma2*t4
return(R)
}
# def estimate_penalty_parameters_dragon(X1, X2):
estimatePenaltyParameters = function(X1,X2)
{
# X1 = matrix(c(1,2,3,1,5,12),nrow=3,byrow=TRUE)
# X2 = matrix(c(9,7,8),nrow=3,byrow=TRUE)
# X1 is omics matrix 1, dimensions n x p1
# X2 is omics matrix 2, dimensions n x p2
# The matrices should have the same ordering by samples
n = nrow(X1)
p1 = ncol(X1)
p2 = ncol(X2)
# n = X1.shape[0]
# p1 = X1.shape[1]
# p2 = X2.shape[1]
X = cbind.data.frame(X1, X2)
# X = np.append(X1, X2, axis=1)
# varS = VarS(X)
# eSqs = EsqS(X)
varS = VarS(X)
esqS = EsqS(X)
# IDs = np.cumsum([p1,p2])
IDs = cumsum(c(p1,p2))
# varS1 = varS[0:IDs[0],0:IDs[0]]
varS1 = varS[1:IDs[1],1:IDs[1]]
# varS12 = varS[0:IDs[0],IDs[0]:IDs[1]]
varS12 = varS[1:IDs[1],(IDs[1]+1):IDs[2]]
# varS2 = varS[IDs[0]:IDs[1],IDs[0]:IDs[1]]
varS2 = varS[(IDs[1]+1):IDs[2],(IDs[1]+1):IDs[2]]
# eSqs1 = eSqs[0:IDs[0],0:IDs[0]]
esqS1 = esqS[1:IDs[1],1:IDs[1]]
# eSqs12 = eSqs[0:IDs[0],IDs[0]:IDs[1]]
esqS12 = esqS[1:IDs[1],(IDs[1]+1):IDs[2]]
# eSqs2 = eSqs[IDs[0]:IDs[1],IDs[0]:IDs[1]]
esqS2 = esqS[(IDs[1]+1):IDs[2],(IDs[1]+1):IDs[2]]
#
# const = (np.sum(varS1) + np.sum(varS2) - 2.*np.sum(varS12)
# + 4.*np.sum(eSqs12))
# T1_1 = -2.*(np.sum(varS1) - np.trace(varS1) + np.sum(eSqs12))
T1_1 = -2*(sum(varS1) - sum(diag(as.matrix(varS1))) + sum(esqS12))
# T1_2 = -2.*(np.sum(varS2) - np.trace(varS2) + np.sum(eSqs12))
T1_2 = -2*(sum(varS2) - sum(diag(as.matrix(varS2))) + sum(esqS12))
# T2_1 = np.sum(eSqs1) - np.trace(eSqs1)
T2_1 = sum(esqS1) - sum(diag(as.matrix(esqS1)))
# T2_2 = np.sum(eSqs2) - np.trace(eSqs2)
T2_2 = sum(esqS2) - sum(diag(as.matrix(esqS2)))
# T3 = 2.*np.sum(eSqs12)
T3 = 2*sum(esqS12)
# T4 = 4.*(np.sum(varS12)-np.sum(eSqs12))
T4 = 4*(sum(varS12)-sum(esqS12))
const = (sum(varS1) + sum(varS2) - 2*sum(varS12)
+ 4*sum(esqS12))
# x = np.arange(0., 1.01, 0.01)
x = seq(0,1,by=0.01)
riskgrid = matrix(nrow = length(x),ncol=length(x))
for(i in 1:length(x))
{
for(j in 1:length(x))
{
riskgrid[i,j] = risk(gamma=c(x[i],x[j]),
const = const,
t11=T1_1,
t12=T1_2,
t21=T2_1,
t22=T2_2,
t3=T3,
t4=T4)
}
}
dim(riskgrid)
# lamgrid = meshgrid(x, x)
# risk_grid = risk(lamgrid)
# indices = np.unravel_index(np.argmin(risk_grid.T, axis=None), risk_grid.shape)
# lams = [x[indices[0]],x[indices[1]]]
#
lams = x[arrayInd(which(riskgrid == min(riskgrid)),.dim=c(101,101))]
# this is seeding with grid search and then we use optimization
print(lams)
# res = minimize(risk, lams, method='L-BFGS-B',#'TNC',#'SLSQP',
# tol=1e-12,
# bounds = [[0.,1.],[0.,1.]])
# python result: array([0.79372539, 0. ])
res = optim(lams,risk,
const=const,
t11=T1_1,
t12=T1_2,
t21=T2_1,
t22=T2_2,
t3=T3,
t4=T4,
method="L-BFGS-B",
lower=c(0,0),
upper=c(1,1),
control = list(trace=TRUE,pgtol = 1e-15))
# reparameterize
lambdas = c(1-res$par[1]^2, 1-res$par[2]^2)
return(list("lambdas"=lambdas,"gammas"=res$par,"optim_result"=res,"risk_grid" = riskgrid))
# penalty_parameters = (1.-res.x[0]**2), (1.-res.x[1]**2)
#
# def risk_orig(lam):
# R = const + (lam[0]*T1_1 + lam[1]*T1_2
# + lam[0]**2*T2_1 + lam[1]**2*T2_2
# + lam[0]*lam[1]*T3 + np.sqrt(1-lam[0])*np.sqrt(1-lam[1])*T4) #reparametrize lamx = 1-lamx**2 for better optimization
# return(R)
# risk_grid_orig = risk_orig(lamgrid)
# return(penalty_parameters, risk_grid_orig)
#
}
get_shrunken_covariance_dragon = function(X1,X2, lambdas)
{
n = nrow(X1)
p1 = ncol(X1)
p2 = ncol(X2)
p = p1 + p2
X = cbind.data.frame(X1,X2)
S = cov(X) # the R implementation of cov() uses the unbiased (1/(n-1)); we need the unbiased version for the lemma of Ledoit and Wolf
# target matrix
Targ = diag(diag(S))
Sigma = matrix(nrow=p, ncol=p)
# Sigma = np.zeros((p,p))
# IDs = np.cumsum([0,p1,p2])
IDs = c(cumsum(c(p1,p2)))
idx1 = 1:IDs[1]
idx2 = (IDs[1]+1):IDs[2]
# Fill in Sigma_11
Sigma[idx1,idx1] = (1-lambdas[1])*S[idx1,idx1] + lambdas[1]*Targ[idx1,idx1]
# Fill in Sigma_22
Sigma[idx2,idx2] = (1-lambdas[2])*S[idx2,idx2] + lambdas[2]*Targ[idx2,idx2]
# Fill in Sigma_12
Sigma[idx1,idx2] = sqrt((1-lambdas[1])*(1-lambdas[2]))*S[idx1,idx2] + sqrt(lambdas[1]*lambdas[2])*Targ[idx1,idx2]
# Fill in Sigma_21
Sigma[idx2,idx1] = sqrt((1-lambdas[1])*(1-lambdas[2]))*S[idx2,idx1] + sqrt(lambdas[1]*lambdas[2])*Targ[idx2,idx1]
return(Sigma)
}
get_precision_matrix_dragon = function(X1, X2, lambdas)
{
Sigma = get_shrunken_covariance_dragon(X1, X2, lambdas)
Theta = solve(Sigma)
return(Theta)
# in the python implementation, mean is also returned. Omitting here
# X = np.hstack((X1, X2))
# mu = np.mean(X, axis=0)
}
get_partial_correlation_from_precision = function(Theta,selfEdges=FALSE)
{
# by default, does not return self edges (diagonal is set to zero)
ggm = -cov2cor(Theta)
if(!selfEdges)
diag(ggm) = 0
return(ggm)
}
get_partial_correlation_dragon = function(X1,X2,lambdas)
{
Theta = get_precision_matrix_dragon(X1, X2, lambdas)
ggm = get_partial_correlation_from_precision(Theta)
return(ggm)
}
# The functions below are for p-value estimation on the DRAGON results
# The functions logli, estimate_kappa, and estimate_p_values are for benchmarking
# with standard GGM; omitting here
# logli = function(X, Theta, mu)
# estimate_kappa = function(n, p, lambda0, seed)
# estimate_p_values(r, n, lambda0, kappa='estimate', seed=1):
log_lik_shrunken = function(kappa, p, lambda, rhos)
{
# kappa is to be optimized, so comes first in the arguments
# p is fixed (number of predictors)
# lambda is fixed (as estimated by DRAGON)
# rhos is fixed (observed partial correlations from the data)
mysum = 0
for(i in 1:p)
{
first_term = (kappa-3)/2*log((1-lambda)^2-rhos[i]^2)
second_term = lbeta(1/2, (kappa-1)/2)
third_term = (kappa-2)*log(1-lambda)
mysum = mysum + first_term - second_term - third_term
}
return(mysum)
}
# def estimate_kappa_dragon(n, p1, p2, lambdas, seed, simultaneous = False):
estimate_kappa_dragon = function(n, p1, n2, lambdas, seed, simultaneous = F)
{
}
# def estimate_p_values_dragon(r, n, p1, p2, lambdas, kappa='estimate', seed=1, simultaneous = False):
estimate_p_values_dragon = function(r, n, p1, p2, lambdas, kappa="estimate",seed=1, simultaneous = F)
{
}
#' Run DRAGON in R.
#'
#' Description: Estimates a multi-omic Gaussian graphical model for two input layers of paired omic data.
#'
#' @param layer1 : first layer of omics data; rows: samples (order must match layer2), columns: variables
#' @param layer2 : second layer of omics data; rows: samples (order must match layer1), columns: variables.
#' @param pval : calculate p-values for network edges. Not yet implemented in R; available in netZooPy.
#' @param gradient : method for estimating parameters of p-value distribution, applies only if p-val == TRUE. default = "finite_difference"; other option = "exact"
#' @param verbose : verbosity level (TRUE/FALSE)
#' @return A list of model results. cov : the shrunken covariance matrix
#' \item{\code{cov}}{ the shrunken covariance matrix}
#' \item{\code{prec}}{ the shrunken precision matrix}
#' \item{\code{ggm}}{ the shrunken Gaussian graphical model; matrix of partial correlations. Self-edges (diagonal elements) are set to zero.}
#' \item{\code{lambdas}}{ Vector of omics-specific tuning parameters (lambda1, lambda2) for \code{layer1} and \code{layer2}}
#' \item{\code{gammas}}{ Reparameterized tuning parameters; gamma = 1 - lambda^2}
#' \item{\code{risk_grid}}{ Risk grid, for assessing optimization. Grid boundaries are in terms of gamma.}
#'
#' @export
dragon = function(layer1,layer2,pval = FALSE,gradient = "finite_difference", verbose = FALSE)
{
if(verbose)
print("[netZooR::dragon] Estimating penalty parameters...")
# estimate penalty parameters
myres = estimatePenaltyParameters(layer1, layer2)
lambdas = myres$lambdas
if(verbose)
print(paste(c("[netZooR::dragon] Estimated parameters:",lambdas),collapse=" "))
if(verbose)
print("[netZooR::dragon] Calculating shrunken matrices...")
# apply penalty parameters to return shrunken covariance and ggm
shrunken_cov = get_shrunken_covariance_dragon(layer1, layer2,lambdas)
precmat = get_precision_matrix_dragon(layer1, layer2, lambdas)
ggm = get_partial_correlation_dragon(layer1, layer2, lambdas)
# Propagate variable names from input layers to output matrices
all_names = c(colnames(layer1), colnames(layer2))
if(!is.null(all_names) && length(all_names) == ncol(shrunken_cov)) {
rownames(shrunken_cov) = colnames(shrunken_cov) = all_names
rownames(precmat) = colnames(precmat) = all_names
rownames(ggm) = colnames(ggm) = all_names
}
# if pval, return pval approx with finite difference
if(pval)
{
print("[netZooR::dragon] p-value calculation not yet implemented in R; to estimate p-values, use netZooPy.")
}
return(list("cov"=shrunken_cov,
"prec"=precmat,
"ggm"=ggm,
"lambdas"=lambdas,
"gammas"=myres$gammas,
"risk_grid"=myres$risk_grid))
}