예제 #1
0
def test_2d_arrays_created_in_python():
    """
    Check that transferring various arrays to R preserves columns, rows,
    and shape.
    """
    bools = [True, False, True, True]
    strings = ['abc', 'def', 'ghi', 'jkl']
    arrays = [
        # next is same as: numpy.array([[1,2,3], [4,5,6]])
        numpy.arange(6).reshape((2, 3), order='C'),
        # next is same as: numpy.array([[1,3,5], [2,4,6]])
        numpy.arange(6).reshape((2, 3), order='F'),
        # next is same as: numpy.array([[True, False], [True, True]])
        numpy.array(bools).reshape((2, 2), order='C'),
        # next is same as: numpy.array([[True, True], [False, True]])
        numpy.array(bools).reshape((2, 2), order='F'),
        numpy.array(strings).reshape((2, 2), order='C'),
        numpy.array(strings).reshape((2, 2), order='F'),
    ]

    for arr in arrays:
        res = conn.r.ident(arr)
        assert res.shape == arr.shape
        assert compareArrays(res, arr)

        # assign array within R namespace and check some cols and rows:
        conn.r.arr = arr
        # check that 2nd row (last row) is equal:
        assert compareArrays(arr[1], conn.r('arr[2,]'))
        # check that 2nd column (middle col) is equal:
        assert compareArrays(arr[:, 1], conn.r('arr[,2]'))
예제 #2
0
def test_2d_arrays_created_in_python():
    """
    Check that transferring various arrays to R preserves columns, rows,
    and shape.
    """
    bools = [True, False, True, True]
    strings = ['abc', 'def', 'ghi', 'jkl']
    arrays = [
        # next is same as: numpy.array([[1,2,3], [4,5,6]])
        numpy.arange(6).reshape((2, 3), order='C'),
        # next is same as: numpy.array([[1,3,5], [2,4,6]])
        numpy.arange(6).reshape((2, 3), order='F'),
        # next is same as: numpy.array([[True, False], [True, True]])
        numpy.array(bools).reshape((2, 2), order='C'),
        # next is same as: numpy.array([[True, True], [False, True]])
        numpy.array(bools).reshape((2, 2), order='F'),
        numpy.array(strings).reshape((2, 2), order='C'),
        numpy.array(strings).reshape((2, 2), order='F'),
    ]

    for arr in arrays:
        res = conn.r.ident(arr)
        assert res.shape == arr.shape
        assert compareArrays(res, arr)

        # assign array within R namespace and check some cols and rows:
        conn.r.arr = arr
        # check that 2nd row (last row) is equal:
        assert compareArrays(arr[1], conn.r('arr[2,]'))
        # check that 2nd column (middle col) is equal:
        assert compareArrays(arr[:, 1], conn.r('arr[,2]'))
예제 #3
0
def test_eval_sequence():
    # first string evaluate of R expression:
    res = conn.r('seq(1, 5)')
    assert compareArrays(res, numpy.array(range(1, 6)))
    assert res.dtype == numpy.int32

    # now make Python-style call to the R function:
    assert compareArrays(conn.r.seq(1, 5), numpy.array(range(1, 6)))
예제 #4
0
def test_eval_sequence():
    # first string evaluate of R expression:
    res = conn.r('seq(1, 5)')
    assert compareArrays(res, numpy.array(range(1, 6)))
    assert res.dtype == numpy.int32

    # now make Python-style call to the R function:
    assert compareArrays(conn.r.seq(1, 5), numpy.array(range(1, 6)))
예제 #5
0
def test_eval_bool_arrays():
    """Test boolean arrays"""
    res = conn.r('TRUE', atomicArray=True)
    assert compareArrays(res, numpy.array([True]))
    assert res.dtype == numpy.bool
    assert compareArrays(conn.r('c(TRUE, FALSE)'), numpy.array([True, False]))

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([True, False, False])),
                         numpy.array([True, False, False]))
예제 #6
0
def test_eval_string_arrays():
    """Test for string arrays"""
    assert compareArrays(conn.r("'abc'", atomicArray=True),
                         numpy.array(['abc']))
    assert compareArrays(conn.r("c('abc', 'def')"), numpy.array(['abc',
                                                                 'def']))

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array(['abc', 'def'])),
                         numpy.array(['abc', 'def']))
예제 #7
0
def test_eval_polyroot():
    # first string evaluate of R expression:
    res = conn.r('polyroot(c(-39.141,151.469,401.045))')
    exp_res = numpy.array(
        [0.1762039 + 1.26217745e-29j, -0.5538897 - 1.26217745e-29j])
    assert compareArrays(res, exp_res)

    # now make Python-style call to the R function:
    assert compareArrays(conn.r.polyroot(conn.r.c(-39.141, 151.469, 401.045)),
                         exp_res)
