Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 31 additions & 18 deletions netZooPy/cobra/cobra.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import pandas as pd
import numpy as np
from scipy.linalg import eigh,pinv
from sklearn.linear_model import LinearRegression, Lasso


def cobra(X, expression):
def cobra(X, expression, cobra='nnls', alpha: np.float64=0.1):
"""
COBRA decomposes a (partial) gene co-expression matrix as a
linear combination of covariate-specific components.
Expand All @@ -16,6 +17,12 @@ def cobra(X, expression):
design matrix of size (n, q), n = number of samples, q = number of covariates
expression : np.ndarray, pd.DataFrame
gene expression as a matrix of size (g, n), g = number of genes
cobra : string
regression mode
nnls: Non-negative least square (default)
nnlasso: Non-negative LASSO
deprecated: MLE estimate
alpha :
Returns
---------
psi : array
Expand Down Expand Up @@ -55,26 +62,32 @@ def cobra(X, expression):
Q = c_eigenvectors[:, indices_nonzero].T[::-1].T

#
gtq = np.matmul(g.T, Q)
d = c_eigenvalues[indices_nonzero][::-1]

#
xtx_inv = np.linalg.pinv(
np.dot(X.T, X)
)
xtx_inv_xt = np.dot(
xtx_inv, X.T
)
if cobra=='nnls':
model = LinearRegression(positive=True).fit(X, np.diag(d) )
psi = np.transpose(model.coef_)
elif cobra=='nnlasso':
model == Lasso(alpha=alpha, positive=True).fit(X, np.diag(d) )
psi = np.transpose(model.coef_)
elif cobra=='deprecated':
gtq = np.matmul(g.T, Q)
xtx_inv = np.linalg.pinv(
np.dot(X.T, X)
)
xtx_inv_xt = np.dot(
xtx_inv, X.T
)

#
psi = np.zeros((q, n))
#
psi = np.zeros((q, n))

for i in range(q):
for h in range(n):
psi[i, h] = n * np.sum([
(
xtx_inv_xt[i, k] * gtq[k, h] ** 2
) for k in range(n)
])
for i in range(q):
for h in range(n):
psi[i, h] = n * np.sum([
(
xtx_inv_xt[i, k] * gtq[k, h] ** 2
) for k in range(n)
])

return psi, Q, d, g
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ igraph
joblib
statsmodels
click
scikit-learn
2 changes: 1 addition & 1 deletion tests/test_cobra.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_cobra():
G_gt = pd.read_csv(G_gt_path, index_col=0)

# Call COBRA
psi, Q, D, G = cobra.cobra(X, expression)
psi, Q, D, G = cobra.cobra(X, expression, cobra='deprecated')

# Cast output to pandas
psi = pd.DataFrame(psi, index=psi_gt.index, columns=psi_gt.columns)
Expand Down