Ejemplo n.º 1
0
def numpy2ri(o):
    """ Augmented conversion function, converting numpy arrays into
    rpy2.rinterface-level R structures. """
    if isinstance(o, numpy.ndarray):
        if not o.dtype.isnative:
            raise(ValueError("Cannot pass numpy arrays with non-native byte orders at the moment."))

        # Most types map onto R arrays:
        if o.dtype.kind in _kinds:
            # "F" means "use column-major order"
            vec = SexpVector(o.ravel("F"), _kinds[o.dtype.kind])
            dim = SexpVector(o.shape, INTSXP)
            res = ro.r.array(vec, dim=dim)
        # R does not support unsigned types:
        elif o.dtype.kind == "u":
            raise(ValueError("Cannot convert numpy array of unsigned values -- R does not have unsigned integers."))
        # Array-of-PyObject is treated like a Python list:
        elif o.dtype.kind == "O":
            res = conversion.py2ri(list(o))
        # Record arrays map onto R data frames:
        elif o.dtype.kind == "V":
            if o.dtype.names is None:
                raise(ValueError("Nothing can be done for this numpy array type %s at the moment." % (o.dtype,)))
            df_args = []
            for field_name in o.dtype.names:
                df_args.append((field_name, 
                                conversion.py2ri(o[field_name])))
            res = ro.baseenv["data.frame"].rcall(tuple(df_args), ro.globalenv)
        # It should be impossible to get here:
        else:
            raise(ValueError("Unknown numpy array type."))
    else:
        res = ro.default_py2ri(o)
    return res
Ejemplo n.º 2
0
 def as_ape_object(o):
     """
     Returns ``o`` as an ape object.
     """
     kwargs = {}
     if isinstance(o, dendropy.TreeList):
         kwargs["keep.multi"] = True
         text = o.as_string("newick")
         return _R["read.tree"](text=text, **kwargs)
     elif isinstance(o, dendropy.Tree):
         kwargs["keep.multi"] = False
         text = o.as_string("newick")
         return _R["read.tree"](text=text, **kwargs)
     #        if isinstance(o, dendropy.Tree) or isinstance(o, dendropy.TreeList):
     #            f = tempfile.NamedTemporaryFile()
     #            o.write_to_stream(f, "nexus", simple=True, block_titles=False)
     #            f.flush()
     #            return _R['read.nexus'](f.name)
     elif isinstance(o, dendropy.CharacterMatrix):
         f = tempfile.NamedTemporaryFile()
         o.write_to_stream(f, "nexus", simple=True, block_titles=False)
         f.flush()
         return _R["read.nexus.data"](f.name)
     else:
         return robjects.default_py2ri(o)
Ejemplo n.º 3
0
    def as_ape_object(o):
        """
        Returns ``o`` as an ape object.
        """
        kwargs = {}
        if isinstance(o, dendropy.TreeList):
            kwargs['keep.multi'] = True
            text = o.as_string("newick")
            return _R['read.tree'](text=text, **kwargs)
        elif isinstance(o, dendropy.Tree):
            kwargs['keep.multi'] = False
            text = o.as_string("newick")
            return _R['read.tree'](text=text, **kwargs)
#        if isinstance(o, dendropy.Tree) or isinstance(o, dendropy.TreeList):
#            f = tempfile.NamedTemporaryFile()
#            o.write_to_stream(f, "nexus", simple=True, block_titles=False)
#            f.flush()
#            return _R['read.nexus'](f.name)
        elif isinstance(o, dendropy.CharacterMatrix):
            f = tempfile.NamedTemporaryFile()
            o.write_to_stream(f, "nexus", simple=True, block_titles=False)
            f.flush()
            return _R['read.nexus.data'](f.name)
        else:
            return robjects.default_py2ri(o)
Ejemplo n.º 4
0
def pd_py2ri(o):
    """ 
    """

    res = None
    if isinstance(o, pd.DataFrame) and isinstance(o.index, pd.DatetimeIndex):
        res = convert_df_to_xts(o)

    if res is None:
        res = robjects.default_py2ri(o)

    return res
