コード例 #1
0
    def test_posixct_in_dataframe_to_pandas(self):
        tzone = robjects.vectors.get_timezone()
        dt = [datetime(1960, 5, 2),
              datetime(1970, 6, 3), 
              datetime(2012, 7, 1)]
        dt = [x.replace(tzinfo=tzone) for x in dt]
        # fix the time
        ts = [x.timestamp() for x in dt]
        # Create an R data.frame with a posixct_vector.
        r_dataf = robjects.vectors.DataFrame({
            'mydate': robjects.baseenv['as.POSIXct'](
                rinterface.FloatSexpVector(ts),
                origin=rinterface.StrSexpVector(('1970-01-01',))
            )})

        # Convert R POSIXct vector to pandas-compatible vector
        with localconverter(default_converter + rpyp.converter):
            py_dataf = robjects.conversion.rpy2py(r_dataf)
        assert pandas.core.dtypes.common.is_datetime64_any_dtype(py_dataf['mydate'])
コード例 #2
0
    def __value_py_to_r(value, ri):
        """Returns the R equivalent of a python value"""
        val = value.value
        if not isinstance(val, (list, tuple)):
            # Is this an iterable ?
            if hasattr(val,
                       '__iter__') and not isinstance(val, (str, unicode)):
                val = [v for v in val]
            else:
                # In R scalar values are vectors with one element
                # So here we put the scalar value into a list
                val = [val]

        na_value = None
        if value.type == 'bool':
            na_value = ri.NALogicalType()
        elif value.type == 'byte':
            na_value = ri.NAIntegerType(
            )  # I guess that's correct ? That should probably be tested though
        elif value.type == 'float':
            na_value = ri.NARealType()
        elif value.type == 'int':
            na_value = ri.NAIntegerType()
        elif value.type == 'string':
            na_value = ri.NACharacterType()

        # Scan the elements to replace Nones by NA
        val = [(na_value if v is None else v) for v in val]

        if value.type == 'bool':
            return ri.BoolSexpVector(val)
        if value.type == 'byte':
            return ri.ByteSexpVector(val)
        if value.type == 'float':
            return ri.FloatSexpVector(val)
        if value.type == 'int':
            return ri.IntSexpVector(val)
        if value.type == 'string':
            return ri.StrSexpVector(val)

        raise PredictionValueTypeException(value.type)
コード例 #3
0
    def test_timeR2Pandas(self):
        tzone = rpyp.get_timezone()
        dt = [datetime(1960, 5, 2),
              datetime(1970, 6, 3), 
              datetime(2012, 7, 1)]
        dt = [x.replace(tzinfo=tzone) for x in dt]
        # fix the time
        ts = [x.timestamp() for x in dt]
        # Create an R POSIXct vector.
        r_time = robjects.baseenv['as.POSIXct'](
            rinterface.FloatSexpVector(ts),
            origin=rinterface.StrSexpVector(('1970-01-01',))
        )

        # Convert R POSIXct vector to pandas-compatible vector
        with localconverter(default_converter + rpyp.converter) as cv:
            py_time = robjects.conversion.rpy2py(r_time)

        # Check that the round trip did not introduce changes
        for expected, obtained in zip(dt, py_time):
            assert expected == obtained.to_pydatetime()
コード例 #4
0
def formatForR(params):
    kwargs = {}
    for key, value in params.iteritems():
        if not isinstance(value, list):
            value = [value]

        t = commonType(value)

        if t == float:
            v = R.FloatSexpVector(value)
        elif t == int:
            v = R.IntSexpVector(value)
        elif t == bool:
            v = R.BoolSexpVector(value)
        elif t == str:
            v = R.StrSexpVector(value)
        else:
            v = None

        kwargs.update([(key, v)])
    return kwargs
コード例 #5
0
def test_init_From_seq_invalid_elt():
    seq = (ri.FloatSexpVector([1.0]), lambda x: x,
           ri.StrSexpVector(['foo', 'bar']))
    with pytest.raises(Exception):
        ri.ListSexpVector(seq)
コード例 #6
0
def test_init_from_seq():
    seq = (1.0, 2.0, 3.0)
    v = ri.FloatSexpVector(seq)
    assert len(v) == 3
    for x, y in zip(seq, v):
        assert x == y
