Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def select(self, CV=True, seed=0):
numpy2ri.activate()
rpy.r.assign('X', self.X.copy())
rpy.r.assign('Y', self.Y.copy())
rpy.r('X = as.matrix(X)')
rpy.r('Y = as.numeric(Y)')
rpy.r('set.seed(%d)' % seed)
rpy.r('cvG = cv.glmnet(X, Y, intercept=FALSE, standardize=FALSE)')
rpy.r("L1 = cvG[['lambda.min']]")
rpy.r("L2 = cvG[['lambda.1se']]")
if CV:
rpy.r("L = L1")
else:
rpy.r("L = 0.99 * L2")
rpy.r("G = glmnet(X, Y, intercept=FALSE, standardize=FALSE)")
n, p = self.X.shape
L = rpy.r('L')
"""
import numpy as np
from scipy.stats import truncnorm
from scipy.optimize import bisect
from scipy.interpolate import interp1d
from scipy.integrate import quad
from warnings import warn
from sklearn.isotonic import IsotonicRegression
# load rpy2 and initialize for numpy support
import rpy2.robjects as rpy
from rpy2.robjects import numpy2ri
numpy2ri.activate()
from mpmath import quad as mpquad, exp as mpexp, log as mplog, mp
mp.dps = 60
from .chisq import quadratic_bounds
DEBUG = False
def expected_norm_squared(initial, C, ndraw=1000, burnin=1000):
"""
Starting with a point in $C$, estimate
the expected value of $\|Y\|^2_2$ under
the distribution implied by $C$, as well
as the variance.
Parameters
from IPython.core import displaypub
from IPython.core.magic import (Magics,
magics_class,
line_cell_magic,
line_magic,
needs_local_scope)
from IPython.core.magic_arguments import (argument,
argument_group,
magic_arguments,
parse_argstring)
if numpy:
from rpy2.robjects import numpy2ri
template_converter += numpy2ri.converter
if pandas:
from rpy2.robjects import pandas2ri
template_converter += pandas2ri.converter
def CELL_DISPLAY_DEFAULT(res, args):
return ro.r.show(res)
class RInterpreterError(ri.embedded.RRuntimeError):
"""An error when running R code in a %%R magic cell."""
msg_prefix_template = ('Failed to parse and evaluate line %r.\n'
'R error message: %r')
rstdout_prefix = '\nR stdout:\n'
""" Regression or prediction methods from R
"""
import numpy as np
from rpy2.robjects.packages import importr
from rpy2.robjects import numpy2ri, pandas2ri
numpy2ri.activate()
pandas2ri.activate()
Rstats = importr('stats')
def CRAN_spline(x, y, w=None, **kwds):
""" Return a prediction function for a smoothing spline from R
Use `rpy2` package to fit a smoothing spline using "smooth.spline".
Args:
x (np.ndarray): independent variable
y (np.ndarray): dependent variable
w (np.ndarray): weights for each observation in `x`/`y`
Returns:
from typing import Optional
from rpy2.robjects import conversion, numpy2ri, pandas2ri, default_converter, SexpVector
from rpy2.robjects.conversion import overlay_converter
from . import scipy2ri
original_converter: Optional[conversion.Converter] = None
converter = conversion.Converter("original anndata conversion")
mat_converter = default_converter + numpy2ri.converter + scipy2ri.converter
# default_converter has SexpVector registered, so we need to overwrite it.
mat_converter.rpy2py.register(SexpVector, numpy2ri.rpy2py_sexp)
def full_converter() -> conversion.Converter:
pandas2ri.activate()
new_converter = conversion.Converter("anndata conversion", template=conversion.converter)
pandas2ri.deactivate()
overlay_converter(scipy2ri.converter, new_converter)
# overwrite the scipy2ri Sexp4 converter and add our others
overlay_converter(converter, new_converter)
return new_converter
import numpy as np
from scipy.stats import norm as normal_dbn
import regreg.api as rr
from selection.algorithms.debiased_lasso import pseudoinverse_debiasing_matrix
# load in the X matrix
import rpy2.robjects as rpy
from rpy2.robjects import numpy2ri
rpy.r('library(hdi); data(riboflavin); X = riboflavin$x')
numpy2ri.activate()
X_full = np.asarray(rpy.r('X'))[:,::40] # every 40th feature, about 100
numpy2ri.deactivate()
from selection.learning.utils import full_model_inference, liu_inference, pivot_plot
from selection.learning.core import split_sampler, keras_fit, repeat_selection, infer_set_target
from selection.learning.Rutils import lasso_glmnet, cv_glmnet_lam
from selection.learning.learners import mixture_learner
boot_design = False
def highdim_model_inference(X,
y,
truth,
selection_algorithm,
sampler,
lam_min,
dispersion,
success_params=(1, 1),
#!/bin/python
# Processing of CSV files with some R functionality.
# Ver 1.0.
# Oct. 2014, PA Taylor (UCT, AIMS).
import getopt, sys
import numpy as np
from rpy2.robjects import r
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
# allows input of np arrays into R functions.
rpy2.robjects.numpy2ri.activate()
grDevices = importr('grDevices') # can't make plot work right now...
# Available output format types for R_Factor Analysis plots, if
# desired
PARN_OUT_types = ['jpeg', 'pdf', 'png', 'tiff']
PARN_OUT_devs = [ grDevices.jpeg , grDevices.pdf ,
grDevices.png , grDevices.tiff ]
# ---------------------------------------------------------------------
# ---------------------------------------------------------------------
def CorMatCheck(Y, cvars):
MM = np.corrcoef(np.transpose(Y))
for i in range(len(MM)):
def init_rpy():
global _rpy_initialized
if _rpy_initialized:
return
_rpy_initialized = True
from rpy2 import robjects
from rpy2.robjects import numpy2ri
import os
path = os.path.dirname(__file__)
with open(path + "/mixedClustering.R", "r") as rfile:
code = ''.join(rfile.readlines())
robjects.r(code)
numpy2ri.activate()
**kwargs: :obj:`dict`
Additional keyword arguments to be passed to the DESeq function of DESeq2.
Returns
-------
:obj:`pandas.DataFrame`
Data frame with results, statistics for each feature.
"""
from tqdm import tqdm
from ngs_toolkit.utils import r2pandas_df, recarray2pandas_df
from rpy2.robjects import numpy2ri, pandas2ri, r
from rpy2.robjects.packages import importr
numpy2ri.activate()
pandas2ri.activate()
importr("DESeq2")
# order experiment and count matrices in same way
experiment_matrix = experiment_matrix.set_index("sample_name").loc[count_matrix.columns, :]
# save the matrices just in case
if save_inputs:
count_matrix.to_csv(os.path.join(output_dir, output_prefix + ".count_matrix.tsv"), sep="\t")
experiment_matrix.to_csv(
os.path.join(output_dir, output_prefix + ".experiment_matrix.tsv"), sep="\t"
)
comparison_table.to_csv(
os.path.join(output_dir, output_prefix + ".comparison_table.tsv"), sep="\t"
)
matrix : :class:`pandas.DataFrame`
DataFrame to normalize.
gc_content : :class:`pandas.Series`
Series with GC content of each feature in ``matrix``.
lengths : :class:`pandas.Series`
Series with length of each feature in ``matrix``.
Returns
----------
:class:`pandas.DataFrame`
Normalized DataFrame
"""
from rpy2.robjects import numpy2ri, pandas2ri, r
from rpy2.robjects.packages import importr
numpy2ri.activate()
pandas2ri.activate()
importr("cqn")
cqn_out = r.cqn(matrix, x=gc_content, lengths=lengths)
y_r = cqn_out[list(cqn_out.names).index("y")]
y = pd.DataFrame(np.array(y_r), index=matrix.index, columns=matrix.columns)
offset_r = cqn_out[list(cqn_out.names).index("offset")]
offset = pd.DataFrame(np.array(offset_r), index=matrix.index, columns=matrix.columns)
return y + offset