예제 #8
0
def test_eval_polyroot():
    # first string evaluate of R expression:
    res = conn.r('polyroot(c(-39.141,151.469,401.045))')
    exp_res = numpy.array([0.1762039 + 1.26217745e-29j,
                           -0.5538897 - 1.26217745e-29j])
    assert compareArrays(res, exp_res)

    # now make Python-style call to the R function:
    assert compareArrays(conn.r.polyroot(conn.r.c(-39.141, 151.469, 401.045)),
                         exp_res)
예제 #9
0
def test_eval_string_arrays():
    """Test for string arrays"""
    assert compareArrays(conn.r("'abc'", atomicArray=True),
                         numpy.array(['abc']))
    assert compareArrays(conn.r("c('abc', 'def')"),
                         numpy.array(['abc', 'def']))

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array(['abc', 'def'])),
                         numpy.array(['abc', 'def']))
예제 #10
0
def test_eval_bool_arrays():
    """Test boolean arrays"""
    res = conn.r('TRUE', atomicArray=True)
    assert compareArrays(res, numpy.array([True]))
    assert res.dtype == numpy.bool
    assert compareArrays(conn.r('c(TRUE, FALSE)'), numpy.array([True, False]))

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([True, False, False])),
                         numpy.array([True, False, False]))
예제 #11
0
def test_eval_complex_arrays():
    """Test complex number arrays"""
    res = conn.r("complex(real = 5.5, imaginary = 6.6)", atomicArray=True)
    assert compareArrays(res, numpy.array([(5.5 + 6.6j)]))
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.complex

    # test via call to ident function with single argument:
    arr = numpy.array([(5.5 + 6.6j), (-3.0 - 6j)])
    assert compareArrays(conn.r.ident(arr), arr)
예제 #12
0
def test_eval_complex_arrays():
    """Test complex number arrays"""
    res = conn.r("complex(real = 5.5, imaginary = 6.6)", atomicArray=True)
    assert compareArrays(res, numpy.array([(5.5+6.6j)]))
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.complex

    # test via call to ident function with single argument:
    arr = numpy.array([(5.5+6.6j), (-3.0-6j)])
    assert compareArrays(conn.r.ident(arr), arr)
예제 #13
0
def test_eval_float_arrays():
    """Test float arrays"""
    assert compareArrays(conn.r("266.5", atomicArray=True),
                         numpy.array([266.5]))
    assert compareArrays(conn.r("c(55.2, -35.7)"), numpy.array([55.2, -35.7]))
    res = conn.r("c(55.5, -35.5)")
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.float

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([1.7, 5.6])),
                         numpy.array([1.7, 5.6]))
예제 #14
0
def test_eval_float_arrays():
    """Test float arrays"""
    assert compareArrays(conn.r("266.5", atomicArray=True),
                         numpy.array([266.5]))
    assert compareArrays(conn.r("c(55.2, -35.7)"), numpy.array([55.2, -35.7]))
    res = conn.r("c(55.5, -35.5)")
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.float

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([1.7, 5.6])),
                         numpy.array([1.7, 5.6]))
예제 #15
0
def test_eval_integer_arrays():
    """
    Test integer arrays. The result from R is actually always a numpy
    float array
    """
    assert compareArrays(conn.r("266", atomicArray=True), numpy.array([266]))
    assert compareArrays(conn.r("c(55, -35)"), numpy.array([55.0, -35.0]))
    res = conn.r("c(55, -35)")
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.float

    #### Create real integer arrays in R:
    res = conn.r('as.integer(c(1, 5))')
    assert compareArrays(res, numpy.array([1, 5]))
    assert res.dtype in (numpy.int, numpy.int32)

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([1, 5])),
                         numpy.array([1, 5]))
예제 #16
0
def test_eval_integer_arrays():
    """
    Test integer arrays. The result from R is actually always a numpy
    float array
    """
    assert compareArrays(conn.r("266", atomicArray=True), numpy.array([266]))
    assert compareArrays(conn.r("c(55, -35)"), numpy.array([55.0, -35.0]))
    res = conn.r("c(55, -35)")
    assert isinstance(res, numpy.ndarray)
    assert res.dtype == numpy.float

    #### Create real integer arrays in R:
    res = conn.r('as.integer(c(1, 5))')
    assert compareArrays(res, numpy.array([1, 5]))
    assert res.dtype in (numpy.int, numpy.int32)

    # test via call to ident function with single argument:
    assert compareArrays(conn.r.ident(numpy.array([1, 5])), numpy.array([1,
                                                                         5]))
예제 #17
0
def test_2d_numeric_array_created_in_R():
    """
    Create an array in R, transfer it to python, and check that columns,
    rows, and shape are preserved.
    Note: Arrays in R are always in Fortran order, i.e. first index moves
    fastest.

    The array in R looks like:
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    """
    arr = conn.r('arr = array(1:6, dim=c(2, 3))')
    assert compareArrays(conn.r.arr, arr)

    # check that 2nd row (last row) is equal:
    assert len(arr[1]) == len(conn.r('arr[2,]')) == 3
    assert compareArrays(arr[1], conn.r('arr[2,]'))

    # check that 2nd column (middle col) is equal:
    assert len(arr[:, 1]) == len(conn.r('arr[,2]')) == 2
    assert compareArrays(arr[:, 1], conn.r('arr[,2]'))
