Source code for dms_tools2.rplot

"""
===================
rplot
===================

Plotting that uses ``R``.

The `dms_tools2` software is written in Python, but there are
useful plotting features that are only available in ``R``,
such `ggseqlogo <https://omarwagih.github.io/ggseqlogo/>`_.

This module uses ``R`` to make plots using these features. It
requires `rpy2 <https://rpy2.readthedocs.io>`_ to be installed.
Installation of `rpy2 <https://rpy2.readthedocs.io>`_ is 
**not** automatic when you install `dms_tools2` unless
you have ``R`` and `rpy2 <https://rpy2.readthedocs.io>`_
installed, or install `dms_tools2` using::

    pip install dms_tools[rplot] --user

"""

import os
import io
import warnings

import pandas

import phydmslib.weblogo
#: default colors for amino acid chars, by functional group
AA_COLORS_FG = phydmslib.weblogo.FunctionalGroupColorMapping()[1]

# import rpy2
try:
    import rpy2
except ImportError:
    raise ImportError("You must install `rpy2` to use `rplot`")
import rpy2.rinterface as rinterface
rinterface.initr()
from rpy2.robjects import pandas2ri, r
pandas2ri.activate()
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import StrVector, ListVector, FloatVector
from rpy2.rlike.container import TaggedList
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

#: Show warnings when running ``R`` code? Plausible values: `default`,
#: `ignore`, and `always`. The `R` code gives many warnings, so
#: `ignore` is good when not developing new code.
SHOW_WARNINGS = 'ignore'

# install necessary packages
_packages = ['ggplot2', 'ggseqlogo']
utils = importr('utils')
with warnings.catch_warnings():
    warnings.simplefilter(SHOW_WARNINGS)
    utils.chooseCRANmirror(ind=1)
    utils.install_packages(StrVector(_packages))
for _package in _packages:
    importr(_package)

# read the R code that defines the R functions we run
_RCODEFILE = os.path.join(os.path.dirname(__file__), 'rplot_Rcode.R')
assert os.path.isfile(_RCODEFILE)
with open(_RCODEFILE) as f:
    _RCODE = f.read()
_RFUNCS = SignatureTranslatedAnonymousPackage(_RCODE, "_RFUNCS")


[docs]def versionInfo(): """Returns string giving `rpy2` and ``R`` version info.""" return "Using `rpy2` {0} with ``R`` {1}".format( rpy2.__version__, rinterface.R_VERSION_BUILD[1])
if __name__ == '__main__': import doctest doctest.testmod()