How to use the rpy2.robjects.packages.importr function in rpy2

To help you get started, we’ve selected a few rpy2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github marcus1487 / nanoraw / nanoraw / plot_commands.py View on Github external
def kmer_dist_main(args):
    global VERBOSE
    VERBOSE = not args.quiet
    nh.VERBOSE = VERBOSE

    try:
        ggplot = importr("ggplot2")
    except:
        sys.stderr.write(GG_LOAD_ERROR)
        sys.exit()

    files = nh.get_files_list(args.fast5_basedirs)
    plot_kmer_dist(
        files, args.corrected_group, args.basecall_subgroups,
        args.read_mean, args.upstream_bases, args.downstream_bases,
        args.num_kmer_threshold, args.num_reads, args.pdf_filename,
        args.r_data_filename, args.dont_plot)

    return
github ZhengXia / dapars / src / DaPars_main.py View on Github external
#print P_val
                #print ratio_val
            else:
                fields[-1] = 'NA'
            
            
            result_dict[fields[0]] = fields
                    
        else:
            first_line = line.strip('\n').split('\t')      
            
        num_line += 1
    
    
    ##Filtering
    stats = importr('stats')
    All_p_adjust = stats.p_adjust(FloatVector(All_P_values), method = 'BH')
    first_line.insert(-1,'Group_A_Mean_PDUI')
    first_line.insert(-1,'Group_B_Mean_PDUI')
    first_line.extend(['P_val','adjusted.P_val','Pass_Filter'])
    output_write.writelines('\t'.join(first_line)+'\n')
    for curr_event_id in result_dict:
        mean_PDUI_group1 = 'NA'
        mean_PDUI_group2 = 'NA'
        curr_P_val = 'NA'
        curr_FDR_val = 'NA'
        Pass_filter = 'N'
        curr_fields = result_dict[curr_event_id]
        if curr_event_id in Selected_events_id:
            sel_ind = Selected_events_id.index(curr_event_id)
            curr_P_val = str(All_P_values[sel_ind])
            curr_FDR_val = str(All_p_adjust[sel_ind])
github openworm / owmeta / PyOpenWorm / data_trans / sci_rna_seq.py View on Github external
def translate(self, ds):
        url = ds.data_url().pop()
        base = importr('base')
        utils = importr('utils')
        utils.download_file(url, destfile="data_source.RData")
        base.load("data_source.RData")
        cds = R('cds')
        print(cds)
github Quetzal-RDF / quetzal / com.ibm.research.quetzal.core / pythonR / TestCDK.py View on Github external
def __init__(self):
        rxnsim = rpackages.importr('RxnSim')
        gosemsim = rpackages.importr('GOSemSim')
github ucbrise / clipper / clipper_admin / clipper_manager.py View on Github external
model_data :
            The trained model to add to Clipper.The type has to be rpy2.robjects.vectors.ListVector,
            this is how python's rpy2 encapsulates any given R model.This model will be loaded
            into the Clipper model container and provided as an argument to the
            predict function each time it is called.
        labels : list of str, optional
            A set of strings annotating the model
        num_containers : int, optional
            The number of replicas of the model to create. More replicas can be
            created later as well. Defaults to 1.
        """

        # importing some R specific dependencies
        import rpy2.robjects as ro
        from rpy2.robjects.packages import importr
        base = importr('base')

        input_type = "strings"
        container_name = "clipper/r_python_container:{}".format(code_version)

        with hide("warnings", "output", "running"):
            fname = name.replace("/", "_")
            rds_path = '/tmp/%s/%s.rds' % (fname, fname)
            model_data_path = "/tmp/%s" % fname
            try:
                os.mkdir(model_data_path)
            except OSError:
                pass
            base.saveRDS(model_data, rds_path)

            vol = "{model_repo}/{name}/{version}".format(
                model_repo=MODEL_REPO, name=name, version=version)
github anbrooks / juncBASE / compareSampleSets.py View on Github external
# All rights reserved.

"""Will do test to compare two sets of groups in the data.

   Input will be an output file from createAS_CountTables.py