예제 #18
0
def test_2d_numeric_array_created_in_R():
    """
    Create an array in R, transfer it to python, and check that columns,
    rows, and shape are preserved.
    Note: Arrays in R are always in Fortran order, i.e. first index moves
    fastest.

    The array in R looks like:
         [,1] [,2] [,3]
    [1,]    1    3    5
    [2,]    2    4    6
    """
    arr = conn.r('arr = array(1:6, dim=c(2, 3))')
    assert compareArrays(conn.r.arr, arr)

    # check that 2nd row (last row) is equal:
    assert len(arr[1]) == len(conn.r('arr[2,]')) == 3
    assert compareArrays(arr[1], conn.r('arr[2,]'))

    # check that 2nd column (middle col) is equal:
    assert len(arr[:, 1]) == len(conn.r('arr[,2]')) == 2
    assert compareArrays(arr[:, 1], conn.r('arr[,2]'))
예제 #19
0
def test_eval_very_convoluted_function_result():
    """
    The result of this call is a highly nested data structure.
    Have fun on evaluation it!
    """
    res = conn.r('x<-1:20; y<-x*2; lm(y~x)')
    assert res.__class__ == TaggedList
    # check which tags the TaggedList has:
    assert res.keys == ['coefficients', 'residuals', 'effects', 'rank',
                        'fitted.values', 'assign', 'qr', 'df.residual',
                        'xlevels', 'call', 'terms', 'model']
    assert compareArrays(res['coefficients'],
                         TaggedArray.new(numpy.array([-0.,  2.]),
                                         ['(Intercept)', 'x']))
예제 #20
0
def test_eval_very_convoluted_function_result():
    """
    The result of this call is a highly nested data structure.
    Have fun on evaluation it!
    """
    res = conn.r('x<-1:20; y<-x*2; lm(y~x)')
    assert res.__class__ == TaggedList
    # check which tags the TaggedList has:
    assert res.keys == [
        'coefficients', 'residuals', 'effects', 'rank', 'fitted.values',
        'assign', 'qr', 'df.residual', 'xlevels', 'call', 'terms', 'model'
    ]
    assert compareArrays(
        res['coefficients'],
        TaggedArray.new(numpy.array([-0., 2.]), ['(Intercept)', 'x']))
예제 #21
0
def test_eval_unicode_arrays():
    """
    Test for unicode arrays. The ident function should return the
    same array, just not as unicode
    """
    try:
        u1 = eval("u'abc'")
        u2 = eval("u'def'")
    except SyntaxError:
        # Python 3 below 3.3 does not accept the u'' operator,
        # just skip this test!
        return

    # test via call to ident function with single argument:
    assert conn.r.ident(numpy.array([u1])) == 'abc'
    assert compareArrays(conn.r.ident(numpy.array([u1, u2])),
                         numpy.array(['abc', 'def']))
예제 #22
0
def test_eval_unicode_arrays():
    """
    Test for unicode arrays. The ident function should return the
    same array, just not as unicode
    """
    try:
        u1 = eval("u'abc'")
        u2 = eval("u'def'")
    except SyntaxError:
        # Python 3 below 3.3 does not accept the u'' operator,
        # just skip this test!
        return

    # test via call to ident function with single argument:
    assert conn.r.ident(numpy.array([u1])) == 'abc'
    assert compareArrays(conn.r.ident(numpy.array([u1, u2])),
                         numpy.array(['abc', 'def']))
예제 #23
0
def test_empty_boolean_array():
    """Check that zero-length boolean ('logical') array is returned fine"""
    conn.r('empty_bool_arr = as.logical(c())')
    assert compareArrays(conn.r.empty_bool_arr, numpy.array([], dtype=bool))
예제 #24
0
def test_tagged_array():
    res = conn.r('c(a=1.,b=2.,c=3.)')
    exp_res = TaggedArray.new(numpy.array([1., 2., 3.]), ['a', 'b', 'c'])
    assert compareArrays(res, exp_res)
    assert res.keys() == exp_res.keys()  # compare the tags of both arrays
예제 #25
0
def test_tagged_array():
    res = conn.r('c(a=1.,b=2.,c=3.)')
    exp_res = TaggedArray.new(numpy.array([1., 2., 3.]), ['a', 'b', 'c'])
    assert compareArrays(res, exp_res)
    assert res.keys() == exp_res.keys()  # compare the tags of both arrays
예제 #26
0
def test_empty_boolean_array():
    """Check that zero-length boolean ('logical') array is returned fine"""
    conn.r('empty_bool_arr = as.logical(c())')
    assert compareArrays(conn.r.empty_bool_arr, numpy.array([], dtype=bool))