Commit 1b83a040 authored by Dirk Eddelbuettel's avatar Dirk Eddelbuettel

Import Upstream version 2.8.6

parents
Author
------
Laurent Gautier
Copyright Laurent Gautier 2008-2010
People have contributed suggestions or patches; they are thanked here,
rpy2 is much better because of them.
rpy2 is making a limited use (if much left) of code from:
RPy - http://rpy.sourceforge.net
--------------------------------
(in rinteface/rinterface.c)
Copyright Walter Moreira 2002-2003
Copyright Gregory Warnes 2003-2008
Parseltongue project - http://serpent.speak.googlepages.com/
------------------------------------------------------------
(in rinterface/rinterface.c)
Copyright Alexander Belopolsky - 2006
global-include README
global-exclude *patch* *diff* .hg
include MANIFEST MANIFEST.in
include NEWS README AUTHORS
include gpl-2.0.txt
include rpy/rinterface/_rinterface.h
include rpy/rinterface/_rinterface.c
include rpy/rinterface/sexp.c
include rpy/rinterface/sexp.h
include rpy/rinterface/array.c
include rpy/rinterface/array.h
include rpy/rinterface/buffer.c
include rpy/rinterface/buffer.h
include rpy/rinterface/sequence.c
include rpy/rinterface/sequence.h
include rpy/rinterface/na_values.c
include rpy/rinterface/na_values.h
include rpy/rinterface/null_value.c
include rpy/rinterface/null_value.h
include rpy/rinterface/embeddedr.c
include rpy/rinterface/embeddedr.h
include rpy/rinterface/r_utils.c
include rpy/rinterface/r_utils.h
include rpy/rinterface/_rpy_device.c
include rpy/rinterface/rpy_device.h
include rpy/rinterface/rexternalptr.c
include rpy/rinterface/rexternalptr.h
include rpy/rinterface/*.py
include rpy/rinterface/tests/*.py
include rpy/__init__.py
include rpy/tests.py
include rpy/rpy_classic.py
include rpy/tests_rpy_classic.py
recursive-include rpy/robjects *.py
recursive-include rpy/ipython *.py
recursive-include rpy/interactive *.py
recursive-include rpy/rlike *.py
prune dist
include doc/Makefile
include doc/source/rpy2_logo.png
This diff is collapsed.
Metadata-Version: 1.1
Name: rpy2
Version: 2.8.6
Summary: Python interface to the R language (embedded R)
Home-page: http://rpy2.bitbucket.io
Author: Laurent Gautier
Author-email: lgautier@gmail.com
License: GPLv2+
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Development Status :: 5 - Production/Stable
Requires: six
This is the source tree or distribution for the rpy2 package.
.. image:: https://img.shields.io/pypi/v/rpy2.svg?style=flat-square
:target: https://pypi.python.org/pypi/rpy2
Installation
============
`pip` should work out of the box:
pip install rpy2
The package is known to compile on Linux, MacOSX, and Windows
(provided that developper tools are installed, and you are ready
figure out how by yourself).
Alternatively, there is a Docker image available to try rpy2 out
without concerns about the installation process.
To run the ipython console:
docker run -it --rm -p 8888:8888 \
rpy2/rpy2:2.8.x ipython
To run jupypter notebook on port 8888:
docker run --rm -p 8888:8888 \
rpy2/rpy2:2.8.x
More information about Docker images can be found in the
`documentation <doc/overview.rst>`_.
In case you find yourself with this source without any idea
of what it takes to compile anything on your platform, try first
python setup.py install
If this fails, consider looking for pre-compiled binaries (they are available on Linux Red Hat,
CentOS, Debian, Ubuntu, etc...) or using the matching Docker container.
Note that `python setup.py develop` will appear to work, but will result in an
installation from the `rpy` directory here. The namespaces will be
incorrect, so don't do that!
Documentation
=============
Documentation is available either in the source tree (to be built),
or online (see the rpy home page on sourceforge).
Testing
=======
The testing machinery uses the new unittest functionality, requiring python 2.7+
(or potentially the backported unittest2 library for older python, but this is
not supported). The test suite can be run (once rpy2 is installed) as follows:
python -m rpy2.tests
By providing an argument, like "-v", you'll get verbose output.
Individual tests can be run as follows:
python -m unittest rpy2.robjects.tests.testVector
Test discovery can be attempted as follows (not that it may not work):
python -m unittest discover rpy2.robjects
Prefer `python -m rpy2.tests` to run all tests.
License
=======
RPy2 can be used under the terms of the GNU
General Public License Version 2 or later (see the file
gpl-2.0.txt). This is the very same license R itself is released under.
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " rpy2demo_graphics to build the figures used in the documentation about graphics"
@echo " rpy2demo_benchmark to build the figure(s) used in the documentation about benchmarks"
@echo " notebooks to build the ipython notebooks used in the documentation"
clean:
rm -rf $(BUILDDIR)/*
rpy2demo_benchmark:
@cd _static/demos && python benchmarks.py
rpy2demo_graphics:
@cd _static/demos && python graphics.py
rpy2demo_all: rpy2demo_graphics rpy2demo_benchmark
# rule to build ipython notebooks from markdown
notebooks/%.ipynb : notebooks/%.md
notedown \
--precode 'from functools import partial' \
'from rpy2.ipython import html' \
'html.html_rdataframe=partial(html.html_rdataframe, table_class="docutils")' \
--run \
-o $@ \
$<
cp $@ _static/notebooks/
# rule to build sphinx-friendly ReST from ipython notebooks
notebooks/%.rst : notebooks/%.ipynb
@cd generated_rst && ipython nbconvert --to rst ../$<
# rule to build HTML render of an ipython notebook
_static/notebooks/%.html : notebooks/%.ipynb
ipython nbconvert --to html $< --output $@
MD_NOTEBOOKS := $(basename $(notdir $(wildcard notebooks/*.md)))
_notebooks: $(MD_NOTEBOOKS:%=notebooks/%.rst)
_notebooks_html: $(MD_NOTEBOOKS:%=_static/notebooks/%.html)
notebooks:
@echo "Building IPython notebooks from markdown..."
mkdir -p _static/notebooks
_notebooks
_notebooks_html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/rpy2.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/rpy2.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/rpy2"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/rpy2"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
This directory contains rst files dynamically generated.
\ No newline at end of file
This diff is collapsed.
__version_vector__ = ((2,8,6), '')
__version__ = '.'.join([str(x) for x in __version_vector__[0]]) + \
'' + __version_vector__[1]
"""
Package to interface with R, with a focus on interactive usage
(REPL approach to code-writing), although the package will work
in non-interactive settings.
The package aims at being simple rather than exhaustively complete
(rpy2.robjects, or rpy2.rinterface, can be used if needed), providing
a comfortable experience with autocompletion-capable python consoles.
"""
from collections import OrderedDict
from rpy2.robjects.packages import _loaded_namespaces
from rpy2.robjects.vectors import IntVector, FloatVector, ComplexVector
from rpy2.robjects.vectors import Array, Matrix
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.vectors import ListVector, DataFrame
from rpy2.robjects.environments import Environment
from rpy2.rinterface import NULL
from rpy2.robjects import Formula, RS4
from rpy2.robjects import methods
from rpy2.robjects import conversion
from rpy2.robjects import help as rhelp
from rpy2.robjects.language import eval
from . import process_revents as revents
from os import linesep
import re
class S4Classes(object):
""" *Very* experimental attempt at getting the S4 classes dynamically
mirrored. """
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __setattr__(self, name, value):
raise AttributeError("Attributes cannot be set. Use 'importr'")
#classes = S4Classes()
#revents.start()
from rpy2.robjects.packages import importr as _importr
from rpy2.robjects.packages import data
import rpy2.robjects.help as rhelp
from rpy2.rinterface import baseenv
from os import linesep
from collections import OrderedDict
import re
class Packages(object):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __setattr__(self, name, value):
raise AttributeError("Attributes cannot be set. Use 'importr'")
packages = Packages()
_loaded_namespaces = baseenv['loadedNamespaces']
def importr(packname, newname = None, verbose = False):
""" Wrapper around rpy2.robjects.packages.importr,
adding the following feature(s):
- package instance added to the pseudo-module 'packages'
"""
assert isinstance(packname, str)
packinstance = _importr(packname, on_conflict = 'warn')
# fix the package name (dots possible in R package names)
if newname is None:
newname = packname.replace('.', '_')
Packages().__dict__[newname] = packinstance
## Currently too slow for a serious usage: R's introspection
## of S4 classes is not fast enough
# d = {}
# for cn in methods.get_classnames(packname):
# class AutoS4(RS4):
# __metaclass__ = methods.RS4Auto_Type
# __rpackagename__ = packname
# __rname__ = cn
# newcn = cn.replace('.', '_')
# d[newcn] = AutoS4
# S4Classes().__dict__[newname] = d
return packinstance
for packname in _loaded_namespaces():
importr(packname)
"""This module runs continuous updates for R, such as redrawing graphs when
the plot window is resized. Use the start() and stop() functions to turn
updates on and off.
"""
from rpy2.rinterface import process_revents
import time
import threading
class _EventProcessorThread(threading.Thread):
""" Call rinterface.process_revents(), pausing
for at least EventProcessor.interval between calls. """
_continue = True
def run(self):
while self._continue:
process_revents()
time.sleep(EventProcessor.interval)
class EventProcessor(object):
""" Processor for R events (Singleton class) """
interval = 0.2
daemon_thread = True
name_thread = 'rpy2_process_revents'
_thread = None
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def start(self):
""" start the event processor """
if (self._thread is not None) and (self._thread.is_alive()):
raise RuntimeError("Processing of R events already started.")
else:
self._thread = _EventProcessorThread(name = self.name_thread)
self._thread.setDaemon(self.daemon_thread)
self._thread.start()
def stop(self):
""" stop the event processor """
self._thread._continue = False
self._thread.join()
thread = property(lambda self: self._thread,
None, None, "Thread that processes the events.")
def start():
""" Start the threaded processing of R events. """
EventProcessor().start()
def stop():
""" Stop the threaded processing of R events. """
EventProcessor().stop()
import unittest
from os.path import dirname
def main():
tr = unittest.TextTestRunner(verbosity = 2)
suite = unittest.defaultTestLoader.discover(dirname(__file__),
pattern='test*')
tr.run(suite)
if __name__ == '__main__':
main()
from .rmagic import load_ipython_extension
""" Goodies for ipython """
import os
import tempfile
import io
from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects.lib import ggplot2, grdevices
from IPython.core.display import Image
# automatic plotting of ggplot2 figures in the notebook
class GGPlot(ggplot2.GGPlot):
def png(self, width = 700, height = 500):
""" Build an Ipython "Image" (requires iPython). """
return image_png(self, width=width, height=height)
class GGPlotSVG(ggplot2.GGPlot):
""" The embedding of several SVG figures into one ipython notebook is
giving garbled figures. The SVG functionality is taken out to a
child class.
"""
def svg(self, width = 6, height = 4):
""" Build an Ipython "Image" (requires iPython). """
with grdevices.render_to_bytesio(grdevices.svg,
width=width,
height=height) as b:
robjects.r("print")(self)
data = b.getvalue()
ip_img = Image(data=data, format='svg', embed=False)
return ip_img
def image_png(gg, width=800, height=400):
with grdevices.render_to_bytesio(grdevices.png,
type="cairo-png",
width=width,
height=height,
antialias="subpixel") as b:
robjects.r("print")(gg)
data = b.getvalue()
ip_img = Image(data=data, format='png', embed=True)
return ip_img
def display_png(gg, width=800, height=400):
ip_img = image_png(gg, width=width, height=height)
return ip_img._repr_png_()
def set_png_formatter():
# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
dpi = png_formatter.for_type(ggplot2.GGPlot, display_png)
return dpi
class PNGplot(object):
"""
Context manager
"""
def __init__(self, width=600, height=400):
self._width = width
self._height = height
png_formatter = get_ipython().display_formatter.formatters['image/png']
self._png_formatter = png_formatter
self._for_ggplot = self._png_formatter.for_type(ggplot2.GGPlot)
def __enter__(self):
self._png_formatter.for_type(ggplot2.GGPlot, display_png)
return None
def __exit__(self, exc_type, exc_val, exc_tb):
self._png_formatter.for_type(ggplot2.GGPlot, self._for_ggplot)
return False
This diff is collapsed.
This diff is collapsed.
import unittest
from os.path import dirname
def main():
tr = unittest.TextTestRunner(verbosity = 2)
suite = unittest.defaultTestLoader.discover(dirname(__file__),
pattern='test*')
tr.run(suite)
if __name__ == '__main__':
main()
This diff is collapsed.
import os
import sys
import warnings
import subprocess
if ((sys.version_info[0] == 2 and sys.version_info[1] < 7) or
(sys.version_info[0] == 3 and sys.version_info[1] < 3)):
raise RuntimeError(
"Python (>=2.7 and < 3.0) or >=3.3 are required to run rpy2")
class RRuntimeWarning(RuntimeWarning):
pass
def _r_home_from_subprocess():
"""Return the R home directory from calling 'R RHOME'."""
try:
tmp = subprocess.check_output(("R", "RHOME"), universal_newlines=True)
except Exception as exc: # FileNotFoundError, WindowsError, etc
return
r_home = tmp.split(os.linesep)
if r_home[0].startswith("WARNING"):
r_home = r_home[1]
else:
r_home = r_home[0].strip()
return r_home