当前位置: 首页>>代码示例>>Python>>正文


Python robjects.FloatVector方法代码示例

本文整理汇总了Python中rpy2.robjects.FloatVector方法的典型用法代码示例。如果您正苦于以下问题:Python robjects.FloatVector方法的具体用法?Python robjects.FloatVector怎么用?Python robjects.FloatVector使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rpy2.robjects的用法示例。


在下文中一共展示了robjects.FloatVector方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sample_coM3

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def sample_coM3(invariants):
    """
    Calculates sample third order co-moment matrix
    Taps into the R package PerformanceAnalytics through rpy2

    :param invariants: sample data of market invariants
    :type invariants: pd.Dataframe
    :param frequency: time horizon of projection, default set ot 252 days
    :type frequency: int
    :return: sample skew dataframe
    """
    
    importr('PerformanceAnalytics')
    if not isinstance(invariants, pd.DataFrame):
        warnings.warn("invariants not a pd.Dataframe", RuntimeWarning)
        invariants = pd.DataFrame(invariants)
    p = invariants.shape[1]
    coskew_function = robjects.r('M3.MM')
    r_inv_vec = robjects.FloatVector(np.concatenate(invariants.values))
    r_invariants = robjects.r.matrix(r_inv_vec,nrow=p,ncol=p)
    r_M3 = coskew_function(r_invariants)
    
    return np.matrix(r_M3) 
开发者ID:VivekPa,项目名称:OptimalPortfolio,代码行数:25,代码来源:moment_est.py

示例2: sample_coM4

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def sample_coM4(invariants):
    """
    Calculates sample fourth order co-moment matrix
    Taps into the R package PerformanceAnalytics through rpy2

    :param invariants: sample data of market invariants
    :type invariants: pd.Dataframe
    :param frequency: time horizon of projection, default set ot 252 days
    :type frequency: int
    :return: sample skew dataframe
    """
    
    importr('PerformanceAnalytics')
    if not isinstance(invariants, pd.DataFrame):
        warnings.warn("invariants not a pd.Dataframe", RuntimeWarning)
        invariants = pd.DataFrame(invariants)
    p = invariants.shape[1]
    coskew_function = robjects.r('M4.MM')
    r_inv_vec = robjects.FloatVector(np.concatenate(invariants.values))
    r_invariants = robjects.r.matrix(r_inv_vec,nrow=p,ncol=p)
    r_M4 = coskew_function(r_invariants)
    
    return np.matrix(r_M4) 
开发者ID:VivekPa,项目名称:OptimalPortfolio,代码行数:25,代码来源:moment_est.py

示例3: test_pickle

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def test_pickle():
    tmp_file = tempfile.NamedTemporaryFile()
    robj = robjects.baseenv["pi"]
    pickle.dump(robj, tmp_file)
    tmp_file.flush()
    tmp_file.seek(0)
    robj_again = pickle.load(tmp_file)
    tmp_file.close()

    assert isinstance(robj, robjects.FloatVector)

    # Check that underlying R objects are identical.
    assert robjects.baseenv["identical"](robj,
                                         robj_again)[0]
    # Check the instance dict is also identical
    assert set(robj.__dict__.keys()) == set(robj_again.__dict__.keys()) 
开发者ID:rpy2,项目名称:rpy2,代码行数:18,代码来源:test_serialization.py

示例4: visualize_report

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def visualize_report(tenx_sample_infos, outpath):
    try:
        from rpy2 import robjects as ro
        from grocsvs import plotting
        
        
        ro.r.pdf(outpath)

        frag_lengths = [numpy.log10(sample_info["frag_length_info"]["sampled"]) for sample_info in tenx_sample_infos.values()]
        max_ = max(numpy.percentile(cur_frag_lengths, 99.5) for cur_frag_lengths in frag_lengths)

        plotting.ecdf(frag_lengths, tenx_sample_infos.keys(), xlim=[0, max_], main="Fragment length distribution",
            xlab="Fragment length (log10)", legendWhere="bottomright")

        bc_counts = dict((name, sample_info["good_bc_count"]) for name, sample_info in tenx_sample_infos.items())
        plotting.barPlot(bc_counts, main="Number of high-quality barcodes", ylim=[0, 1.1*max(bc_counts.values())])

        # oldpar = r.par(mfrow=[min(3, len(tenx_sample_infos)), 2])
        oldpar = ro.r.par(mfrow=[2,1])

        for name, tenx_sample_info in tenx_sample_infos.items():
            C_Rs = tenx_sample_info["coverage_of_fragments"]
            C_Rs = C_Rs["coverages"] / C_Rs["lengths"].astype(float)

            ro.r.hist(ro.FloatVector(C_Rs), breaks=50, xlab="Fragment coverage by short-reads (C_R)", main=name)
            ro.r.hist(ro.FloatVector(tenx_sample_info["physical_depths"]), breaks=100, xlab="Coverage by long fragments (C_F)",
                main=name)

        ro.r.par(oldpar)

        ro.r["dev.off"]()
    except:
        with open(outpath, "w") as f:
            f.write("[the visual report requires rpy2 to be correctly installed]") 