Ejemplo n.º 5
0
def numpy2ri(o):
    if isinstance(o, numpy.ndarray):
        if not o.dtype.isnative:
            raise(ValueError("Cannot pass numpy arrays with non-native byte orders at the moment."))

        # The possible kind codes are listed at
        #   http://numpy.scipy.org/array_interface.shtml
        kinds = {
            # "t" -> not really supported by numpy
            "b": rinterface.LGLSXP,
            "i": rinterface.INTSXP,
            # "u" -> special-cased below
            "f": rinterface.REALSXP,
            "c": rinterface.CPLXSXP,
            # "O" -> special-cased below
            "S": rinterface.STRSXP,
            "U": rinterface.STRSXP,
            # "V" -> special-cased below
            }
        # Most types map onto R arrays:
        if o.dtype.kind in kinds:
            # "F" means "use column-major order"
            vec = rinterface.SexpVector(o.ravel("F"), kinds[o.dtype.kind])
            dim = rinterface.SexpVector(o.shape, rinterface.INTSXP)
            res = ro.r.array(vec, dim=dim)
        # R does not support unsigned types:
        elif o.dtype.kind == "u":
            raise(ValueError("Cannot convert numpy array of unsigned values -- R does not have unsigned integers."))
        # Array-of-PyObject is treated like a Python list:
        elif o.dtype.kind == "O":
            res = ro.conversion.py2ri(list(o))
        # Record arrays map onto R data frames:
        elif o.dtype.kind == "V":
            if o.dtype.names is None:
                raise(ValueError("Nothing can be done for this numpy array type %s at the moment." % (o.dtype,)))
            df_args = []
            for field_name in o.dtype.names:
                df_args.append((field_name, 
                                ro.conversion.py2ri(o[field_name])))
            res = ro.baseNameSpaceEnv["data.frame"].rcall(tuple(df_args))
        # It should be impossible to get here:
        else:
            raise(ValueError("Unknown numpy array type."))
    else:
        res = ro.default_py2ri(o)
    return res
Ejemplo n.º 6
0
def pd_py2ri(o):
    """ 
    """
    res = None
    if isinstance(o, pd.DataFrame): 
        if isinstance(o.index, pd.DatetimeIndex):
            res = convert_df_to_xts(o)
        else:
            res = rcom.convert_to_r_dataframe(o)

    if isinstance(o, pd.DatetimeIndex): 
        res = convert_datetime_index(o)
        
    if res is None:
        res = robjects.default_py2ri(o)

    return res
Ejemplo n.º 7
0
def pd_py2ri(o):
    """ 
    """
    res = None
    if isinstance(o, pd.DataFrame):
        if isinstance(o.index, pd.DatetimeIndex):
            res = convert_df_to_xts(o)
        else:
            res = rcom.convert_to_r_dataframe(o)

    if isinstance(o, pd.DatetimeIndex):
        res = convert_datetime_index(o)

    if res is None:
        res = robjects.default_py2ri(o)

    return res
Ejemplo n.º 8
0
def numpy2ri(o):
    """ Augmented conversion function, converting numpy arrays into
    rpy2.rinterface-level R structures. """
    # allow array-likes to also function with this module.
    if not isinstance(o, numpy.ndarray) and hasattr(o, '__array__'):
        o = o.__array__()
    if isinstance(o, numpy.ndarray):
        if not o.dtype.isnative:
            raise (ValueError(
                "Cannot pass numpy arrays with non-native byte orders at the moment."
            ))

        # Most types map onto R arrays:
        if o.dtype.kind in _kinds:
            # "F" means "use column-major order"
            vec = SexpVector(o.ravel("F"), _kinds[o.dtype.kind])
            dim = SexpVector(o.shape, INTSXP)
            #FIXME: no dimnames ?
            #FIXME: optimize what is below needed/possible ? (other ways to create R arrays ?)
            res = rinterface.baseenv['array'](vec, dim=dim)
        # R does not support unsigned types:
        elif o.dtype.kind == "u":
            raise (ValueError(
                "Cannot convert numpy array of unsigned values -- R does not have unsigned integers."
            ))
        # Array-of-PyObject is treated like a Python list:
        elif o.dtype.kind == "O":
            res = conversion.py2ri(list(o))
        # Record arrays map onto R data frames:
        elif o.dtype.kind == "V":
            if o.dtype.names is None:
                raise (ValueError(
                    "Nothing can be done for this numpy array type %s at the moment."
                    % (o.dtype, )))
            df_args = []
            for field_name in o.dtype.names:
                df_args.append((field_name, conversion.py2ri(o[field_name])))
            res = ro.baseenv["data.frame"].rcall(tuple(df_args), ro.globalenv)
        # It should be impossible to get here:
        else:
            raise (ValueError("Unknown numpy array type."))
    else:
        res = ro.default_py2ri(o)
    return res