stephenslab / ebnm

R package to fit Empirical Bayes Normal Means model.
https://stephenslab.github.io/ebnm/
12 stars 9 forks source link

error with normal_scale_mixture when calling ebnm from python #80

Closed zihao12 closed 1 year ago

zihao12 commented 2 years ago

I am calling ebnm through python. It works when I use "point_normal", but gives an error when using "normal_scale_mixture".

Code is as follows

import numpy as np
import scipy
import pickle
import rpy2
import rpy2.interactive as r
import rpy2.interactive.packages
from rpy2.robjects import numpy2ri
import pdb
ebnm = r.packages.importr("ebnm")
prior_family = "normal_scale_mixture" ## works fine when using point_normal
with open('error_gv.pkl', 'rb') as f:
    data = pickle.load(f)
g = data['g']
v = data['v']
s = np.sqrt(v).copy()
x = g.copy()
numpy2ri.activate()
fit = ebnm.ebnm(x = x, s= s, prior_family = prior_family, mode = "estimate")
g_ = np.asarray(fit.rx2('posterior'))
numpy2ri.deactivate()
g_ = g_.view((float, len(g_.dtype.names)))[:, 0]
print(g_)

The error message is

rpy2.rinterface_lib.embedded.RRuntimeError: Error in (x - mode)^2/sigma2 : non-conformable arrays
pcarbo commented 2 years ago

Here is the example in R rerproducing the error:

library(ebnm)
load("zihao.RData")
fit = ebnm(x = x,s = s,prior_family = "normal_scale_mixture")
# Error in (x - mode)^2/sigma2 : non-conformable arrays

zihao.RData.gz

willwerscheid commented 2 years ago

here x and s are of class array. The code works if you instead call fit = ebnm(x = as.numeric(x),s = as.numeric(s),prior_family = "normal_scale_mixture").

pcarbo commented 2 years ago

This worked for me (after running the above code):

import rpy2.robjects
y = robjects.vectors.FloatVector(x)
w = robjects.vectors.FloatVector(s)
fit = ebnm.ebnm(x = y, s=w, prior_family = prior_family, mode = "estimate")

So it looks like some care is needed in converting python data structures to R (and presumably vice versa).