开发者ID:grocsvs,项目名称:grocsvs,代码行数:36,代码来源:qc.py

示例5: barPlot

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def barPlot(dict_, keysInOrder=None, printCounts=True, ylim=None, *args, **kwdargs):
    """ Plot a bar plot

    Args:
        dict_: a dictionary of name -> value, where value is the height of the bar
            use a collections.OrderedDict() to easily convey the order of the groups
        keysInOrder: an optional ordering of the keys in dict_ (alternate option to using collections.OrderedDict)
        printCounts: option to print the counts on top of each bar

    additional kwdargs are passed directly to r.barplot()
    """

    if not keysInOrder:
        keysInOrder = dict_.keys()
    
    heights = ro.FloatVector([dict_[key] for key in keysInOrder])

    kwdargs["names.arg"] = ro.StrVector(keysInOrder)

    if ylim is None:
        if printCounts:
            ylim = [min(heights), max(heights)*1.1]
        else:
            ylim = [min(heights), max(heights)]

    x = r.barplot(heights, ylim=ro.FloatVector(ylim), *args, **kwdargs)

    if printCounts:
        heightsStrings = ["{:.2g}".format(height) for height in heights]
        r.text(x, ro.FloatVector(heights), ro.StrVector(heightsStrings), pos=3)
    return x 
开发者ID:grocsvs,项目名称:grocsvs,代码行数:33,代码来源:plotting.py

示例6: histogram

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def histogram(self, vline=None, params=None):
        '''
        plot histogram with vline at x=vline
        '''
        self.params['x'] = ro.FloatVector(self.data)
        self.params['labels'] = False

        if params is not None:
            self.params.update(params)

        graphics().hist(**self.params)

        if vline is not None:
            lineParams = {'v': vline, 'col': 'red'}
            graphics().abline(**lineParams) 
开发者ID:cstoeckert,项目名称:iterativeWGCNA,代码行数:17,代码来源:manager.py

示例7: r_bats

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def r_bats(self, y, components):
        components = components.copy()
        if 'seasonal_periods' in components:
            components['seasonal_periods'] = ro.IntVector(components['seasonal_periods'])
        importr('forecast')
        r_bats_func = ro.r['bats']
        r_forecast = ro.r['forecast']
        r_y = ro.FloatVector(list(y))
        r_model = r_bats_func(r_y, **components)
        summary = r_forecast(r_model)
        # predictions = np.array(summary.rx('fitted')).flatten()
        return summary, r_model 
开发者ID:intive-DataScience,项目名称:tbats,代码行数:14,代码来源:RComparisonBase.py

示例8: r_tbats

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def r_tbats(self, y, components):
        components = components.copy()
        if 'seasonal_periods' in components:
            components['seasonal_periods'] = ro.IntVector(components['seasonal_periods'])
        importr('forecast')
        r_bats_func = ro.r['tbats']
        r_forecast = ro.r['forecast']
        r_y = ro.FloatVector(list(y))
        r_model = r_bats_func(r_y, **components)
        summary = r_forecast(r_model)
        # predictions = np.array(summary.rx('fitted')).flatten()
        return summary, r_model 
开发者ID:intive-DataScience,项目名称:tbats,代码行数:14,代码来源:RComparisonBase.py

示例9: fit_and_evaluate

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def fit_and_evaluate(x,z,t,y,df):
    '''
    Fit and evaluate non-parametric regression using  Darolles, Fan, Florens and Renault (2011)

    Implemented in the `np` package in R.

    See [the np package documation](https://cran.r-project.org/web/packages/np/np.pdf) for details.
    '''
    npr=importr('np')
    y_R = robjects.FloatVector(list(y.flatten()))
    (x_eval, t_eval), y_true = test_points(df, 10000)
    mod = npr.npregiv(y_R, t, z, x=x, zeval=t_eval, xeval=x_eval,
                    method="Tikhonov", p=0, optim_method ="BFGS")
    return ((y_true - to_array(mod.rx2('phi.eval')))**2).mean() 