コード例 #7
0
def test_getslice():
    vec = ri.FloatSexpVector([1.0, 2.0, 3.0])
    vec = vec[0:2]
    assert len(vec) == 2
    assert vec[0] == 1.0
    assert vec[1] == 2.0
コード例 #8
0
 def testInitFromIter(self):
     it = range(10)
     v = ri.FloatSexpVector(it)
     self.assertEqual(10, len(v))
     for x,y in zip(range(10), v):
         self.assertEqual(x, y)
コード例 #9
0
def test_init_From_seq_invalid_float():
    seq = (1.0, 'b', 3.0)
    with pytest.raises(ValueError):
        ri.FloatSexpVector(seq)
コード例 #10
0
def test_init_from_iter():
    it = range(3)
    v = ri.FloatSexpVector(it)
    assert len(v) == 3
    for x, y in zip(range(3), v):
        assert x == y
コード例 #11
0
ファイル: test_na.py プロジェクト: Trixter9994/lazero
def test_NAReal_in_vector():
    na_float = ri.NA_Real
    x = ri.FloatSexpVector((1.1, na_float, 2.2))
    assert math.isnan(x[1])
    assert x[0] == 1.1
    assert x[2] == 2.2
コード例 #12
0
def npfloat_py2rpy(obj):
    return rinterface.FloatSexpVector([obj, ])
コード例 #13
0
ファイル: varwald.py プロジェクト: snazzyservice/pyrace
    # test LBA pdf

    acc = VarWaldAccumulator(2, 0.1, 0, 1)
    print acc
    nsamples = 10000

    x = np.linspace(0, 3, nsamples)
    pl.plot(x, acc.pdf(x))
    pl.xlim(0, 3)

    import rpy2.robjects as robjects

    r = robjects.r
    r['source']('./test/misc/UWA.R')

    rx = rinterface.FloatSexpVector(x - .1)

    yr = r['digt'](rx, k=2 - .5, l=0, a=.5)
    y = np.array(yr)
    pl.plot(x, y, color='red')
    assert np.any(y - acc.pdf(x) < 1e-10)
    #pl.plot( x, acc.cdf(x))

    #y=acc.sample(10000, upper_limit=3)
    #a=pl.hist(y, 100, normed=True)
    #print np.sum(a[1])

    #print "PDF Sum: ", (np.sum(acc.pdf(x))/nsamples*10)
    #print "PDF Integral: ",scipy.integrate.quad(acc.pdf, 0, np.infty)[0]
    #print "CDF(0,1000) :", acc.cdf(np.array([0,1000]))
    pl.show()
コード例 #14
0
 def _toVector(arg):
     return r.FloatSexpVector(arg)
コード例 #15
0
 def testNARealInVector(self):
     na_float = ri.NARealType()
     x = ri.FloatSexpVector((1.1, na_float, 2.2))
     self.assertTrue(x[1] is na_float)
     self.assertEqual(1.1, x[0])
     self.assertEqual(2.2, x[2])
コード例 #16
0
def test_getitem():
    vec = ri.FloatSexpVector([1.0, 2.0, 3.0])
    assert vec[1] == 2.0
コード例 #17
0
 def testInitFromSeq(self):
     seq = (1.0, 2.0, 3.0)
     v = ri.FloatSexpVector(seq)
     self.assertEqual(3, len(v))
     for x,y in zip(seq, v):
         self.assertEqual(x, y)
コード例 #18
0
def test_setitem():
    vec = ri.FloatSexpVector([1.0, 2.0, 3.0])
    vec[1] = 100.0
    assert vec[1] == 100.0
コード例 #19
0
 def testGetSliceFloat(self):
     vec = ri.FloatSexpVector([1.0,2.0,3.0])
     vec = vec[0:2]
     self.assertEqual(2, len(vec))
     self.assertEqual(1.0, vec[0])
     self.assertEqual(2.0, vec[1])
コード例 #20
0
ファイル: vectors.py プロジェクト: xchechi123x/Cyclopath
 def __init__(self, obj):
     obj = rinterface.FloatSexpVector(obj)
     super(FloatVector, self).__init__(obj)