"""

import sys
import optparse 
import pdb
import os
import random

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')

from helperFunctions import updateDictOfLists

#import numpy as np
#import matplotlib.pyplot as plt
#import matplotlib.mlab as mlab

r = robjects.r
# Suppresses warnings
robjects.r["options"](warn=-1)
#############
# CONSTANTS #
#############
NA = "NA"
DEF_SIGN_CUTOFF = 0.05
DEF_THRESH = 10
github ReliaQualAssociates / ramstk / rtk / _calculations_ / survival.py View on Github external
def theoretical_distribution(_data_, _distr_, _para_):

    Rbase = importr('base')

# Create the R density and probabilty distribution names.
    ddistname = R.paste('d', _distr_, sep='')
    pdistname = R.paste('p', _distr_, sep='')

# Calculate the minimum and maximum values for x.
    xminleft = min([i[0] for i in _data_ if i[0] != 'NA'])
    xminright = min([i[1] for i in _data_ if i[1] != 'NA'])
    xmin = min(xminleft, xminright)

    xmaxleft = max([i[0] for i in _data_ if i[0] != 'NA'])
    xmaxright = max([i[1] for i in _data_ if i[1] != 'NA'])
    xmax = max(xmaxleft, xmaxright)

    xrange = xmax - xmin
    xmin = xmin - 0.3 * xrange
github jcreinhold / intensity-normalization / intensity_normalization / utilities / robex.py View on Github external
vol. 30, no. 9, pp. 16171634, 2011.

Author: Jacob Reinhold (jacob.reinhold@jhu.edu)

Created on: May 21, 2018
"""

import os
import warnings

import ants
from rpy2.robjects.packages import importr

from intensity_normalization.utilities.io import split_filename

ROBEX = importr('robex')


def robex(img, out_mask, skull_stripped=False):
    """
    perform skull-stripping on the registered image using the
    ROBEX algorithm

    Args:
        img (str): path to image to skull strip
        out_mask (str): path to output mask file
        skull_stripped (bool): return the mask
            AND the skull-stripped image [default = False]

    Returns:
        mask (ants.ANTsImage): mask/skull-stripped image
    """
github Joker-Jerome / UTMOST / joint_GBJ.py View on Github external
# covariance dir 
    cov_dir = args.cov_dir
    
    # output dir 
    out_dir = args.output_dir
     
    # read list of genes
    gene_info = pd.read_table(info_file)
    
    # output name
    output_name = args.output_name 
    
    # r interface
    r_requirement()
    rpy2.robjects.numpy2ri.activate()
    importr("GBJ")
    
    P = nend - nstart + 1
    gene_ensg = gene_info["gene_ensg"].copy()
    gene_id = gene_info["gene_ensg"].copy()
    gene_name = gene_info["gene_ensg"].copy()
    
    # read z-score file
    logging.info("Read in z-score files")
    
    # directory of z-score
    os.chdir(single_mask_dir) 
    
    # search for files ending with .csv
    fi = []
    
    for file in sorted(os.listdir(single_mask_dir)):
github pyrevo / ClusterScan / clusterscan.py View on Github external
def rpy2_plotter(anno, clusters, name):
    """Plot genes distribution in clusters using ggplot2 from R."""
    pandas2ri.activate()
    grdevices = importr('grDevices')
    rprint = robjects.globalenv.get("print")

    anno = anno.sort_values(by="n_ft", ascending=False)
    anno = anno.head(n=10)
    category = anno["category"].tolist()
    clusters = clusters[clusters["category"].isin(category)]
    clusters = pandas2ri.py2ri(clusters)

    pp = ggplot2.ggplot(clusters) + ggplot2.aes_string(x="n_features") + ggplot2.geom_histogram(binwidth=1) + ggplot2.facet_wrap(robjects.Formula("~category"), ncol=5) + ggplot2.labs(x="Number of Features", y="Number of Clusters", title="Clusters distribution")

    grdevices.pdf(file=name, width=11.692, height=8.267)
    rprint(pp)
    grdevices.dev_off()