开发者ID:jhartford,项目名称:DeepIV,代码行数:16,代码来源:nonpar.py

示例10: nullDistPermutations

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def nullDistPermutations(tfbs_genes, matched_genes, nPerms=1000):
    '''
    Randomly generate a null distribution of genes from the background
    set, match for pCpG and total number of genes.  Calculate
    enrichment of these genes for the given TFBS.  Permuate nPerm times.
    Return a median enrichment and p-value from the empirical
    cumulative frequency distribution.
    '''

    null_dist = []

    for i in range(0, nPerms):
        null_genes = genNullGeneSet(matched_genes)
        null_counts = countTFBSEnrichment(tfbs_genes, null_genes)
        null_enrich = null_counts[0] / float(null_counts[1])
        null_dist.append(null_enrich)

    # null_dist = robjects.FloatVector([float(x) for x in null_dist])
    # null_dist_r = robjects.FloatVector([float(x) for x in null_dist])

    # null_ecdf = ecdf(null_dist)
    out_dict = {}
    out_dict['null'] = null_dist
    out_dict['median'] = np.median(null_enrich)

    return out_dict 
开发者ID:CGATOxford,项目名称:CGATPipelines,代码行数:28,代码来源:PipelineTransfacMatch.py

示例11: test_nareal

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def test_nareal():
    vec = robjects.FloatVector((1.0, 2.0, 3.0))
    vec[0] = robjects.NA_Real
    assert robjects.baseenv['is.na'](vec)[0] is True 
开发者ID:rpy2,项目名称:rpy2,代码行数:6,代码来源:test_vector.py

示例12: test_float_repr

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def test_float_repr():
    vec = robjects.vectors.FloatVector((1,2,3))
    r = repr(vec).split('\n')
    assert r[-1].startswith('[')
    assert r[-1].endswith(']')
    assert len(r[-1].split(',')) == 3 
开发者ID:rpy2,项目名称:rpy2,代码行数:8,代码来源:test_vector.py

示例13: test_sequence_to_vector

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def test_sequence_to_vector():
    res = robjects.sequence_to_vector((1, 2, 3))
    assert isinstance(res, robjects.IntVector)

    res = robjects.sequence_to_vector((1, 2, 3.0))
    assert isinstance(res, robjects.FloatVector)

    res = robjects.sequence_to_vector(('ab', 'cd', 'ef'))
    assert isinstance(res, robjects.StrVector)

    with pytest.raises(ValueError):
        robjects.sequence_to_vector(list()) 
开发者ID:rpy2,项目名称:rpy2,代码行数:14,代码来源:test_vector.py

示例14: test_sample_probabilities

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def test_sample_probabilities():
    vec = robjects.IntVector(range(100))
    spl = vec.sample(10, probabilities=robjects.FloatVector([.01] * 100))
    assert len(spl) == 10 
开发者ID:rpy2,项目名称:rpy2,代码行数:6,代码来源:test_vector.py

示例15: setup_func

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import FloatVector [as 别名]
def setup_func(kind):
#-- setup_sum-begin
    n = 20000
    x_list = [random.random() for i in range(n)]
    module = None
    if kind == "array.array":
        import array as module
        res = module.array('f', x_list)
    elif kind == "numpy.array":
        import numpy as module
        res = module.array(x_list, 'f')
    elif kind == "FloatVector":
        import rpy2.robjects as module
        res = module.FloatVector(x_list)
    elif kind == "FloatSexpVector":
        import rpy2.rinterface as module
        module.initr()
        res = module.FloatSexpVector(x_list)
    elif kind == "FloatSexpVector-memoryview-array":
        import rpy2.rinterface as module
        module.initr()
        tmp = module.FloatSexpVector(x_list)
        mv = tmp.memoryview()
        res = array.array(mv.format, mv)
    elif kind == "list":
        res = x_list
    elif kind == "R":
        import rpy2.robjects as module
        res = module.rinterface.FloatSexpVector(x_list)
        module.globalenv['x'] = res
        res = None
#-- setup_sum-end
    else:
        raise ValueError("Unknown kind '%s'" %kind)
    return (res, module) 
开发者ID:rpy2,项目名称:rpy2,代码行数:37,代码来源:benchmarks.py


注:本文中的rpy2.robjects.FloatVector方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。