rpy-1.0.3/0000755000076700000240000000000011012207656011511 5ustar warnesstaffrpy-1.0.3/ChangeLog0000644000076700000240000012206511012206040013253 0ustar warnesstaff2008-05-13 03:32 warnes * [r513] setup.py: Add notes on what is necessary to build against multiple versions of R on OSX 2008-05-09 21:17 warnes * [r511] TODO: Add to TODO. 2008-05-09 21:16 warnes * [r510] src/rpymodule.c: Patch to correct link problem with R-2.7.0 2008-04-16 14:19 warnes * [r489] rpy.py: Fix R.__repr__() bug. 2008-04-10 16:51 warnes * [r487] NEWS, rpy_version.py: Update for RPy release 1.0.2 2008-04-10 16:50 warnes * [r486] examples/nnet.py: Add simple neural net example 2008-04-10 16:49 warnes * [r485] src/rpymodule.c: Use R's internal function to clean up R temporary directory for R 2.4.0 and later 2008-04-10 13:45 warnes * [r484] src/rpymodule.c: Correct the handling of CStackLimit code. 2008-04-03 23:26 warnes * [r475] tests/test_robj.py: Use failUnless / failUnlessRaises instead of assertTrue / assertRaises in test_robj.py for compatibility with python 2.3 2008-01-29 19:41 lgautier * [r403] src/rpymodule.c: changed function types form ssizeargfunc to intargfunc, and ssizessizeargfunc to intintargfunc (for compatibility with Python 2.4). It compiles with Python 2.5 with warnings. Conditional definitions will probably have to be made for Python 2.6 (or before to clear up the warnings). 2008-01-27 14:15 lgautier * [r402] src/rpymodule.c, tests/test_robj.py: - Added getslice methods for Robject - Added unit-tests for it - Added unit-tests for getItem 2008-01-25 20:14 warnes * [r401] rpy_tools.py: Correct name of runtime exception 2008-01-21 16:08 eddelbuettel * [r400] debian/changelog, debian/control: Updated debian/ to current upload 1.0.1-2 2008-01-21 16:00 eddelbuettel * [r399] doc/rpy.texi: corrected simple line plot example 2008-01-21 15:59 eddelbuettel * [r398] debian/changelog, debian/control, debian/overrides, debian/rules: updated to current version 2008-01-07 17:16 warnes * [r397] src/rpymodule.c: Correct mismatch between declaration and definition of init_embedded_win32 2008-01-07 16:03 warnes * [r396] src/rpymodule.c: Add ability to pass command-line argumnents to init_embedded_win32 2008-01-07 16:01 warnes * [r395] tests/test_sigint.py: Add 1 second sleep to interrupt test to allow time for interrupt delivery 2008-01-02 17:57 warnes * [r394] rpy.py, src/rpymodule.c: Add code to export 'Robj' type 2008-01-02 17:34 warnes * [r393] src/io.c: Minor code reformatting in io.c 2008-01-02 17:33 warnes * [r392] rpy_tools.py: Use 'tail -n 1' instead of 'tail -1' when calling 'R RHOME' to make recent versions of tail happy 2008-01-02 17:29 warnes * [r391] rpy.py, rpy_options.py: Add startup options to prevent initialization of console read/write/showfiles 2007-11-30 01:44 warnes * [r390] NEWS: Update NEWS for 1.0.1 2007-11-30 01:27 warnes * [r389] rpy_version.py: Update version to 1.0.1 2007-11-30 01:00 warnes * [r388] doc/defs.texi, doc/rpy.texi: Update copyright notice in documentation 2007-11-30 00:57 warnes * [r387] rpy.py: Remove debug print statments 2007-11-30 00:56 warnes * [r386] rpy_wintools.py: Improve detection of R installation directories on Win32 2007-11-30 00:55 warnes * [r385] setup.bat: Improve Win32 setup.bat build script 2007-11-30 00:40 warnes * [r384] src/RPy.h, src/rpymodule.c: Add appropriate cleanup shell command for Win32 2007-11-29 16:12 warnes * [r383] INSTALL.WINDOWS, setup.bat: Update windows compile instructions and batch file 2007-11-29 16:07 warnes * [r382] rpy.py: Move rpy module load back inside try:except block 2007-11-29 16:06 warnes * [r381] setup.py: ensure RHOMES is in ascii, since most command line tools are unhappy with unicode... 2007-11-29 15:59 warnes * [r380] src/RPy.h, src/rpymodule.c: Apply tiny patch to fix Win32 startup problem. 2007-11-20 02:18 eddelbuettel * [r379] debian/changelog, debian/compat, debian/control, debian/overrides, debian/rules: sync with files of Debian 1.0.0-1 release of rpy 2007-11-15 05:24 warnes * [r378] NEWS: Update for v 1.0.0 2007-11-15 04:59 warnes * [r377] rpy_version.py: update version to 1.0.0 (after thinking about it) 2007-11-15 04:17 warnes * [r376] rpy_version.py: update version to 1.1-Beta1 2007-11-15 04:08 warnes * [r375] tests/test_modes.py: Comment out gc code, only needed when debugging 2007-11-15 03:47 warnes * [r374] tests/test_numeric.py: Change function to_r used in tests to make it more reliable 2007-11-15 03:22 warnes * [r373] tests/test_io.py: Add code to test_io to return io redirection to initial state after each test 2007-11-13 16:24 warnes * [r372] tests/testall.py: Add ability to loop over test cases 2007-11-13 15:41 warnes * [r371] tests/test_numeric.py: Improve display of messages about tests being skipped (more) 2007-11-13 15:37 warnes * [r370] tests/test_numeric.py: Improve display of messages about tests being skipped 2007-11-13 15:35 warnes * [r369] tests/test_numeric.py: Numeric.Character isn't handled (yet?), so modify test appropriately 2007-11-13 15:28 warnes * [r368] tests/test_numeric.py: Minor reformatting of test_numeric.py 2007-11-13 06:43 warnes * [r367] tests/test_numeric.py: Select which syntax variant to use by which library was loaded, rather than using try:except to try a second variance after the first failed. 2007-11-13 06:27 warnes * [r366] tests/test_array.py, tests/test_numeric.py: Fix array test to explicitly check elements of 3 dimensional objects for equality. 2007-11-13 06:26 warnes * [r365] src/rpymodule.c: More work on handling Numeric/NumPy array and scalar objects. Only NumPy string/unicode/char objects are still unhandled, AFAIK. 2007-11-13 06:13 warnes * [r364] setup.py: Add /usr/share/R/include path for Ubuntu (?Debian?) R include files 2007-11-12 23:27 warnes * [r363] TODO, rpy.py, setup.py, src/RPy.h, src/R_eval.c, src/rpymodule.c, tests/test_array.py, tests/test_numeric.py, tests/test_robj.py, tests/test_tor.py, tests/test_util.py: - Add three new exceptions: RPyException Base exception class for all RPy Exceptions RPyTypeConversionException Error in conversion between R and Python RPyRException Error raised within R (RException is set equal to RPyException for backwards compatibility) - Properly handle all Numeric/NumPy array types - Solve 64 bit problems converting Numeric/NumPy arrays 2007-11-06 16:49 warnes * [r362] src/RPy.h, src/rpymodule.c: Apply patch submitted by Matthew Brett to resolve array size issues on 64 bit platforms 2007-10-18 19:40 warnes * [r361] src/rpymodule.c: More fixes for handling of Unicode strings. Suggested by Toby Dylan Hocking. 2007-10-18 01:54 warnes * [r359] src/rpymodule.c: Remove unneeded comment 2007-10-18 01:36 warnes * [r358] rpy_wintools.py: Apply patch [ 1808836 ] Install-script tweaking for Windows 2007-10-18 01:26 warnes * [r357] src/rpymodule.c: Handle python unicode strings in calls to R by first converting to python ascii strings 2007-10-08 20:35 warnes * [r356] setup.py: Testing whewther Numeric is present was broken. Fixed. 2007-10-08 20:33 warnes * [r355] rpy_options.py: Change default for rpy_options.VERBOSE to False 2007-10-08 20:26 warnes * [r354] src/rpymodule.c: Use proper test for whether R_CStackLimit can/should be set 2007-10-08 19:09 warnes * [r353] tests/testall.py: Show modules to be tested 2007-05-18 15:41 warnes * [r351] rpy_version.py: Update version number 2007-03-24 21:40 warnes * [r344] src/rpymodule.c: R_CStackLimit is only present on Unix-like systems, so omit it on Win32. 2007-03-12 22:50 warnes * [r343] src/rpymodule.c: Applied patch created by Andrew McNamara that resolves the C stack limit error produced by R in some contexts, such as resizing the x11() window. 2007-02-20 16:41 warnes * [r342] rpy.py, setup.py, src/RPy.h, src/rpymodule.c, tests/test_array.py, tests/test_numeric.py, tests/test_topy.py: Initial attempt to apply Numpy support patch provided by Alexander Belopolsky 2006-12-11 18:59 alain001 * [r341] rpy_version.py: Added config for other R versions. 2006-09-16 00:37 eddelbuettel * [r340] debian/changelog, debian/control, debian/pycompat, debian/python-rpy.postinst, debian/python-rpy.preinst, debian/python-rpy.prerm, debian/rules: updated debian/* files 2006-08-18 14:19 alain001 * [r339] rpy.py: Moved some code so no longer necessary to have R/bin in PATH 2006-08-08 19:29 alain001 * [r338] rpy_version.py: 1.0-RC1 2006-08-08 19:27 alain001 * [r337] setup.py: Changed contact info. 2006-08-07 19:04 alain001 * [r336] tests/testall.py: Better filtering of module names 2006-08-07 15:05 alain001 * [r335] tests/test_topy.py: Removed some tests related to NA and NAN 2006-08-04 16:35 alain001 * [r334] tests/test_io.py: Skip tests involving set_rpy_showfiles() for win32 2006-06-21 12:52 eddelbuettel * [r333] debian/changelog, debian/control, debian/rules: updated debian/ to the 'New Debian Python Policy' 2006-04-06 02:03 eddelbuettel * [r304] debian/changelog, debian/rules, doc/rpy.texi, rpy_tools.py: - rpy_tools.py: Render regular expression for R version less strict to cope with switch from 'R x.y.z' to 'Version x.y.z' as in the current R 2.3.0 alpha release - doc/rpy.texi: Move include of defs.texi up so that RPy is defined in title - debian/rules: Additional removals in clean target - debian/changelog: Entry for 0.99.2-1 2006-04-04 18:28 warnes * [r303] NEWS: Clarify text. 2006-04-04 18:23 warnes * [r302] NEWS, rpy_version.py, setup.bat: Bump up version number and NEWS for new build to correct lack of Numeric support in Windows distribution. 2006-03-25 01:35 warnes * [r300] debian/changelog, debian/copyright, debian/python-rpy-doc.doc-base, debian/rules, doc/defs.texi, doc/rpy.texi: Changes submitted by Dirk Eddelbuettel: The documentation wouldn't build in all the forms I needed. See the attached diff, esp at the end -- in rpy.texi I 'pulled' defs.texi a few lines higher so that the RPy macro is known, and for some odd reason I also needed to edit your email address in the comment header of defs.texi. Same behaviour on Debian testing and in the Debian unstable chroot the packages are built in. There are a few more debian/ changes in the diff that you sync to the archive. 2006-03-22 22:13 warnes * [r299] COPYING, GPL_LICENSE, LGPL_LICENSE, MPL_LICENSE, README, doc/Makefile, doc/defs.texi, doc/rpy.texi, rpy_wintools.py, setup.Win32, setup.bat, setup.in, src/RPy.h, src/R_eval.c, src/io.c, src/robjobject.h, src/rpy_Rinterface.h, src/rpy_Startup.h, src/rpymodule.c, src/setenv.c, src/setenv.h: Add tri-way license: MPL, GPL, LGPL 2006-03-22 22:07 warnes * [r298] rpy_version.py: - Fix startup crash on win32 - Allow use of MPL, GPL, or LGPL. 2006-03-22 22:05 warnes * [r297] rpy.py: Fix crash on win32 due to omission (was commented out!) of explicit dll load. 2006-03-16 16:32 warnes * [r293] MANIFEST.in: Update MANIFEST.in to exclude svn files. 2006-03-16 15:22 warnes * [r292] debian/rules: My bad. Add compile flags to the build section, not the install section! 2006-03-16 00:10 warnes * [r291] debian/python-rpy-doc.doc-base, debian/python-rpy-doc.postinst, debian/python-rpy-doc.prerm, debian/watch: debian build changes per Dirk Eddelbuettel 2006-03-16 00:07 warnes * [r290] debian/changelog, debian/control, debian/rules: debian build changes per Dirk Eddelbuettel 2006-03-16 00:03 warnes * [r289] NEWS, rpy_version.py: Update version numer and NEWS file for 0.99.0 release 2006-03-15 23:43 warnes * [r288] INSTALL.WINDOWS, rpy_wintools.py, setup.Win32, setup.bat, setup.cfg, setup.py: Dramatically simplify the build process for Win32. The gcc and ld included in MinGW 5.0.2 can now linking directly against DLL's, removing the need for much of the previous complexity. 2006-03-15 23:29 warnes * [r287] setup.in: Add comments showing full set of configuration options 2006-03-15 23:27 warnes * [r286] debian/rules: Provide explicit path to R include files 2006-03-15 19:01 warnes * [r285] setup.cfg: Add setup.cfg template to allow users to more easily customize build/install options. 2006-03-10 21:34 warnes * [r284] MANIFEST.in, setup.py, src/rpymodule.c: This code now works on both Linux and Windows. For windows: - libpythonXX.a must be in C:/pythonXX/libs - R.dll, R.def, and libR.a need to be in the rpy directory Otherwise, a badly mangled version of the full path to the dll gets inserted into the binary. Grrr. This is probably a bug in the mingw version of ld, but it seems to be longstanding. 2006-03-10 13:42 warnes * [r283] rpy_wintools.py, setup.py: Remove partially working win32 changes 2006-03-10 12:56 warnes * [r281] setup.py: Revert a couple of minor changes 2006-03-10 06:18 warnes * [r280] mingw_buildrpy.bat, rpy.py, rpy_option.py, rpy_options.py, rpy_tools.py, rpy_wintools.py, setup.py, src/RPy.h, src/rpy_Rinterface.h, src/rpy_Startup.h, src/rpymodule.c, win_tools.py: More modifications. For some reason, with MinGW,using -L causes the names of dlls required by the generated dll to get mangled. This prevents the correct DLL from being found at run time. I'm not sure how to get around this. 2006-03-06 22:22 warnes * [r279] INSTALL.WINDOWS, MANIFEST.in, rpy.py, setup.py, win_tools.py: More win32 work. DLL error on load. 2006-03-03 22:10 warnes * [r278] INSTALL.WINDOWS, mingw_buildrpy.bat, rpy.py, rpy_option.py, rpy_tools.py, setup.py, src/RPy.h, src/rpy_Rinterface.h, src/rpymodule.c, win_tools.py: `cat commit.txt` 2006-03-02 19:32 warnes * [r277] rpy.py, rpy_tools.py, src/rpymodule.c: Communicate RHOME, RVER, RVERSION, RUSER from python to C code using environment variables. This avoids the need to have duplicate C code to obtain these values. 2006-03-02 17:34 warnes * [r276] src/rpymodule.c: Undo recent changes to rpymodule. Decided to use a different approach. 2006-03-01 21:24 warnes * [r275] src/rpymodule.c: Remove code to determine location of R shared library. Instead realy on RPy.py to pass these in. 2006-02-28 23:24 warnes * [r274] rpy.py, rpy_tools.py: More fixes for win32 2006-02-28 14:57 warnes * [r271] setup.py: Correct 'RHOME' to 'RHOMES' in introductory help text. 2006-02-28 14:51 warnes * [r270] rpy.py: Fix bugs on windows. 2006-02-28 14:34 warnes * [r269] doc/Makefile, doc/README, doc/manual.texi, doc/rpy.texi: rename manual.text to rpy.texi to better match standard usage of info files 2006-02-27 23:23 warnes * [r268] setup.py, src/rpymodule.c: Hopefully, these changes fix run-time testing for the absence of Numeric when the code was compiled with Numeric present. 2006-02-27 23:15 warnes * [r267] rpy.py: Add workaround for windows plotting issue. Correct fix is to get the eventloop working properly. 2006-02-27 22:36 warnes * [r266] setup.py: OSX is now using an external BLAS library, so remove Rlapack link option. 2006-02-27 22:32 warnes * [r265] INSTALL.WINDOWS: Update text regarding need to install Numeric and add URL. 2006-02-27 21:59 warnes * [r259] INSTALL.WINDOWS: Make instructions more clear about the need for the 'Numeric' package. 2005-11-04 06:13 andrewmcnamara * [r258] tests/test_tor.py: Add test for bug ID 1277392. 2005-11-04 05:50 andrewmcnamara * [r257] src/rpymodule.c: Fixed bug 1277392 - if an Robj was encounted as the first item in a sequence being converted to an R object, then seq_to_R would return NULL (without setting the python error flag). Prior to revision 1.26, an "any" would be returned. This change reinstates the old behavior. 2005-10-10 20:51 warnes * [r256] rpy.py, rpy_version.py: Fix bug in __repr__ 2005-10-10 19:59 warnes * [r255] rpy.py: Attempt to set the binary path for Windows 2005-10-10 19:58 warnes * [r254] NEWS: old changes. 2005-10-07 01:54 andrewmcnamara * [r253] rpy.py: At exit, attempt to stop the event loop before Python dismantles everything (which causes the event loop to throw an exception). 2005-10-06 05:35 andrewmcnamara * [r252] src/rpymodule.c, tests/test_robj.py: Additional error checking for keyword arguments (and associated tests). 2005-10-06 05:31 andrewmcnamara * [r251] setup.py: setup.py's "mtime()" function was not returning the modification time. Changed to simply alias sys.path.getmtime(). 2005-07-28 14:25 warnes * [r232] NEWS, rpy_version.py, src/rpymodule.c: For version 0.4.6 2005-07-28 04:55 warnes * [r230] rpy_tools.py, setup.py: - Strip leading and trailing spaces from RHOME. - Display contents of RHOMES 2005-07-28 02:23 warnes * [r229] NEWS, tests/test_noninteractive.py: Fix typo. 2005-07-27 17:59 warnes * [r228] tests/test_noninteractive.py: Add testcase to catch R terminating rather than raising the exception when run non-interactively via stdin redirection. 2005-07-27 17:56 warnes * [r227] rpy.py: Wait for all threads to exit before doing R clean up. 2005-07-27 16:01 warnes * [r226] tests/test_boolean.py, tests/test_numeric.py, tests/test_tor.py, tests/test_vars.py, tests/testall.py: Make sure default mode is set back to NO_DEFAULT before running each test. Otherwise some tests will fail if a previous test didn't changed the mode. 2005-07-27 13:42 warnes * [r225] rpy.py: Fix missing import and typo for Win32 reported by Wei-Hao Lin 2005-07-27 03:05 warnes * [r224] rpy.py, src/RPy.h, src/R_eval.c, src/rpymodule.c, tests/test_vars.py: Fix bug reported by Nicolas Lebas: Segfault when accessing r objects via r.. It turns out the code was only properly handling this for R function objects. Resolution: 1) Rename get_from_name to get_fun_from_name and get to get_fun to show that these calls should only be used for R function objects. 2) Modify the R class to call R's 'get' function instead of using get_fun(). 3) Add comments to get_fun_from_names to elucidate the non-obvious code there. 2005-07-27 02:59 warnes * [r223] setup.py: Create/overwrite .c files only if they don't exist or are out of date. 2005-07-25 14:45 warnes * [r222] NEWS: Fix version number typo 2005-07-25 14:29 warnes * [r221] NEWS: Update for 0.4.5 2005-07-25 14:20 warnes * [r220] setup.py: setup.py doesn't seem to like an author without an email. 2005-07-25 14:20 warnes * [r219] MANIFEST.in: We need to exclude version-specific source files created by the multi-R changes. 2005-07-25 14:09 warnes * [r218] rpy_version.py: Update version number. 2005-07-25 14:07 warnes * [r217] setup.py: Modify setup.py to build & install for multiple R versions, following Bo Peng's contributions. 2005-07-25 13:15 warnes * [r216] INSTALL.WINDOWS, mingw_buildrpy.bat, rpy_version.py: Update windows build instructions. Provide mingw_buildrpy.bat 2005-07-25 13:06 warnes * [r215] src/rpy_Rinterface.h: Add rpy_Rinterface.h, which is used for R versions before 2.1.0. 2005-07-23 04:41 warnes * [r213] NEWS: Document changes to warning message display. 2005-07-23 04:39 warnes * [r212] src/rpymodule.c: Show warnign messages after each R evaluation. 2005-07-23 04:34 warnes * [r211] NEWS: Update for 0.4.4 2005-07-23 04:17 warnes * [r210] rpy.py, rpy_version.py, src/RPy.h, src/rpy_Startup.h, src/rpymodule.c: Avoid calling numeric when it is not available at runtime. 2005-07-23 02:59 warnes * [r209] MANIFEST.in: Omit core files! 2005-07-23 00:03 warnes * [r208] MANIFEST.in: Trying to remove tidla terminated files resulted in no files. 2005-07-21 17:35 warnes * [r206] setup.py: Windows doesn't know what to do with runtime_libs. 2005-07-21 03:33 warnes * [r205] setup.py: Win32 requires that the quotes around DEFINE's are escaped. 2005-07-21 03:23 warnes * [r204] rpy_tools.py: - Raise RuntimeError instead of Distutils error. - Quote R command so that embedded spaces won't cause problems. 2005-07-20 06:51 warnes * [r202] NEWS: Spelling! 2005-07-20 06:35 warnes * [r201] doc/manual.texi: Update documentation to reflect new 'VECTOR_CONVERSION' mode. 2005-07-20 05:38 warnes * [r200] NEWS, rpy.py, rpy_tools.py, setup.py, src/rpymodule.c: Complete work for version-specific shared libraries. 2005-07-20 05:29 warnes * [r199] tests/logit.r: Add logit.r required by test_lapack_load.py. 2005-07-19 20:40 warnes * [r198] tests/test_lapack_load.py: Add test that we can load the Rlapack library. 2005-07-19 20:39 warnes * [r197] NEWS, rpy.py, src/RPy.h, src/rpymodule.c, tests/test_array.py, tests/test_modes.py, tests/test_numeric.py, tests/test_robj.py, tests/test_topy.py, tests/test_tor.py, tests/test_util.py: - Add support for python boolean objects. R Logicals are now converted to/from Python booleans. - New translation mode 'VECTOR_CONVERSION', which differs from 'BASIC_CONVERSION' in that R objects are always returned as vectors even if length 1. 2005-07-15 18:44 warnes * [r196] src/RPy.h: Changes to avoid redefinition errors on Win32. 2005-07-15 17:36 warnes * [r195] src/rpymodule.c: - Fix error (potential segfault!) when handling conversion of factor objects contining missing values 2005-07-15 17:28 warnes * [r194] tests/test_topy.py: Minor whitespace reformatting. 2005-07-15 17:28 warnes * [r193] rpy.py: - Fix bug in R.__call__ that could cause problems when the 'r' object is not present. 2005-07-15 17:23 warnes * [r192] tests/test_topy.py: Add tests for NA values. 2005-07-15 15:00 warnes * [r191] rpy.py: - The R integer 'NA' value is now accessible as the 'NA' attribute of the Python 'r' object. - The R floating point 'NA' value is now accessible as the 'NAN' attribute of the Python 'r' object. 2005-07-15 07:07 warnes * [r190] setup.py: Explicitly link to libRlapack to ensure this library is found at runtime. (Oddly simply adding -R doesn't do the trick.) 2005-07-15 06:15 warnes * [r189] doc/Makefile: Explicitly call tex / makeinfo / pdflatex twice to ensure that toc/index are properly built. 2005-07-15 06:06 warnes * [r188] setup.py: - Display R path and version - Append version string ('2010') to shared library/dll name so that multiple versions can colocate. This should ease packaging for windows. 2005-07-15 05:35 warnes * [r187] rpy.py: Add code to try loading R-version specific _rpy module on Win32. This should make it easier to support multiple R versions with a single distributed package. 2005-07-14 19:14 warnes * [r186] rpy.py: - On Windows, always look at the registry to see where to find the R DLL. This should avoid the nasty popup error message when the DLL isn't on the path. Patch by Peter (maubp@users.sourceforge.net) 2005-07-14 18:55 warnes * [r185] src/rpymodule.c: Fixes bug "[ 1238226 ] rpymodule.c needs updating for R 2.1.1 or later" (win32-specific) 2005-07-14 18:46 warnes * [r184] INSTALL.UNIX, INSTALL.WINDOWS, README: Move installation instructions to separate files. 2005-07-14 17:45 warnes * [r183] tests/test_cleanup.py, tests/testall.py: Fix typo in test_cleanup, remove special case for test_cleanup in testall.py 2005-07-14 17:43 warnes * [r182] rpy.py, src/rpymodule.c, tests/test_cleanup.py, tests/test_init.py, tests/testscript_cleanup.py: - Move cleanup call to python finalization rather than R object deletion. - Split out testing of R init function from cleanup. - Improve cleanup testing by using a separate python script. 2005-07-14 06:37 warnes * [r181] NEWS, rpy.py, rpy_io.py, rpy_version.py, setup.py, src/RPy.h, src/io.c, src/rpymodule.c, tests/README, tests/test_cleanup.py, tests/test_io.py, tests/testall.py: New features - R source headers no longer needed, and are no longer included in the source package - The R interpreter is propely shutdown on python exit or deletion all references. This ensures that all temporary directories and files are removed Bug fixes: - Fix build error for R 2.0.0+ on Mac OSX ('darwin') - Previous versions of rpy have permitted multiple copies of the R interpreter wrapper to be instantiated (via "newR = rpy.R()" ). However R's design imposes a limit of one interpreter per python process. To avoid confusion on this point, attempts to instantate more than one R interpreter object will now generate RuntimeError exceptions. - r.help() now works as expected by users. Behind the scenes: - Some work has been done "under the hood" to allow an R interpreter to be shut down and then started up again. This is *not* currently working. 2005-01-04 15:12 warnes * [r174] src/rpymodule.c: - Remove 'statichere' prefix of Robj_Type definition to resolve build error under gcc 4.0. ('staticforward' and 'statichere' are used for defining and referencing static forward definitions, respectively. Here, however, the definition of Robj_Type is the first and only definitition.) 2004-12-23 00:13 warnes * [r172] TODO: Add a couple of items, enhance format. 2004-12-23 00:01 warnes * [r171] rpy.py, rpy_version.py, setup.py: - Provide version of getstatuscommands for windows. Other trivial changes. 2004-11-08 18:03 warnes * [r160] rpy_version.py: Make that version 0.4.0! 2004-11-08 18:02 warnes * [r159] NEWS: Update for 0.4.0 2004-11-08 17:59 warnes * [r158] rpy_version.py: Update version number for 0.4.0. 2004-11-08 17:58 warnes * [r157] README, setup.py: We now attempt to bundle the R header files needed to compile rpy. 2004-11-08 15:43 warnes * [r156] setup.py: One more change for R 2.0.0: libR.so now lives in $RHOME/lib rather than $RHOME/bin. 2004-11-02 00:27 nj7w * [r152] rpy_version.py: Update version number 2004-11-02 00:09 nj7w * [r151] NEWS: Update for release 0.3.6. 2004-11-01 23:56 nj7w * [r150] README, setup.py: Improve Windows installation instructions & fix minor build problem. 2004-10-23 01:55 warnes * [r149] rpy_version.py, src/RPy.h, src/rpymodule.c: Second attempt to get support for R 2.0.0 working. 2004-10-22 13:06 warnes * [r148] src/R_eval.c, src/rpymodule.c: Commit changes for compatibility with (bug? in) R 2.0.0 2004-10-08 15:52 warnes * [r147] src/RPy.h, src/rpymodule.c: - Remove some redundant includes from rpymodule.c - Add 'getRHOME' function (not yet used). 2004-09-13 21:27 warnes * [r144] setup.py: Fix new typo. 2004-09-13 21:22 warnes * [r143] README, setup.py, src/rpymodule.c: - Changes to fix compilation under Windows. - Fix for typo in rpymodule.c 2004-08-23 21:18 warnes * [r142] doc/manual.texi: Fixed typos. 2004-06-14 20:59 warnes * [r141] src/RPy.h: Add Startup.h to unix build as well. 2004-06-14 20:56 warnes * [r140] src/rpymodule.c: Replace Python comment character with C comment character. grrr. 2004-06-14 20:08 warnes * [r139] setup.py, src/rpymodule.c: Fix segfault on run due to strangeness in quoting C DEFINES at build time. 2004-04-22 18:42 warnes * [r138] setup.py: Add configuration case for OSF to resolve linker problem reported by Andrew Hill . 2004-02-27 17:05 warnes * [r137] rpy_io.py: Undelete. 2004-02-27 04:48 warnes * [r135] undelete.csh: Remove extraneous file. 2004-02-27 04:47 warnes * [r134] COPYING, MANIFEST.in, README, TODO, debian/changelog, debian/control, debian/copyright, debian/rules, doc/Makefile, doc/README, doc/defs.texi, doc/manual.texi, examples/README, examples/animation.py, examples/chisquared.py, examples/faithful.dat, examples/faithful.py, examples/useful/dataframe.py, examples/useful/erobj.py, rpy.py, rpy_io.py, rpy_version.py, setup.py, src/RPy.h, src/R_eval.c, src/io.c, src/robjobject.h, src/rpymodule.c, src/setenv.c, src/setenv.h, tests/README, tests/table.txt, tests/test_array.py, tests/test_boolean.py, tests/test_io.py, tests/test_modes.py, tests/test_numeric.py, tests/test_robj.py, tests/test_sigint.py, tests/test_topy.py, tests/test_tor.py, tests/test_util.py, tests/testall.py: - Remove windows line endings from files. - Fix incorrect code for darwin build include in the windows changes. - It appears that PRE_2_2 needs to be set for 2.3 as well as 2.1 for rpy to pass its unit tests. Does it need to be set for 2.2 as well? (I don't have a 2.2 hand to test with.) 2004-02-27 03:32 warnes * [r133] NEWS: Correct NEWS file for 0.3.5. 2004-02-27 03:08 warnes * [r132] README.sav, rpy_version.pyc, src/io.c.bak, src/rpymodule.c.bak: Delete a few files accidentaly 'undeleted' 2004-02-27 03:01 warnes * [r131] rpy_version.pyc, src/io.c.bak, src/rpymodule.c.bak: Undelete File 2004-02-27 02:58 warnes * [r130] COPYING, MANIFEST.in, NEWS, README, TODO, debian, debian/changelog, debian/control, debian/copyright, debian/rules, doc, doc/Makefile, doc/README, doc/defs.texi, doc/manual.texi, examples/README, examples/animation.py, examples/chisquared.py, examples/faithful.dat, examples/faithful.py, examples/useful/dataframe.py, examples/useful/erobj.py, rpy.py, rpy_io.py, rpy_version.py, setup.py, src, src/RPy.h, src/R_eval.c, src/io.c, src/robjobject.h, src/rpymodule.c, src/setenv.c, src/setenv.h, tests, tests/README, tests/table.txt, tests/test_array.py, tests/test_boolean.py, tests/test_io.py, tests/test_modes.py, tests/test_numeric.py, tests/test_robj.py, tests/test_sigint.py, tests/test_topy.py, tests/test_tor.py, tests/test_util.py, tests/testall.py: Undelete file 2004-02-27 02:41 warnes * [r126] README.sav, undelete.csh: Initial revision 2004-02-27 02:08 warnes * [r125] README: Undelete. 2004-02-19 22:13 warnes * [r124] README: Add note that all Windows specific code has been integrated into the main rpy tree. 2004-02-19 22:12 warnes * [r123] .cvsignore, COPYING, MANIFEST.in, NEWS, README, TODO, debian, doc, rpy.py, rpy_io.py, rpy_version.py, setup.py, src, tests: The Windows code is now integrated into the main RPy tree, so these files are no longer necessary. 2004-02-19 18:10 warnes * [r121] NEWS: Updated NEWS entries for 0.3.5. 2004-02-18 03:02 warnes * [r113] rpy_version.py: Update version number for 0.3.5 release. 2004-02-18 03:01 warnes * [r112] MANIFEST.in: Exclude .tgz and .tar.gz files from being included in the distributed packages. 2004-02-17 18:48 warnes * [r111] src/R_eval.c, src/rpymodule.c: - Fix defintions of symbols used by other modules. These were incorrectly marked 'extern'. 2004-02-17 18:45 warnes * [r110] tests/test_sigint.py: Force win32 to pass test_signint test. 2004-02-17 18:15 warnes * [r109] setup.py: Jan de Leeuw recommends against -Xlinker -m, and indicates that -dynamic is the default. 2004-02-17 15:37 warnes * [r108] setup.py: Add linker flags that should enable rpy to build on Mac OS X (darwin). 2004-02-12 17:12 warnes * [r107] rpy_version.py, setup.py: More changes to allow building on Mac OSX. 2004-02-12 17:11 warnes * [r106] NEWS: Belated checkin of changes for RPy 0.3.4. 2004-02-12 02:37 warnes * [r105] src/RPy.h, src/R_eval.c, src/rpymodule.c: - Mark all variable definitions in headers 'extern', and place actual definitions in the appropriate source file. This should permit compilation on Max OSX. 2004-02-10 20:57 warnes * [r104] setup.py: Patch to add build info for Mac OSX, submitted by Christopher Fonnesbeck . Its not yet quite right, but a step in the right direction. 2004-02-04 21:26 warnes * [r95] rpy.py, setup.py: Finish renaming io.py to rpy_io.py. 2004-02-04 21:20 warnes * [r94] rpy.py: Fix crash on startup under win32 due to a typo that caused the wrong event-loop code to be executed.. 2004-02-04 21:10 warnes * [r93] io.py, rpy_io.py: Renamed io.py to rpy_io.py to prevent conflict with a file in the python-stats package. 2004-02-04 21:06 warnes * [r92] debian, debian/changelog, debian/control, debian/copyright, debian/rules: Add debian packaging files provided by Dirk Eddelbuettel. 2004-01-21 06:25 warnes * [r86] MANIFEST.in: - Add a couple of trash file types to be excluded from build packages 2004-01-21 06:18 warnes * [r85] MANIFEST.in: Make sure that the dist/ subdirectory doesn't get included in the source packages, otherwise we get HUGE packages because they include all previous packages. 2004-01-21 05:59 warnes * [r84] tests/test_robj.py: Fix test of lcall. 2004-01-21 05:53 warnes * [r83] rpy_version.py: - Update version number for release. 2004-01-21 05:50 warnes * [r82] src/RPy.h: Undo last change: remove #undef because it caused compile faulures in older python versions. 2004-01-21 05:42 warnes * [r81] tests/test_array.py, tests/test_boolean.py, tests/test_io.py, tests/test_modes.py, tests/test_numeric.py, tests/test_robj.py, tests/test_sigint.py, tests/test_topy.py, tests/test_tor.py, tests/test_util.py: Modify tests so that they operate on the local rpy rather than the system installed copy. This makes it a lot easier to test changes. 2004-01-21 05:40 warnes * [r80] src/RPy.h: Avoid warning message by undefining _FILE_OFFSET_BITS to avoid conflict between system defintion and python's definition. 2004-01-21 05:34 warnes * [r79] setup.py: Added runtime_library_dirs so that the rpy shared library _rpy.so includes the ncessary path to the R shared library Rlib.so. This ensures that Rlib.so will be found even if it is not in LD_LIBRARY_PATH. 2004-01-16 06:43 warnes * [r64] NEWS, README, TODO: Update text documentation files. 2004-01-16 06:43 warnes * [r63] doc/Makefile: Expand shell alternative patterns "foo.{bar,baz}" to "foo.bar foo.baz" because some shells used by make don't handle the former properly (eg, sh on Solaris 9). Add ignore return value flag (prepend '-') to "rm" commands, since absence of the file to be deleted is not a problem. 2004-01-16 06:38 warnes * [r62] doc/manual.texi: *** empty log message *** 2004-01-16 06:33 warnes * [r61] tests/test_robj.py: Improve documentation for lcall. Modify unit test for lcall to be simpler. 2004-01-16 05:06 warnes * [r60] doc/manual.texi: Fix typos in manual.texi. 2004-01-16 05:04 warnes * [r59] doc/manual.texi: Add documentation of lcall method. 2004-01-16 05:00 warnes * [r58] src/rpymodule.c, tests/test_robj.py: Integrate patch #720222: new RObj method 'lcall', which provides an 'lcall' method for calling objects with a list of (name,value) arguments. This allows the programmer to work around Python's use of *unordered* dictionaries for named arguments. 2004-01-15 22:55 warnes * [r57] rpy_version.py, src/R_eval.c, src/rpymodule.c, src/setenv.c: Minor changes for release of version 3.3. 2004-01-15 22:54 warnes * [r56] setup.py: Add quotes to allow for special characters in RHOME path. 2004-01-15 22:51 warnes * [r55] tests/test_sigint.py: Rewrite to put signal sender code into a function. Works now ?! 2004-01-15 22:45 warnes * [r54] tests/test_modes.py: Fix error in unit test. 2004-01-15 18:14 warnes * [r51] README, doc/Makefile: Added the creating of manual_html.tgz for the web site. 2004-01-08 16:56 warnes * [r46] rpy_version.py, src/rpymodule.c: Fix bug under Unix due to Win32 changes. 2004-01-08 16:18 warnes * [r45] README, rpy.py, rpy_version.py, setup.py, src/R_eval.c, src/io.c, src/robjobject.h, src/rpymodule.c, src/setenv.c, src/setenv.h, win, win/.cvsignore, win/readme, win/setup.py, win/src/RPy.h, win/src/R_eval.c, win/src/setenv.c, win/version: - Changes to work with R 1.8.X - First attempt to integrate Windows changes into Unix source tree - Additional information for building under windows 2003-03-17 23:46 wall_m * [r44] src/rpymodule.c: Fixed a bug with the R's gc. It solves the problems with large chunks of data. 2003-02-15 20:05 wall_m * [r42] README: Fixed wrong version 2003-02-15 19:52 wall_m * [r40] NEWS: Updated 2003-02-15 19:23 wall_m * [r38] src/rpymodule.c: Changed the sync mechanism to a lock. 2003-02-15 19:19 wall_m * [r37] doc/manual.texi: Some explanations about r('...') and r_events. 2003-02-15 19:18 wall_m * [r36] setup.py: Using the rpy_version module. 2003-02-15 19:17 wall_m * [r35] VERSION, rpy_version.py: Changed VERSION for a module, easier to import. 2003-02-15 19:16 wall_m * [r34] rpy.py: Now, using a lock to sync with R_eval. A lot faster. 2003-02-15 19:15 wall_m * [r33] README: Added Kelley's contrib and fixed the minimum R version. 2003-02-10 23:32 wall_m * [r27] src/io.c: * Fixed thread problems with Python i/o callbacks. * Enabled the event loop when reading input. 2003-02-10 23:29 wall_m * [r26] src/RPy.h: Added declarations. 2003-02-10 23:17 wall_m * [r25] MANIFEST.in: Some fixes. 2003-02-10 23:10 wall_m * [r24] setup.py: When building a source distro, substitute $VERSION$ with the VERSION file content. 2003-02-10 23:08 wall_m * [r23] src/R_eval.c: * Events are disables before entering R and enabled after leaving R. * If the event loop is stopped, the enable/disable doesn't happen, which speed up things a lot. * Fixed a bug in do_eval_expr (executing Python code after changing the SIGINT handler). 2003-02-10 22:52 wall_m * [r22] src/rpymodule.c: * Fixed a bug about executing Python code with a wrong SIGINT handler, in do_eval_expr. * Added handling of the event loop before and after the evaluation of R expresions. * Speed up in the evaluation of R expresion when the event loop is off. * Disable the event loop when R is not interactive. * Imported the rpy namespace, for easier access to the Python functions. 2003-02-10 22:46 wall_m * [r21] rpy.py: Fixed the start/stop_r_eventloop problems. 2003-02-10 21:40 wall_m * [r20] README: Added win32all URL. 2002-11-19 20:43 wall_m * [r19] MANIFEST, MANIFEST.in, NEWS, README, TODO, VERSION, doc/README, doc/manual.texi, io.py, rpy.py, setup.py, src/RPy.h, src/R_eval.c, src/io.c, src/robjobject.h, src/rpymodule.c, src/setenv.c, src/setenv.h, tests/test_boolean.py, tests/test_io.py, tests/test_sigint.py, tests/test_topy.py: Release 0.3, see the release notes or the NEWS file for changes since 0.2. Modified Files: NEWS README TODO VERSION rpy.py setup.py doc/README doc/manual.texi src/RPy.h src/R_eval.c src/robjobject.h src/rpymodule.c tests/test_topy.py Added Files: MANIFEST.in io.py src/io.c src/setenv.c src/setenv.h tests/test_boolean.py tests/test_io.py tests/test_sigint.py Removed Files: MANIFEST 2002-04-12 16:20 wall_m * [r18] NEWS, VERSION, tests, tests/.cvsignore: Added Files: NEWS VERSION tests/.cvsignore 2002-04-12 16:18 wall_m * [r17] MANIFEST, README, RPy.h, R_eval.c, TODO, USING, doc, doc/Makefile, doc/README, doc/defs.texi, doc/manual.texi, examples, examples/README, examples/animation.py, examples/chisquared.py, examples/faithful.dat, examples/faithful.py, examples/useful, examples/useful/dataframe.py, examples/useful/erobj.py, robjobject.h, rpy.py, rpymodule.c, setup.py, src, src/RPy.h, src/R_eval.c, src/robjobject.h, src/rpymodule.c, test-array.py, test-numeric.py, test.py, tests, tests/README, tests/table.txt, tests/test_array.py, tests/test_modes.py, tests/test_numeric.py, tests/test_robj.py, tests/test_topy.py, tests/test_tor.py, tests/test_util.py, tests/testall.py: Big changes and reorganization. Due to being working in my own repository, history is not available. 2002-03-18 18:02 wall_m * [r16] test-array.py, test-numeric.py: Fixed nested_scopes for version 2.1 2002-03-18 17:59 wall_m * [r15] rpymodule.c: Fixed a C function call which is not in the 2.1 API 2002-03-18 17:21 wall_m * [r14] rpymodule.c: Lot of changes. * Added conversion from/to Numeric when available * Fixed the conversion of data frames * Added the conversion of R arrays from/to list of lists of ... in the case when Numeric is not available 2002-03-18 14:03 wall_m * [r13] rpy.py, rpymodule.c: Import Numeric when available Fixed a bug in conversion of names. 2002-03-18 14:01 wall_m * [r12] setup.py: Added the detection of Numeric. 2002-03-18 13:58 wall_m * [r11] USING: Fixed minor typo. 2002-03-18 13:53 wall_m * [r10] RPy.h: Added the include of Numeric header when available. Added the declaration of Rf_initEmbeddedR. 2002-03-18 13:35 wall_m * [r9] robjobject.h, test-array.py, test-numeric.py, test.py: Added Files: robjobject.h test-array.py test-numeric.py test.py 2002-03-13 18:38 wall_m * [r8] rpymodule.c: * Fixed several important bugs. o Added a list for saving anonymous R objects o Added several PROTECT's which were missing o Fixed a bug related to signals that, when catch by R, makes Python seg fault 2002-03-09 03:01 wall_m * [r4] ., .cvsignore, COPYING, MANIFEST, README, RPy.h, R_eval.c, TODO, USING, rpy.py, rpymodule.c, setup.py: Initial revision rpy-1.0.3/debian/0000755000076700000240000000000011012207656012733 5ustar warnesstaffrpy-1.0.3/debian/changelog0000644000076700000240000003445310772312061014615 0ustar warnesstaffrpy (1.0.1-2) unstable; urgency=low * doc/rpy.texi: Corrected R plot() example, also committed to upstream SVN archive. (Closes: #461923) * debian/control: Updated Standards-Version: to current value. -- Dirk Eddelbuettel Mon, 21 Jan 2008 10:01:56 -0600 rpy (1.0.1-1) unstable; urgency=low * New upstream release announced today * debian/control: Update Depends: on r-base-core to (>= 2.6.1) -- Dirk Eddelbuettel Thu, 29 Nov 2007 20:59:55 -0600 rpy (1.0.0-3) unstable; urgency=low * Rebuilt for R 2.6.1 * debian/control: Updated (Build-)Depends accordingly -- Dirk Eddelbuettel Mon, 26 Nov 2007 20:04:09 -0600 rpy (1.0.0-2) unstable; urgency=low * debian/control: Add texlive-latex-base to Build-Depends: (Closes: #452675) -- Dirk Eddelbuettel Sat, 24 Nov 2007 08:29:14 -0600 rpy (1.0.0-1) unstable; urgency=low * New upstream release announced today * debian/control: Update Depends: on r-base-core to (>= 2.6.0) but remove the (<< 2.7.0) so that rpy should not prevent R from entering testing -- Dirk Eddelbuettel Mon, 19 Nov 2007 16:51:59 -0600 rpy (1.0~rc3-3) unstable; urgency=low * src/{RPy.h,rpymodule.c},setup.py,tests/test_tor.py: Applied amd64 patch posted by Matthew Brett to the rpy list (Closes: #443147) * debian/control: Update Build-Depends to 'r-base-dev (>= 2.6.0)' and Depends to 'r-base-core (>= 2.6.0), r-base-core (<< 2.7.0)' -- Dirk Eddelbuettel Thu, 25 Oct 2007 10:27:42 -0500 rpy (1.0~rc3-2) unstable; urgency=low * Rebuilt for R 2.6.0 (Closes: #443066) * debian/control: Update Build-Depends to 'r-base-dev (>> 2.5.1)' and Depends to 'r-base-core (>> 2.5.1), r-base-core (<< 2.6.1)' -- Dirk Eddelbuettel Tue, 18 Sep 2007 09:19:30 -0500 rpy (1.0~rc3-1) unstable; urgency=low * New upstream release * debian/control: Set (Build-)Depends: on 'r-base-core (>= 2.5.1)', but keep Depends on r-base-core (<< 2.5.2)' * debian/control: Switch from python-numeric to python-numpy-dev which is now supported upstream -- Dirk Eddelbuettel Thu, 28 Jun 2007 21:56:45 -0500 rpy (1.0~rc2-1) unstable; urgency=low * New upstream release, but carry over patch from #401670 * Rebuilt under release candidate for R 2.5.1 (Closes: #430645) * debian/control: Set Built-Depends: on 'r-base-core (>= 2.5.1~20070622)' * debian/control: Set Depends: on 'r-base-core (>= 2.5.1~20070622), r-base-core (<< 2.5.2)' to prevent breaks with new R versions -- Dirk Eddelbuettel Tue, 26 Jun 2007 09:06:14 -0500 rpy (1.0~rc1-6) unstable; urgency=low * Rebuilt under R version 2.5.0 released yesterday * debian/control: (Built-)Depends: on (r-base-core >= 2.5.0) -- Dirk Eddelbuettel Wed, 25 Apr 2007 12:53:57 -0500 rpy (1.0~rc1-5) unstable; urgency=low * src/rpymodule.c: Applied patch (from rpy-list) created by Andrew McNamara that resolves the C stack limit error produced by R in some contexts, such as resizing the x11() window. (Closes: #401670) -- Dirk Eddelbuettel Mon, 12 Mar 2007 21:06:40 -0500 rpy (1.0~rc1-4) unstable; urgency=low * Rebuilt under current R version 2.4.1 (Closes: #404636) * debian/control: (Built-)Depends: on (r-base-core >= 2.4.1) -- Dirk Eddelbuettel Wed, 27 Dec 2006 10:03:08 -0600 rpy (1.0~rc1-3) unstable; urgency=low * Rebuilt under current R-patched version of R 2.4.0 * debian/control: (Built-)Depends: on (r-base-core >= 2.4.0) -- Dirk Eddelbuettel Tue, 5 Dec 2006 20:59:00 -0600 rpy (1.0~rc1-2) unstable; urgency=low * Rebuilt under the release candidate of R 2.4.0 * debian/control: (Built-)Depends: on (r-base-core >> 2.3.1) -- Dirk Eddelbuettel Thu, 28 Sep 2006 20:55:10 -0500 rpy (1.0~rc1-1) unstable; urgency=low * New upstream release * debian/control: Build-Depends: now 'python-central (>= 0.5)' [lintian] * debian/python-rpy.preinst: Added debhelper token [lintian] -- Dirk Eddelbuettel Thu, 14 Sep 2006 16:32:43 -0500 rpy (0.99.2-5) unstable; urgency=low * debian/rules: Call dh_installdeb after dh_pycentral (Closes: #378755) * debian/python-rpy.preinst: Added, remove old instances of .pyc or .pyo files if found; add stanza for dh_pycentral. * debian/python-rpy.{postinst,prerm}: Added as stanza for dh_pycentral -- Dirk Eddelbuettel Wed, 19 Jul 2006 18:50:27 -0500 rpy (0.99.2-4) unstable; urgency=low * Updated according to http://wiki.debian.org/DebianPython/NewPolicy for the New Python Policy (Closes: #373378) * debian/pycompat: created * debian/control: - new fields XS-Python-Version and XB-Python-Version - replaced python2.{3,4}-rpy packages with python-rpy - added ${python:Depends} to Depends: - added python-central to Build-Depends: - updated versioned Depends and Build-Depends: - added Provides: ${python:Provides} * debian/rules: Added dh_pycentral call -- Dirk Eddelbuettel Tue, 20 Jun 2006 20:20:55 -0500 rpy (0.99.2-3) unstable; urgency=low * Rebuilt under the pre-release for R 2.3.1 (Closes: #368624) * debian/control: (Build-)Depends: now on 'r-base-core (>= 2.3.0.svn38119)' and Depends: also on 'r-base-core (<< 2.4.0)' * debian/control: Upgraded Standards-Version to 3.7.2 -- Dirk Eddelbuettel Tue, 23 May 2006 10:45:29 -0500 rpy (0.99.2-2) unstable; urgency=low * Rebuilt under R 2.3.0 * debian/control: Updated Depends: for python2.{3,4}-rpy on r-base-core to '>= 2.3.0' and '<< 2.3.1' (Closes: #364893) * debian/control: Updated Build-Depends: for r-base-core to '>= 2.3.0' -- Dirk Eddelbuettel Thu, 27 Apr 2006 12:55:18 -0500 rpy (0.99.2-1) unstable; urgency=low * New upstream release * rpy_tools.py: Patch reg.exp. for R version to allow R 2.3.0 pre-release * doc/{defs,rpy}.texi: Carry over patches from 0.99.1 -- Dirk Eddelbuettel Wed, 5 Apr 2006 19:08:52 -0500 rpy (0.99.1-1) unstable; urgency=low * New upstream release * doc/{defs,rpy}.texi: Small patches to allow complete Debian build * debian/copyright: Updated to reflect new choice of MPL, GPL or LGPL -- Dirk Eddelbuettel Fri, 24 Mar 2006 16:36:30 -0600 rpy (0.99.0-1) unstable; urgency=low * New upstream release, including the debian/rules patch by Greg * debian/rules: Patch by Greg to not require setup.py changes * debian/rules: Small updates for changed names of some documentation files * debian/python-rpy-doc.doc-base: Changed to rpy_html/ directory name * debian/rules: Small updates to clean target -- Dirk Eddelbuettel Thu, 16 Mar 2006 13:50:25 -0600 rpy (0.4.6-4) unstable; urgency=low * setup.py: Added os.path.join(RHOME.strip(), '../../share/R/include'), to include_dirs in 'else' branch for Linux/Solaris as we now have include directories in /usr/share/R/include instead of the previous location of /usr/lib/R/include aka $RHOME/include (Closes: #356849) -- Dirk Eddelbuettel Tue, 14 Mar 2006 19:21:52 -0600 rpy (0.4.6-3) unstable; urgency=low * Rebuilt for R 2.2.1 * debian/control: Depends: for r-base-core updated to (>= 2.2.1), also added (<< 2.2.2) to ensure packages stay in sync with their R version * debian/rules: Set DH_COMPAT=4 -- Dirk Eddelbuettel Tue, 20 Dec 2005 21:30:07 -0600 rpy (0.4.6-2) unstable; urgency=low * Rebuilt for R 2.2.0 (Closes: #330213) * debian/control: Depends: for r-base-core updated to (>= 2.2.0), also added (<< 2.2.1) to ensure packages stay in sync with their R version -- Dirk Eddelbuettel Wed, 2 Nov 2005 17:51:59 -0600 rpy (0.4.6-1) unstable; urgency=low * New upstream release -- Dirk Eddelbuettel Thu, 28 Jul 2005 19:22:37 -0500 rpy (0.4.5-1) unstable; urgency=low * New upstream release -- Dirk Eddelbuettel Mon, 25 Jul 2005 19:41:23 -0500 rpy (0.4.4-1) unstable; urgency=low * New upstream release -- Dirk Eddelbuettel Sat, 23 Jul 2005 06:09:11 -0500 rpy (0.4.3-1) unstable; urgency=low * New upstream release -- Dirk Eddelbuettel Wed, 20 Jul 2005 22:29:21 -0500 rpy (0.4.2.1-2) unstable; urgency=low * debian/control: Updated Build-Depends and removed python2.2-numeric which no longer exists in Debian's unstable distribution (Closes: #318199) * debian/control: Removed entry for Python 2.2 version of rpy * debian/rules: Deactivated invocation of Python 2.2 build * R-2.1.1/src/include/* copied in from current R-2.1.1 sources * debian/control: Upgraded to 3.6.2.1 -- Dirk Eddelbuettel Sat, 16 Jul 2005 22:05:05 -0500 rpy (0.4.2.1-1) unstable; urgency=low * New upstream version released today * This version contains the R 2.1.0 headers missing in 0.4.2 -- Dirk Eddelbuettel Tue, 24 May 2005 21:50:51 -0500 rpy (0.4.2-1) unstable; urgency=low * New upstream version released today * R-2.1.0/src/include/* copied in from current R-2.1.0 sources as an upstream snafu accidently lead to omitting this directory -- Dirk Eddelbuettel Mon, 23 May 2005 21:16:38 -0500 rpy (0.4.1-4) unstable; urgency=low * src/rpymodules.c: Apply one-line patch from Andreas Jochens to compile under gcc 4.0; patch has long been in upstream CVS (Closes: #288442) * Rebuilt under R 2.1.0 -- Dirk Eddelbuettel Sat, 23 Apr 2005 14:25:55 -0500 rpy (0.4.1-3) unstable; urgency=low * debian/rules: Add 'cd doc/ && make all' for pdf, html + info versions of the RPy manual, and install all into the -doc package. (Closes: #304498) * debian/control: Added 'texinfo, texi2html, tetex-extra' to Build-Depends * debian/python-rpy-doc.{prerm, postinst}: Added to call install-info for rpy * debian/python-rpy-doc.doc-base: Added to register html files with doc-base * R-2.1.0/: Copied src/include directory from R 2.1.0 release candidate -- Dirk Eddelbuettel Sun, 17 Apr 2005 18:35:49 -0500 rpy (0.4.1-2) unstable; urgency=low * debian/control: Also provide a version for Python 2.4: (Closes: #292556) - Adjusted Build-Depends - Added new section * debian/rules: Adjusted accordingly. * Thanks to Faheem Mitha for an almost complete patch implementing this -- Dirk Eddelbuettel Sat, 29 Jan 2005 22:49:23 -0600 rpy (0.4.1-1) unstable; urgency=low * New upstream release pre-release with R 2.0.1 support (Closes: #287191) -- Dirk Eddelbuettel Mon, 27 Dec 2004 09:04:43 -0600 rpy (0.4.0-1) unstable; urgency=low * New upstream release, incorporating some changes we suggested after 0.3.6 -- Dirk Eddelbuettel Mon, 8 Nov 2004 21:25:38 -0600 rpy (0.3.6-1) unstable; urgency=low * New upstream release * This upstream release now requires access to the header files in the R source tree, not only those include in the binary packages * For this reason, we added $R_SRC/src/include/ as R-2.0.0/src/include/ * debian/rules: Add the new required R_SRC=R-2.0.0/ * setup.py: Apply the same patch from the previous release to look for libR.so in $R_HOME/lib, not in $R_HOME/bin as for pre-2.0.0 R * debian/watch: Added watch file -- Dirk Eddelbuettel Sat, 6 Nov 2004 21:27:56 -0600 rpy (0.3.5-5) unstable; urgency=low * Rebuilt under R 2.0.0 per Graham Williams' suggestion (Closes: #276055) * debian/control: Updated Depends: and Build-Depends: accordingly * setup.py: Set r_libs = os.path.join(RHOME, 'lib') to build under R 2.0.0 -- Dirk Eddelbuettel Mon, 11 Oct 2004 18:33:52 -0500 rpy (0.3.5-4) unstable; urgency=low * debian/rules: Added dh_python call * debian/control: Added python to Build-Depends -- Dirk Eddelbuettel Tue, 27 Jul 2004 18:19:28 -0500 rpy (0.3.5-3) unstable; urgency=low * debian/control: Added "python2.2-numeric, python2.3-numeric" to Build-Depends to enable direct array transfer (Closes: #261744) * debian/control: Also added accordingly to Depends for 2.2 and 2.3 * debian/control: Upgraded Standards-Version to 3.6.1.1 -- Dirk Eddelbuettel Tue, 27 Jul 2004 17:33:20 -0500 rpy (0.3.5-2) unstable; urgency=low * debian/control: Depends: r-base-core for python2.*-rpy (Closes: #250071) * debian/control: Section for python-rpy-doc changed to doc per override -- Dirk Eddelbuettel Thu, 17 Jun 2004 21:17:43 -0500 rpy (0.3.5-1) unstable; urgency=low * New upstream release -- Dirk Eddelbuettel Tue, 2 Mar 2004 20:52:43 -0600 rpy (0.3.4-2) unstable; urgency=low * io.py: Renamed to rpyio.py * setup.py, rpy.py: Adjusted to import and call rpyio instead of io * These changes should resolve the clash with python-stats (Closes: #231051) * debian/control: Renamed doc package to python-rpy-doc and set appropriate Provides:, Conflicts: and Replaces: entries for python-rpy-docs for upgrade -- Dirk Eddelbuettel Wed, 4 Feb 2004 10:48:49 -0600 rpy (0.3.4-1) unstable; urgency=low * New upstream release * The upstream releases now links with -rpath so that /usr/lib/R/bin/libR.so will be found without requiring either editing /etc/ld.so.conf or setting LD_LIBRARY_PATH which enables the package to work as is on Debian. * Converted the previously unpublished private package 'rpy' into a set of four (hopefully :) Python Policy conformant packages python-rpy, python-rpy-docs, python2.2-rpy and python2.3-rpy. Building with python2.1 did not work as expected, and a package may be added at a future date. -- Dirk Eddelbuettel Thu, 22 Jan 2004 22:36:06 -0600 rpy (0.3.3-1) unstable; urgency=low * New upstream release [ not uploaded to Debian ] -- Dirk Eddelbuettel Sat, 17 Jan 2004 10:31:11 -0600 rpy (0.3.1-1) unstable; urgency=low * Initial Debianisation [ not actually uploaded to Debian ] * src/{RPy.h,R_eval.c}: s/jump_now(void)/Rf_onintr(void)/ to reflect an internal change in R * Still needs LD_LIBRARY_PATH / ld.so.conf to point to /usr/lib/R/bin -- Dirk Eddelbuettel Wed, 17 Sep 2003 20:36:43 -0500 rpy-1.0.3/debian/compat0000644000076700000240000000000210723662125014135 0ustar warnesstaff5 rpy-1.0.3/debian/control0000644000076700000240000000316510772312061014342 0ustar warnesstaffSource: rpy Section: python Priority: optional Maintainer: Dirk Eddelbuettel Standards-Version: 3.7.3 XS-Python-Version: all Build-Depends: debhelper (>= 5.0.37.2), r-base-dev (>= 2.6.1), python-all-dev (>= 2.3.5-10), python-numpy, python-numpy-dev, texinfo, texi2html, texlive-base, texlive-latex-base, python-central (>= 0.5) Package: python-rpy Architecture: any Depends: ${shlibs:Depends}, ${python:Depends}, python-numpy, r-base-core (>= 2.6.1) Replaces: python2.2-rpy (<< 0.99.2-4), python2.3-rpy (<< 0.99.2-4), python2.4-rpy (<< 0.99.2-4) Conflicts: python2.2-rpy (<< 0.99.2-4), python2.3-rpy (<< 0.99.2-4), python2.4-rpy (<< 0.99.2-4) XB-Python-Version: ${python:Versions} Provides: ${python:Provides} Suggests: python-rpy-docs Description: Python interface to the GNU R language and environment This Debian package provides RPy, a very simple yet robust Python interface to the GNU R Programming Language. It can manage different types of R objects, and can execute arbitrary R functions, including graphic functions. . URL: http://rpy.sourceforge.net/ Package: python-rpy-doc Replaces: python-rpy-docs Provides: python-rpy-docs Conflicts: python-rpy-docs Architecture: all Section: doc Description: Python interface to the GNU R language (documentation package) This Debian package provides RPy, a very simple yet robust Python interface to the GNU R Programming Language. It can manage different types of R objects, and can execute arbitrary R functions, including graphic functions. . This Debian package contains documentation and examples from the rpy source package. . URL: http://rpy.sourceforge.net/ rpy-1.0.3/debian/copyright0000644000076700000240000000503110411117033014654 0ustar warnesstaffThis is the Debian GNU/Linux r-noncran-rpy package of RPy, a package providing an interface between the R and the Python languages and environments. RPy was initially written by Walter Moreira, and is now maintained by Gregory R. Warnes. This package was created by Dirk Eddelbuettel . The sources where downloaded from a sourceforge mirror website at http://umn.dl.sourceforge.net/sourceforge/rpy/ RPy is copyright by Walter Moreira and Gregory R. Warnes and was originally licensed under the GPL as described. As of version 0.99.1, RPy is now licensed under a choice of MPL, GPL and LGPL. The following code is provided in the upstream sources as section 7 of the top-level README, as well as in HEADER.c and HEADER.py: RPy is subject to the Mozilla Public License Version 1.1 (the "License"); you may not use RPy except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ (or see the file MPL_LICENSE) Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the RPy python module. The Initial Developer of the Original Code is Walter Moreira. Portions created by the Initial Developer are Copyright (C) 2002 the Initial Developer. All Rights Reserved. Contributor(s): Gregory R. Warnes (Maintainer) Alternatively, RPy may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL", see the file GPL_LICENSE), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL", see the file LGPL_LICENSE), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. On a Debian GNU/Linux system, the MPL, GPL and LGPL licenses are included under their names in the directory /usr/share/common-licenses/ . rpy-1.0.3/debian/overrides0000644000076700000240000000051310772312061014656 0ustar warnesstaffpython-rpy: script-not-executable ./usr/share/pycentral/python-rpy/site-packages/rpy_options.py python-rpy: binary-or-shlib-defines-rpath ./usr/lib/python2.4/site-packages/_rpy2061.so /usr/lib/R/bin:/usr/lib/R/lib python-rpy: binary-or-shlib-defines-rpath ./usr/lib/python2.5/site-packages/_rpy2061.so /usr/lib/R/bin:/usr/lib/R/librpy-1.0.3/debian/pycompat0000644000076700000240000000000210526147137014510 0ustar warnesstaff2 rpy-1.0.3/debian/python-rpy-doc.doc-base0000644000076700000240000000060110411117033017212 0ustar warnesstaffDocument: python-rpy-doc.doc-base Title: The RPy Reference Manual in html format Author: Walter Moreira and Gregory R. Warnes Abstract: This is the reference manual for RPy, a Python extension module for using the R programming language. Section: Apps/Math Format: HTML Index: /usr/share/doc/python-rpy-doc/rpy_html/index.html Files: /usr/share/doc/python-rpy-doc/rpy_html/*.html rpy-1.0.3/debian/python-rpy-doc.postinst0000644000076700000240000000074310411116613017432 0ustar warnesstaff#!/bin/sh # # postinst script for the Debian GNU/Linux python-roy-doc package # # Dirk Eddelbuettel set -e #DEBHELPER# case "$1" in configure) install-info --quiet --section "Math" "RPy" \ --description="The RPy Reference Manual."\ /usr/share/info/rpy.info.gz ;; abort-upgrade|abort-remove|abort-deconfigure) ;; *) echo "postinst called with unknown argument \`$1'" >&2 ;; esac exit 0 rpy-1.0.3/debian/python-rpy-doc.prerm0000644000076700000240000000063310411116613016672 0ustar warnesstaff#!/bin/sh # # prerm script for the Debian GNU/Linux python-roy-doc package # # Dirk Eddelbuettel set -e #DEBHELPER# case "$1" in remove|purge) install-info --quiet --remove rpy ;; upgrade) ;; failed-upgrade|abort-install|abort-upgrade|disappear) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 0 ;; esac rpy-1.0.3/debian/python-rpy.postinst0000644000076700000240000000056010526147137016700 0ustar warnesstaff#!/bin/sh # # postinst script for the Debian GNU/Linux python-rpy package # # Copyright 2006 by Dirk Eddelbuettel set -e #DEBHELPER# case "$1" in configure) ;; abort-upgrade|abort-remove|abort-deconfigure) ;; *) echo "postinst called with unknown argument \`$1'" >&2 ;; esac exit 0 rpy-1.0.3/debian/python-rpy.preinst0000644000076700000240000000115710526147137016504 0ustar warnesstaff#!/bin/sh # # prerinst script for the Debian GNU/Linux python-rpy package # # Copyright 2006 by Dirk Eddelbuettel set -e #DEBHELPER# case "$1" in install|upgrade) for f in rpy rpy_io rpy_options rpy_tools rpy_versions rpy_wintools; do for e in pyc pyo; do for v in 2.3 2.4; do if [ -f /usr/lib/python$v/site-packages/$f.$e ]; then rm -fv /usr/lib/python$v/site-packages/$f.$e fi done done done ;; abort-upgrade|disappear) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 0 ;; esac exit 0 rpy-1.0.3/debian/python-rpy.prerm0000644000076700000240000000057210526147137016145 0ustar warnesstaff#!/bin/sh # # prerm script for the Debian GNU/Linux python-rpy package # # Copyright 2006 by Dirk Eddelbuettel set -e #DEBHELPER# case "$1" in remove|purge) ;; upgrade) ;; failed-upgrade|abort-install|abort-upgrade|disappear) ;; *) echo "prerm called with unknown argument \`$1'" >&2 exit 0 ;; esac rpy-1.0.3/debian/rules0000644000076700000240000000703310772312061014012 0ustar warnesstaff#!/usr/bin/make -f # debian/rules file for the Debian GNU/Linux python-rpy package # Copyright 2004 - 2007 by Dirk Eddelbuettel package := python-rpy debbase := $(CURDIR)/debian debtmp := $(debbase)/$(package) debdoc := debian/python-rpy-doc/usr/share/doc/python-rpy-doc lintiandir := $(debtmp)/usr/share/lintian/overrides #PYTHON2.1 := python2.1 #PYTHON2.2 := python2.2 #PYTHON2.3 := python2.3 #PYTHON2.4 := python2.4 PYVERS := $(shell pyversions -r debian/control) compilerflags = -O2 -Wall # Uncomment this to turn on verbose mode. # export DH_VERBOSE=1 get-orig-source: upstream upstream: links http://prdownloads.sourceforge.net/rpy/ configure: configure-stamp configure-stamp: dh_testdir touch configure-stamp build: configure-stamp build-stamp build-stamp: dh_testdir # CFLAGS="$(compilerflags)" $(PYTHON2.3) setup.py build \ # build_ext --include-dirs=/usr/share/R/include # CFLAGS="$(compilerflags)" $(PYTHON2.4) setup.py build \ # build_ext --include-dirs=/usr/share/R/include for python in $(PYVERS); \ do CFLAGS="$(compilerflags)" $$python setup.py build \ build_ext --include-dirs=/usr/share/R/include ; \ done (cd doc && make all) touch build-stamp clean: dh_testdir dh_testroot rm -f build-stamp configure-stamp [ ! -f Makefile ] || $(MAKE) distclean (cd doc/ && make clean && rm -vf manual.pdf manual.info manual.dvi \ && rm -vfr manual_html manual_html.tgz) for python in $(PYVERS); \ do $$python setup.py clean; \ done -rm -f `find . -name "*~"` -rm -rf debian/tmp debian/files* core debian/substvars -rm -f doc/html/function.html doc/html/packages.html -rm -f doc/rpy.dvi doc/rpy.pdf doc/rpy_html.tgz -rm -f config.cache config.status -rm -rf build/* -rm -rf rpy_version.pyc rpy_tools.pyc -rm -rf doc/rpy_html/*.html doc/rpy.info dh_clean install: build dh_testdir dh_testroot dh_clean -k dh_installdirs #$(PYTHON2.1) setup.py install --root=debian/python2.1-rpy #$(PYTHON2.2) setup.py install --root=debian/python2.2-rpy #$(PYTHON2.3) setup.py install --root=debian/python2.3-rpy #$(PYTHON2.4) setup.py install --root=debian/python2.4-rpy for python in $(PYVERS); \ do $$python setup.py install --root=debian/python-rpy; \ done install -d $(lintiandir) install -m 0644 debian/overrides $(lintiandir)/$(package) # Build architecture-independent files here. binary-indep: build install dh_testdir -i dh_testroot -i dh_installdocs -i dh_installdocs -ppython-rpy-doc NEWS README TODO \ doc/rpy.pdf doc/rpy_html/ dh_installdirs -ppython-rpy-doc usr/share/info/ install -m 0644 doc/rpy.info \ $(debbase)/python-rpy-doc/usr/share/info/rpy.info dh_installexamples -ppython-rpy-doc examples/* tests/ chmod -R 0644 $(debdoc)/examples/ dh_installchangelogs -i dh_link -i dh_compress -i dh_fixperms -i dh_installdeb -i dh_gencontrol -i dh_md5sums -i dh_builddeb -i # Build architecture-dependent files here. binary-arch: build install dh_testdir -a dh_testroot -a # dh_installdebconf -a dh_installdocs -a dh_installexamples -a # dh_installmenu -a # dh_installemacsen -a # dh_installpam -a # dh_installmime -a # dh_installinit -a # dh_installcron -a # dh_installmanpages -a # dh_installinfo -a # dh_undocumented -a dh_installchangelogs -a dh_strip -a dh_link -a dh_compress -a dh_fixperms -a # dh_suidregister -a # dh_makeshlibs -a # dh_perl -a dh_pycentral -a dh_shlibdeps -a dh_installdeb -a dh_gencontrol -a dh_md5sums -a dh_builddeb -a binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary install rpy-1.0.3/debian/watch0000644000076700000240000000032310411116613013754 0ustar warnesstaff# format version number, currently 2; this line is compulsory! version=2 # This is one format for an HTTP site, which is the same as the FTP format http://prdownloads.sourceforge.net/rpy/rpy-([-0-9\.]*).tar.gz rpy-1.0.3/doc/0000755000076700000240000000000011012207656012256 5ustar warnesstaffrpy-1.0.3/doc/defs.texi0000644000076700000240000000350510723660215014077 0ustar warnesstaff@ignore % $Id: defs.texi 388 2007-11-30 01:00:00Z warnes $ % % ***** BEGIN LICENSE BLOCK ***** % Version: MPL 1.1/GPL 2.0/LGPL 2.1 % % The contents of this file are subject to the Mozilla Public License Version % 1.1 (the "License"); you may not use this file except in compliance with % the License. You may obtain a copy of the License at % http://www.mozilla.org/MPL/ % % Software distributed under the License is distributed on an "AS IS" basis, % WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License % for the specific language governing rights and limitations under the % License. % % The Original Code is the RPy python module. % % The Initial Developer of the Original Code is Walter Moreira. % Portions created by the Initial Developer are Copyright (C) 2002 % the Initial Developer. All Rights Reserved. % % Contributor(s): % Gregory R. Warnes (Maintainer) % % Alternatively, the contents of this file may be used under the terms of % either the GNU General Public License Version 2 or later (the "GPL"), or % the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), % in which case the provisions of the GPL or the LGPL are applicable instead % of those above. If you wish to allow use of your version of this file only % under the terms of either the GPL or the LGPL, and not to allow others to % use your version of this file under the terms of the MPL, indicate your % decision by deleting the provisions above and replace them with the notice % and other provisions required by the GPL or the LGPL. If you do not delete % the provisions above, a recipient may use your version of this file under % the terms of any one of the MPL, the GPL or the LGPL. % % ***** END LICENSE BLOCK ***** @end ignore @macro Python Python @end macro @macro RPy RPy @end macro @macro R R @end macro rpy-1.0.3/doc/Makefile0000644000076700000240000000462210411116617013720 0ustar warnesstaff# $Id: Makefile 299 2006-03-22 22:13:54Z warnes $ # # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is the RPy python module. # # The Initial Developer of the Original Code is Walter Moreira. # Portions created by the Initial Developer are Copyright (C) 2002 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Gregory R. Warnes (Maintainer) # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** SRC = rpy.texi defs.texi dvi: rpy.dvi rpy.dvi: $(SRC) tex rpy.texi tex rpy.texi info: rpy.info rpy.info: $(SRC) makeinfo rpy.texi makeinfo rpy.texi html: rpy_html/index.html rpy_html/index.html: $(SRC) makeinfo --html rpy.texi makeinfo --html rpy.texi -rm -rf rpy_html mv rpy rpy_html rpy_html_tgz: html tar -cvzf rpy_html.tgz rpy_html pdf: rpy.pdf rpy.pdf: $(SRC) pdftex rpy.texi pdftex rpy.texi all: dvi info html pdf rpy_html_tgz dist-clean: clean -rm -f rpy.dvi rpy.pdf rpy.info -rm -rf rpy_html rpy_html.tgz clean: -rm -f rpy.cp rpy.cps rpy.fn rpy.fns rpy.ky -rm -f rpy.kys rpy.log rpy.pg rpy.pgs rpy.tmp -rm -f rpy.toc rpy.tp rpy.tps rpy.vr rpy.vrs -rm -f rpy.aux rpy-1.0.3/doc/README0000644000076700000240000000135110411116617013134 0ustar warnesstaffThis directory contains the main documentation for RPy. It is in texinfo format in the file 'rpy.texi'. Several formats derived from this file are provided. If you need another format, please, ask me. Formats provided: rpy.dvi rpy.info rpy.pdf rpy.html [directory] If you need to rebuild the documentation, you can do: make dvi (to build the dvi file) make pdf (to build the pdf file) make html (to build the directory 'manual_html') make info (to build the info file) make all (to build all the formats) make clean (to remove auxiliary files) make dist-clean (to remove all formats) You must have the correspondig tools to build the different formats, see the Makefile. rpy-1.0.3/doc/rpy.texi0000644000076700000240000013440510772312061013771 0ustar warnesstaff\input texinfo @c -*-texinfo-*- @c %**start of header @setfilename rpy.info @include defs.texi @settitle @RPy{} Reference Manual @c %**end of header @dircategory Programming @direntry * RPy: (rpy). RPy, Python extension module for R. @end direntry @macro version 0.3.3 @end macro @ifinfo This file documents @RPy{} @version{} Copyright 2002-2004 Walter Moreira Copyright 2004-2006 Walter Moriera and Pfizer, Inc. Copyright 2006- Walter Moriera, Pfizer, Inc., University of Rochester Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries a copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). @end ignore Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the sections entitled ``Copying'' and ``GNU General Public License'' are included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @end ifinfo @titlepage @title @RPy{} Reference Manual @subtitle (version @version{}) @author Walter Moreira and Gregory R. Warnes @page @vskip 0pt plus 1filll Copyright @copyright{} 2002-2004 Walter Moreira, @copyright{} 2004- Walter Moreira and Pfizer Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the sections entitled ``Copying'' and ``GNU General Public License'' are included exactly as in the original, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @end titlepage @ifnottex @node Top, Overview, (dir), (dir) @top @RPy{} Reference Manual (version @version{}) This is the reference manual for @RPy{} version @version{}, a @Python{} extension module for using the @R{} programming language. @end ifnottex @menu * Overview:: * Starting up:: * Interface description:: * Conversion system:: * Input/Output functions:: @emph{(new in 0.3)} * Miscellaneous:: * Caveat and bugs:: * Acknowledgements:: @end menu @iftex @contents @end iftex @node Overview, Starting up, Top, Top @chapter Overview @RPy{} is a very simple, yet robust, @uref{http://www.python.org, @Python{}} interface to the @uref{http://www.r-project.org, @R{} Programming Language}. It can manage all kinds of @R{} objects and can execute arbitrary @R{} functions (including the graphic functions). All the errors from the @R{} language are converted to @Python{} exceptions. Any module that later were installed on the @R{} system, can easily be used from within @Python{}, without introducing any changes. Starting from version 0.3, @RPy{} works on any POSIX system and Windows. The @RPy{} code is initially inspired in RSPython, which is part of the @uref{http://www.omegahat.org/RSPython, Omegahat project}. The main goals of @RPy{} are: @enumerate @item It should provide a very robust @Python{} interface to @R{} (segfaults shouldn't happen [tm]). @item It should be as transparent and easy to use as possible. @item It should be usable for real scientific and statistical computations. @end enumerate Currently, @RPy{} has a good degree of stability (in spite of the low version number). It provides a very customizable conversion system between @Python{} and @R{} types (@pxref{Conversion system}), user defined I/O functions and a complete handling of the @R{} errors via @Python{} exceptions. Since version 0.2, @RPy{} uses the @uref{http://numpy.sourceforge.net, Numeric} extension module for the conversion of arrays. However, if it is not available, @RPy{} converts @R{} arrays to @Python{} lists. Many things are still to be done (@pxref{To do}), but priority one is the porting to Windows. @menu * To do:: * Contact info and contributing:: @end menu @node To do, Contact info and contributing, Overview, Overview @section To do @itemize @bullet @item Possibility to pass @Python{} functions to @R{} functions (and, perhaps, to make @RPy{} a bidirectional @Python{}-@R{} interface). @item More builtin classes for conversion of @R{} classes. @item Add real examples and applications. @end itemize @node Contact info and contributing, , To do, Overview @section Contact info and contributing Please, submit any bug, comment or suggestion to the address below. When submitting bugs, it would be preferable to fill the Sourceforge form, because it can be read by many people. If you have used @RPy{} in a real world application or have some interesting examples of use, please, drop me a line. They can be linked from the @RPy{} website or included in the distribution, in order to make easier to grasp the @RPy{} capabilities. @table @asis @item Original author: Walter Moreira @item Current maintainer Gregory Warnes @item Web: @uref{http://rpy.sourceforge.net} @item Email: @email{gregory.r.warnes@@pfizer.com} @end table @node Starting up, Interface description, Overview, Top @chapter Starting up After installation, you are able to execute, almost verbatim, most of the code from the @R{} manuals. This section should be enough to start playing. @xref{Interface description}, for a detailed description; @ref{Conversion system}, for details on the conversion of types and names; and @ref{Input/Output functions} for the customization of I/O routines. @menu * Installation:: * Invocation:: * Small example:: @end menu @node Installation, Invocation, Starting up, Starting up @section Installation See the installation procedure in the file @file{README}, which is provided with the @RPy{} distribution. (Should the @file{README} instructions appear in this place?) @node Invocation, Small example, Installation, Starting up @section Invocation Once installed, the module can be imported with: @example >>> from rpy import * @end example @noindent If an error occurs, refer to the section TROUBLESHOOTING on the @file{README} file. The module @code{rpy} imports a @Python{} object named @code{r}, from which all the @R{} functions and objects can be retrieved, see @ref{R objects look up}. This module also implements a new @Python{} type: @code{Robj}, which represents an arbitrary @R{} object, see @ref{Robj type}. For example: @example >>> r.wilcox_test @end example @noindent is the @R{} function @code{wilcox.test} which computes the Wilcoxon statistical test. An object of type @code{Robj} is always callable as long as the corresponding @R{} object is: @example >>> r.wilcox_test([1,2,3], [4,5,6]) @{'p.value': 0.10000000000000001, 'statistic': @{'W': 0.0@}, 'null.value': @{'mu': 0.0@}, 'data.name': 'c(1, 2, 3) and c(4, 5, 6)', 'alternative': 'two.sided', 'parameter': None, 'method': 'Wilcoxon rank sum test'@} @end example The arguments are translated automatically to @R{} objects and the return value is translated back to @Python{}, when this is possible (@pxref{Conversion system}). This autoconversion can be customized at several levels or disabled at all. Objects of type @code{Robj} also support keyword arguments, in the same way as normal @Python{} functions: @example >>> r.seq(1, 3, by=0.5) [1.0, 1.5, 2.0, 2.5, 3] @end example The module @code{rpy} defines a new exception type derived from the base class @code{Exception}, called @code{RException}, see @ref{R exceptions}. When any kind of error in the @R{} interpreter occurs, an exception of this type is raised: @example >>> r.plot() Traceback (most recent call last): File "", line 1, in ? rpy.RException: Error in function (x, ...) : Argument "x" is missing, with no default @end example @node Small example, , Invocation, Starting up @section Small example Here we present a very small example. Some other bigger examples can be found in the @file{examples} directory of the @RPy{} distribution. See also @ref{Useful examples}. If you want to contribute some code that you find interesting as an example of use, please, write to me (@pxref{Contact info and contributing}). This lines of code draw the density of a chi-squared distribution: @example >>> from rpy import * >>> >>> degrees = 4 >>> grid = r.seq(0, 10, length=100) >>> values = [r.dchisq(x, degrees) for x in grid] >>> r.par(ann=0) >>> r.plot(grid, values, type='l') @end example @node Interface description, Conversion system, Starting up, Top @chapter Interface description In general, @R{} functions can be accessed transparently via attributes of the @code{r} object. Parameters and return values are converted to and from @R{} automatically. However, some @R{} functions, such us @code{$} or @code{[[}, need special syntax, and sometimes objects of type @code{Robj} need to be manipulated. @menu * R objects look up:: * Robj type:: * R exceptions:: * R boolean objects:: @emph{(new in 0.3)} @end menu @node R objects look up, Robj type, Interface description, Interface description @section R objects look up There are two ways of retrieving a @R{} object via the @Python{} @code{r} object: @itemize @bullet @item as attributes @item as keywords @end itemize The two ways are completely equivalent, the only difference is that some names cannot be used as attributes, so in some cases you must use the second way. The first time that a @R{} object is required, it is looked up in the @R{} global environment and it is cached in a dictionary in the @code{r} object. After then, retrieving the same object is only a look up in a @Python{} dictionary. The first way of retrieving a @R{} object is as attributes of the @code{r} object. For example: @example r.seq r.as_data_frame r.print_ @end example @noindent refer to the @R{} functions @code{seq}, @code{as.data.frame} and @code{print} respectively. Note that some kind of name conversion is required in order to make the attributes valid @Python{} identifiers. But the rules of name conversions are pretty simple; namely, the following conversions are applied to @Python{} identifiers @quotation @multitable @columnfractions .5 .5 @item @Python{} name @tab @R{} name @item ---- @tab ---- @item Underscore (@samp{_}) @tab dot (@samp{.}) @item Double underscore (@samp{__}) @tab arrow (@code{<-}) @item Final underscore (preceded by a letter) @tab is removed @end multitable @end quotation @noindent The final rule is used to allow the retrieving of @R{} objects whose names are @Python{} keywords. Some additional examples: @quotation @multitable @columnfractions .5 .5 @item @Python{} name @tab @R{} name @item ---- @tab ---- @item @code{t_test} @tab @code{t.test} @item @code{attr__} @tab @code{attr<-} @item @code{parent_env__} @tab @code{parent.env<-} @item @code{class_} @tab @code{class} @end multitable @end quotation The second way of retrieving a @R{} object is as keywords of the @code{r} object. In this form, no name conversion is required. The string used as keyword must be, exactly, the @R{} name of the object. For example: @example r['as.data.frame'] r['print'] r['$'] @end example @noindent refer to the corresponding @R{} functions. Note that with this syntax you can retrieve functions such as @code{$}, @code{$<-} or @code{[[}, which are impossible to express with the attribute syntax. However, the attributes are more appealing to the eyes. Due to the dynamic nature of the look up, when installing additional modules in the @R{} system, it is @strong{not} necessary to make changes in the interface. All you have to do is to load the module in the same way as in @R{}: @example >>> r.library('splines') ['splines', 'ctest', 'base'] @end example @node Robj type, R exceptions, R objects look up, Interface description @section Robj type The new type @code{Robj} represents an arbitrary @R{} object. All the @R{} functions retrieved via the @code{r} object (@pxref{R objects look up}) are of type @code{Robj}: @example >>> type(r.seq) @end example @noindent If you use the standard conversion of types, you'll probably never find another object of type @code{Robj}. However, there are reasons for, sometimes, manipulating these objects (@pxref{Conversion system}). @menu * Calling R objects:: * Methods of Robj type:: * Sequence protocol:: @end menu @node Calling R objects, Methods of Robj type, Robj type, Robj type @subsection Calling R objects An object of type @code{Robj} is always callable. When it represents a @R{} function, that function is invoked; if it is not a @R{} function, an exception is raised (@pxref{R exceptions}): @example >>> callable(r.seq) 1 >>> callable(r.pi) 1 >>> r.pi() Traceback (most recent call last): File "", line 1, in ? rpy.RException: Error: attempt to apply non-function @end example The arguments passed to the @code{Robj} object can be any @Python{} object, including another @code{Robj} object. When an object of a standard @Python{} type is passed, it is converted to a @R{} type according to the rules described in @ref{Python to R}. When a @code{Robj} object is passed, the @R{} function receives the corresponding @R{} object unchanged. Usually, you don't need to think on these things, because the conversion works as one expects. A @code{Robj} also supports keyword arguments, if the corresponding @R{} function does it. The names of the keyword arguments are also under the name conversion rules described in @ref{R objects look up}. For example: @example >>> r.seq(1, 3) [1, 2, 3] >>> r.seq(1, 3, by=0.5) [1.0, 1.5, 2.0, 2.5, 3.0] >>> r['options'](show_coef_Pvalues=0) @{'show.coef.Pvalues': 1@} >>> r.print_(r.seq) function (...) UseMethod("seq") @end example Return values of the call to a @code{Robj} object are also converted from @R{} to @Python{}. When no conversion is possible, an @code{Robj} object is returned, which holds a reference to the @R{} object. This behavior is completely customizable (@pxref{R to Python}). Note that python uses a python dictionary to store named arguments. As a consequence the order named arguments will be lost in calls to R functions, and hence may not produce what an R programmer expects: @example >>> set_default_mode(NO_CONVERSION) >>> r.print_(r.c(0,a=1,b=2,c=3)) a c b 0 1 3 2 >>> set_default_mode(BASIC_CONVERSION) @end example To work around this problem, @code{RObj} provides the @code{lcall} method which expects a list containing 2 element (name, value) tuples instead of a list of named and unnamed arguments. Unnamed arguments are indicated by using None or '' as for the name element of the tuple. While this form is unwieldy, it is functional and is occasionally necessary: @example >>> set_default_mode(NO_CONVERSION) >>> r.print_(r.c.lcall( (('',0),('a',1),('b',2),('c',3)) ) ) a b c 0 1 2 3 >>> set_default_mode(BASIC_CONVERSION) @end example [See @pxref{Conversion system} for the meaning of @code{set_default_mode}. It is used here to prevent python from translating the output of @code{c} into a python dictionary (which loses element order) before @code{print_} displays it.] @node Methods of Robj type, Sequence protocol, Calling R objects, Robj type @subsection Methods of Robj type An object of type @code{Robj} has three methods: @table @code @item as_py([mode]) This method forces the conversion of a @code{Robj} object to a classical @Python{} object, whenever possible. If it is not possible, the same object is returned. The optional parameter is the mode from which to apply the conversion, see @ref{Modes}. The default value for this parameter is the @dfn{global mode} (@pxref{R to Python}). @item autoconvert([mode]) @itemx local_mode([mode]) This method sets the local conversion mode for each object, which is used when the default mode is set to @samp{NO_DEFAULT}, (@pxref{Python to R}). When no argument is passed to this method, it displays the current local conversion mode of the object. (The two names are synonyms for compatibility with version 0.1.) @item lcall([argument list]) This method calls the R object (if callable) using the parameters provided as a single list containing a 2 element (name, value) tuple for each arguments. Unnamed arguments may have None or '' as the name element. @end table For example: @example >>> r.seq.local_mode(NO_CONVERSION) >>> a = r.seq(3, 5) >>> a >>> a.as_py() [3, 4, 5] >>> set_default_mode(NO_CONVERSION) >>> r.print_(r.c.lcall( (('',0),('a',1),('b',2),('c',3)) ) ) a c b 0 1 3 2 >>> set_default_mode(BASIC_CONVERSION) @end example @node Sequence protocol, , Methods of Robj type, Robj type @subsection Sequence protocol An object of type @code{Robj} supports (partially at the moment, slices are not supported yet) the sequence protocol. You can retrieve or set the n-th item of a @code{Robj} object, and you can take its length with the usual @Python{} function @code{len}. Every @R{} object is a vector, so this protocol can be applied to any @code{Robj} object; although it can raise an exception when an index is out of bounds. Note that in this case, the exception is @code{IndexError} instead of @code{RException}; this is done to allow a @code{for} loop to iterate over a @code{Robj} object. The return values of the sequence functions are converted to @Python{} according to the default mode. If the default mode is set to @samp{NO_DEFAULT}, the sequence functions use the @samp{PROC_MODE} conversion mode. @example >>> r.seq.local_mode(NO_CONVERSION) >>> a = r.seq(3, 5) >>> a[0] 3 >>> a[2] 5 >>> a[-1] 5 >>> a[4] Traceback (most recent call last): File "", line 1, in ? IndexError: R object index out of range >>> >>> for i in a: ... print i ... 3 4 5 @end example @noindent The behavior of the setting of items is different from that of @Python{}, mainly, when you try to set an item out of bounds. Remember, in these cases, that the setting is done via @R{} functions, which have different semantic from the @Python{} sequence functions. @example (following the previous example) >>> b = r.seq(1, 3) >>> dummy = r.print_(b) [1] 1 2 3 >>> b[0] = -1 >>> dummy = r.print_(b) [1] -1 2 3 >>> b[6] = 4 >>> dummy = r.print_(b) [1] -1 2 3 NA NA NA 4 @end example @noindent Also, be careful with the different index convention between @Python{} and @R{}: in @Python{}, indices start at 0; in @R{}, they start at 1. @example (following the previous example) >>> a[0] 3 >>> r['['](a, 1) 3 @end example @noindent Function @code{len} can also be applied to any @code{Robj} object: @example (following the previous example) >>> len(a) 3 >>> len(r.seq) 1 >>> len(r.pi) 1 @end example @node R exceptions, R boolean objects, Robj type, Interface description @section R exceptions @RPy{} implements a new exception type, called @code{RException}, which is derived from the base class of all exceptions @code{Exception}. This exception is raised when an error in the @R{} interpreter occurred. The error message included in the exception is the message given by the @R{} interpreter. For example: @example >>> RException >>> >>> r.t_test(1) Traceback (most recent call last): File "", line 1, in ? rpy.RException: Error in t.test.default(1) : not enough x observations @end example Note that not all operations with @code{Robj} objects raise this exception. When using the sequence protocol on @code{Robj} objects, the exceptions raised are @code{IndexError}, in order to properly use the @code{for} loop (@pxref{Sequence protocol}). Other functions, such as mode functions, raise @code{ValueError} (@pxref{Modes}). @node R boolean objects, , R exceptions, Interface description @section R boolean objects The @RPy{} module provides, as a convenience, the @code{TRUE} and @code{FALSE} R objects, as attributes to the @code{r} Python object (i.e.: @code{r.TRUE} and @code{r.FALSE}). For example: @example >>> r.TRUE >>> r.typeof(r.TRUE) 'logical' @end example Note that the @code{T} and @code{F} names from R are variables bounded to the logical objects; however, they can be rebound. So, @code{r.T} and @code{r.F} may not be the objects you expect. Use @code{r.TRUE} and @code{r.FALSE} instead. @node Conversion system, Input/Output functions, Interface description, Top @chapter Conversion system Usually, automatic conversion from and to @R{} objects works as expected. However, the system is very customizable; you can define your own conversion rules. Some useful examples are shown. @menu * R to Python:: * Python to R:: * Useful examples:: @end menu @node R to Python, Python to R, Conversion system, Conversion system @section R to Python @RPy{} has four different @dfn{conversion modes}. A mode can be @dfn{global} or @dfn{local} to every @code{Robj} object. When a global mode is active, the output from every @code{Robj} is converted according to that mode (@pxref{Modes}). (We'll use @dfn{default} as a synonym of global.) The local mode is an attribute of the @code{Robj} objects, which can be retrieved with the @code{local_mode} method (@pxref{Methods of Robj type}). When the global mode is not active, the local mode is looked up to convert the output of a given @code{Robj} object. @menu * Modes:: * Proc conversion:: * Class conversion:: * Basic conversion:: * Vector conversion:: * No conversion:: * Notes:: @end menu @node Modes, Proc conversion, R to Python, R to Python @subsection Modes There are five different conversion modes, identified by the following constants (provided by the @code{rpy} module) and another constant to indicate the absence of a global mode: @itemize @bullet @item @code{PROC_CONVERSION} @item @code{CLASS_CONVERSION} @item @code{BASIC_CONVERSION} @item @code{VECTOR_CONVERSION} @item @code{NO_CONVERSION} @item @code{NO_DEFAULT} @end itemize The @code{rpy} module provides three functions for manipulating the conversion modes: @table @code @item get_default_mode() Get the default conversion mode. It returns some of the previous constants (actually, an integer from the set @{-1,0,1,2@}, but you should use the literal constant rather than the numeric value). @item set_default_mode(m) Set the default conversion mode to @code{m}. @item with_mode(m, fun) Wrap the function @code{fun} in the conversion mode @code{m}. It returns a new function which accepts the same parameters as @code{fun} but, when called, it is evaluated in the conversion mode @code{m}. For example: @example >>> set_default_mode(BASIC_CONVERSION) >>> r.seq(1,3) [1, 2, 3] >>> with_mode(NO_CONVERSION, r.seq)(1,3) @end example @end table The result of a call to a @code{Robj} object is converted according to the following rules: @enumerate @item If the default mode has a value in the set @{@code{PROC_CONVERSION}, @code{CLASS_CONVERSION}, @code{BASIC_CONVERSION}, @code{NO_CONVERSION}@}, that mode is used. @item If the default mode has the value @code{NO_DEFAULT}, then the object's local mode is used. @item When an object cannot be converted in some mode (global or local), the object fall through to the next mode. The @code{NO_CONVERSION} mode always succeed returning a ``pure'' @code{Robj} object. @end enumerate At startup the default mode is set to @code{NO_DEFAULT}, which means that each object has its own conversion mode, and every @code{Robj} object is retrieved with a local mode set to @code{PROC_CONVERSION}. @node Proc conversion, Class conversion, Modes, R to Python @subsection Proc conversion This mode converts a @code{Robj} object according to a @Python{} dictionary, named @code{proc_table}, whose keys and values are functions of one parameter. The keys are applied sequentially to the @code{Robj} object: @itemize @bullet @item if no function returns a true value, then the conversion mode fails; @item if some function returns a true value, then the corresponding value of the dictionary is applied to the @code{Robj} object, and the result is returned as the converted object. @end itemize For example: @example >>> set_default_mode(PROC_CONVERSION) >>> def check_str(o): ... return r.is_character(o) ... >>> def f(o): ... o_py = o.as_py(BASIC_CONVERSION) ... if o_py == 'foo': ... return 'cannot return "foo"' ... return o_py ... >>> proc_table[check_str] = f >>> r.c('bar') 'bar' >>> r.c('foo') 'cannot return "foo"' >>> r.c(['bar','foo']) ['bar', 'foo'] @end example Note that the conversion is not applied recursively. This mode is applied only before returning the final result to @Python{}. This conversion mode can be used for many purposes (@pxref{Useful examples}); but, mainly, it is used to test whether a @R{} object has some attribute, and to act in consequence. Note that this conversion mode is not efficient if the @code{proc_table} dictionary has many keys, because, usually, all of them must be checked. On the other hand, with only one key which always returns true, it can be used to completely intercept the conversion system (@pxref{Enhanced Robj}). @node Class conversion, Basic conversion, Proc conversion, R to Python @subsection Class conversion This mode converts a @code{Robj} object according to a @Python{} dictionary, named @code{class_table}, whose keys are strings or tuples of strings and its values are functions of one parameter. If a @code{Robj} object matches this table (see below), the corresponding value of the dictionary is applied to the @code{Robj} object and the result is returned as the converted object. If the @code{Robj} object has no class attribute or the class attribute does not match in @code{class_table}, then this conversion mode fails. In order to a @code{Robj} object match the @code{class_table} dictionary, one of the following cases must be satisfied: @enumerate @item the @code{class} @R{} attribute of the object is a string and it is found in the @code{class_table} dictionary; or @item the @code{class} @R{} attribute of the object is a vector of strings and it is found in the @code{class_table} dictionary; or @item the @code{class} @R{} attribute of the object is a tuple of strings and one of the tuple's elements is found in the @code{class_table} dictionary. @end enumerate For example: @example >>> set_default_mode(CLASS_CONVERSION) >>> def f(o): ... return 5 ... >>> class_table['data.frame'] = f >>> r.as_data_frame([1,2,3]) 5 @end example This table is used, mainly, to translate @R{} objects of some class, to @Python{} objects of a class which mimics the @R{} original class behavior. @xref{DataFrame class}. Note that this mode is far more efficient than the @code{PROC_CONVERSION} mode. It only needs a look up in a @Python{} dictionary. @node Basic conversion, Vector conversion, Class conversion, R to Python @subsection Basic conversion This mode tries to convert a @code{Robj} object to a basic @Python{} object. It can convert most of the @R{} types to an adequate @Python{} type; but, sometimes, some information is lost. The following table shows the conversion of types. When converting lists of objects, the rules are applied recursively. @quotation @multitable @columnfractions .2 .5 .3 @item @R{} object @tab @Python{} object @tab Notes @item ----- @tab ----- @tab ----- @item NULL @tab None @item Logical @tab Boolean @tab (1)(2) @item Integer @tab Plain integer @tab (1)(2) @item Real @tab Float @tab (1)(3) @item Complex @tab Complex (1) @item String @tab String (1) @item Vector @tab list or dictionary @tab (1)(4) @item List @tab list or dictionary @tab (1)(4) @item Array @tab Array or list @tab (5) @item Other @tab (fails) @end multitable @end quotation @noindent Notes: @table @asis @item (1) In the R system there are no true scalar types. All values are vectors, with scalars represented by vectors of length one. In Python, however, there is a representational and conceptual difference between scalars immutable lists (tuples), and mutable lists. Thus, An R vector of length one could potentially be translated into any of three Python forms : @example r("as.integer(1)") --> int(1) --> [int(1),] --> (int(1),) @end example It is impossible to tell which of these is best from the R object itself. With @code{BASIC_CONVERSION}, @R assumes that a vector of length one should be translated as scalar, and that vectors with other lengths (including 0) should be translated into Python [] lists. @RPy{} 0.4.3 introduced the new @code{VECTOR_CONVERSION} mode (@pxref{Vector conversion}), which always returns a python list regardless of the length of the @R{} vector. @item (2) The @R{} programming language has an integer value represented by @samp{NA} (not applicable) which is converted to and from @Python{} as the minimum integer (which is the actual value in @R{}). Be careful, because the semantic is completely different: @table @asis @item @Python{}: @code{NA/100} --> @code{(-sys.maxint-1)/100 != NA} @item @R{}: @code{NA/100} --> @code{NA} @end table @item (3) The @acronym{IEEE} float values @code{NaN} (not a number) and @code{Inf} (infinite) are also converted between @Python{} and @R{}. @item (4) Vectors and lists from @R{} may have an attribute @code{names}, which are the names of the elements of the sequence. In those cases, the sequence is translated to a @Python{} dictionary whose keys are the names, and the values are the corresponding values of the sequence. When there are no names, the vector or list is translated to a normal @Python{} list. @item (5) When Numeric is installed, a @R{} array is converted to a Numeric array. Otherwise, a list of nested lists is returned. @end table When converting @R{} arrays, the column and row names are discarded. Also, for @R{} data frames, row names are discarded while column names are kept. And many other @R{} objects with complex attribute structure may loose some of its attributes when converted to @Python{} objects. When it is necessary to keep all the information of an @R{} object, it is better to use the @code{CLASS_CONVERSION} mode with proper classes (@pxref{Useful examples}), or to use the @code{NO_CONVERSION} mode (@pxref{No conversion}). @node Vector conversion, No conversion, Basic conversion, R to Python @subsection Vector conversion The @code{VECTOR_CONVERSION} differs from the @code{BASIC_CONVERSION} mode (@pxref{Basic conversion}) in only one way. It always returns a Python list [] object regardless of the length of the original R vector. @node No conversion, Notes, Vector conversion, R to Python @subsection No conversion This mode simply returns a @code{Robj} object which is a reference to the @R{} object under conversion. @xref{Robj type}. This mode always succeed. @node Notes, , No conversion, R to Python @subsection Notes @strong{Warning:} In order to avoid infinite recursion with the user conversion functions, the value functions in the @code{class_table} and the key and value functions in the @code{proc_table}, are evaluated in the @code{BASIC_CONVERSION} mode (@pxref{Basic conversion}). This allows the @R{} functions, called inside the conversion functions, to return @Python{} values, without consulting the tables again. You may force other conversion modes with the @code{as_py()} method of the @code{Robj} type (@pxref{Methods of Robj type}), but you should be careful. @node Python to R, Useful examples, R to Python, Conversion system @section Python to R The conversion from @Python{} objects to @R{} objects is automatic. It is done when passing parameters in @code{Robj} objects. Normal @Python{} objects are converted to @R{} objects according to the table given in @ref{Basic conversion}. A @code{Robj} object is converted to the @R{} reference which it represents. In addition, every @Python{} object which defines a @code{as_r()} method, is converted to @R{} as the result of calling that method. If none of this apply, an exception is raised. For example: @example >>> class Foo: ... def as_r(self): ... return 5 ... >>> a = Foo() >>> dummy = r.print_(a) [1] 5 >>> >>> r.print_(range) Traceback (most recent call last): File "", line 1, in ? rpy.RException: cannot convert from type 'builtin_function_or_method' @end example @node Useful examples, , Python to R, Conversion system @section Useful examples We present two examples which can be useful in real applications. They also show the use of the @code{PROC_CONVERSION} and @code{CLASS_CONVERSION} modes. These examples are provided with the @RPy{} distribution in the directory @file{examples/useful}. @menu * Enhanced Robj:: * DataFrame class:: @end menu @node Enhanced Robj, DataFrame class, Useful examples, Useful examples @subsection Enhanced Robj This example shows an extended @code{Robj} type which supports @R{} attribute look up via normal @Python{} attribute access. It also supports the representation given by the @R{} interpreter, and it implements the @code{as_r()} method for converting itself to @R{}. In Python 2.2 you can take advantage of the possibility to subclass types, and the examples can be rewritten in a more powerful way. However, these examples are Python 2.1 and 2.2 compatible. File @file{erobj.py}: @example from rpy import * class ERobj: def __init__(self, robj): self.robj = robj def as_r(self): return self.robj def __str__(self): a = with_mode(NO_CONVERSION, lambda: r.textConnection('tmpobj', 'w'))() r.sink(file=a, type='output') r.print_(self.robj) r.sink() r.close_connection(a) str = with_mode(BASIC_CONVERSION, lambda: r('tmpobj'))() return '\n'.join(as_list(str)) def __getattr__(self, attr): e = with_mode(BASIC_CONVERSION, lambda: r['$'](self.robj, attr))() if e: return e return self.__dict__[attr] @end example The @code{__str__} method makes the @R{} interpreter print to the @code{tmpobj} @R{} variable. Then, it is retrieved and returned as the string representation of the object. Note the use of the @code{with_mode} function for not changing the mode in use. Note, also, the use of the utility functions @code{as_list} and @code{r} (@pxref{Miscellaneous}). An example of use: @example >>> from rpy import * >>> from erobj import * >>> proc_table[lambda o: 1] = ERobj >>> set_default_mode(PROC_CONVERSION) >>> >>> e = r.t_test([1,2,3]) >>> e >>> print e One Sample t-test data: c(1, 2, 3) t = 3.4641, df = 2, p-value = 0.07418 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: -0.4841377 4.4841377 sample estimates: mean of x 2 >>> >>> e.statistic @{'t': 3.4641016151377548@} @end example @node DataFrame class, , Enhanced Robj, Useful examples @subsection DataFrame class This example is a subclass of the Enhanced Robj (@pxref{Enhanced Robj}), which can be used to mimic the @samp{Data Frame} class of the @R{} language. It overrides the @code{__getattr__} method for retrieving the columns of the data frame object. It adds a method for accessing the rows and it inherits the representation and @code{as_r} method. File @file{dataframe.py}: @example from rpy import * import erobj class DataFrame(erobj.ERobj): def __init__(self, robj): erobj.ERobj.__init__(self, robj) def rows(self): return r.attr(self.robj, 'row.names') def __getattr__(self, attr): o = self.__dict__['robj'] if attr in as_list(r.colnames(o)): return r['$'](o, attr) return self.__dict__[attr] @end example An example of use: @example >>> from rpy import * >>> from dataframe import * >>> class_table['data.frame'] = DataFrame >>> set_default_mode(CLASS_CONVERSION) >>> >>> e = r.as_data_frame(@{'foo': [4,5,6], 'bar': ['X','Y','Z']@}) >>> e >>> print e foo bar 1 4 X 2 5 Y 3 6 Z >>> >>> e.foo [4, 5, 6] >>> e.bar ['X', 'Y', 'Z'] >>> e.rows() ['1', '2', '3'] @end example @node Input/Output functions, Miscellaneous, Conversion system, Top @chapter Input/Output functions @RPy{} provides three functions for customizing the input and output from the @R{} interpreter. In versions 0.1 and 0.2, the input/output from/to @R{} was connected to the C stdin/stdout, which don't necessarily coincides with the Python sys.stdin/sys.stdout. These was noticeable if you run those versions over IDLE or other IDE (probably, you don't see the output of @code{r.print_(5)}). Now, the R input/output is connected, by default, to the Python streams. But you can insert your own functions for reading, writing and displaying files. @table @code @item get_rpy_input() @itemx set_rpy_input(f) Get/set the function used by the @R{} interpreter to require input. The parameter for @code{set_rpy_input} must be a function with signature @code{f(prompt, size)}. The parameter @var{prompt} is a string to be displayed and @var{size} is an integer which denotes the maximum length of the input buffer. @item get_rpy_output() @itemx set_rpy_output(f) Get/set the function used by the @R{} interpreter to output data. The parameter for @code{set_rpy_output} must be a function with signature @code{f(s)}, where @var{s} is the string to be displayed. @item get_rpy_showfiles() @itemx set_rpy_showfiles(f) @strong{[Not available on Windows]} Get/set the function used by the @R{} interpreter to display files, including the output from the @code{help} command. The parameter for @code{set_rpy_showfiles} must be a function with signature @code{f(files, headers, title, delete)}. Parameters @var{files} and @var{headers} are lists of filenames and strings, respectively, to be displayed sequentially. Parameter @var{title} is the overall title and parameter @var{delete} signals whether the files should be deleted after displaying. @end table The default values for the input/output/showfiles functions are in the @file{io} module. That is, when @RPy{} is imported, the following instructions are executed: @example import io set_rpy_input(io.rpy_input) set_rpy_output(io.rpy_output) set_rpy_showfiles(io.rpy_showfiles) @end example For input and output, the functions @code{io.rpy_input} and @code{io.rpy_output} just use the sys.stdin and sys.stdout streams of Python. For displaying files, the @file{io} module provides two functions: @code{io.showfiles_common} and @code{io.showfiles_tty}, and the default @code{io.rpy_showfiles} is an alias for the former. Function @code{io.showfiles_common} displays the files using the @code{io.rpy_output} function, while function @code{io.showfiles_tty} displays the files using a pager (namely @code{less}, you may need to customize it). @heading Notes @itemize @bullet @item When an exception is raised inside I/O functions, the exception is ignored, although it is displayed normally. @item On Windows, the output of the @code{help} command is always displayed on a separate window. The @R{} event loop (see @ref{Miscellaneous}) must be running for the window to be functional. @end itemize @node Miscellaneous, Caveat and bugs, Input/Output functions, Top @chapter Miscellaneous The @code{rpy} module includes some utility functions: @table @code @item as_list(obj) If @code{obj} is a list or an object which supports the list protocol, it returns @code{obj}. Otherwise, it returns the one element list @code{[obj]}. @c @end table @noindent This function is useful when testing whether a @code{Robj} has some given attribute. For example: @example >>> 'class' in as_list(r.attributes(robj)) @end example The reason for not doing @code{'class' in r.attributes(robj)} is that @code{r.attributes} can return either @code{None} (when @code{robj} has no attributes), a string (when @code{robj} has only one attribute) or a list of strings (when it has several attributes). Function @code{as_list} unify these three cases to allow the @code{in} test. @c @table @code @item r(s) Parameter @code{s} is a string containing arbitrary @R{} code. Function @code{r} evaluates the string @code{s} in the @R{} interpreter and returns its result. @c @end table This function is useful when working with @R{} constructions which have no parallel @Python{} syntax, such as linear models, for example. @example >>> set_default_mode(NO_CONVERSION) >>> d = r.data_frame(x=[1,2,3], y=[4,5,6]) >>> >>> model = r("y ~ x") >>> fitted_model = r.lm(model, data = d) @end example Complete fragments of @R{} code can also be evaluated (note that the value returned by the function @code{r} is the value of the last expression): @example >>> r(""" ... print(5) ... x <- "foo" ... print(x) ... """) [1] 5 [1] "foo" 'foo' @end example This function is useful, also, when a changing R object is required. Since the expression @code{r.foo} is cached in a Python dictionary, later changes in the object pointed by @code{r.foo} are not seen. In that case, the proper expression to use is @code{r('foo')}, which evaluates @code{foo} and returns its result every time it is called. @item start_r_eventloop() @itemx stop_r_eventloop() @emph{(new in 0.3)} @strong{[Not available on Windows]} These functions start and stop the @R{} event loop. When @RPy{} is imported, the @code{start_r_eventloop} function is executed. Normally, in interactive use, you needn't stop it. The @R{} event loop keeps running in a daemonic thread. In case you need finer control over that loop, you can use the @code{r_events} function. @item r_events([usec]) @emph{(new in 0.3)} @strong{[parameter @var{usec} not available on Windows]} This function processes a pending @R{} event or blocks with a @var{usec} microseconds timeout. The default value for @var{usec} is 10000 microseconds. If, for some reason, you don't want to use the threaded event loop and you want to manually use @code{r_events}, you can do some loop like the following: @example >>> r.plot([1]) >>> while 'X11' in as_list(r('.Devices')): ... r_events() @end example The @code{while} loop will run until the graphics window is closed. @end table @node Caveat and bugs, Acknowledgements, Miscellaneous, Top @chapter Caveat and bugs You should be warned about some ``corners'': @itemize @bullet @item In some situations, the @R{} interpreter uses the name bound to an object for displaying or for taking some action. For example, if you eval in @R{} the expression: @example var <- c(1,2,3) plot(var) @end example you obtain a plot with the y-axis labeled by @code{var}. However, in @Python{} there is no standard way to know a name bound to an object, so, even when an @code{Robj} has a @Python{} name, the @R{} interpreter doesn't see that information. The practical consequence is that the @R{} plots made from @Python{} are labeled with the @emph{entire} vector of data, usually cluttering up the graphic. I really don't see an elegant way to solve this. Of course, the immediate and pragmatic solution is to write @code{r.par(ann=0)} for disabling the automatic label annotations, or to set the labels explicitly. Another solution (a bit trickier) is: @example >>> r.assign("var", [1,2,3]) >>> r("plot(var)") @end example @item The conversion between the @acronym{IEEE} values, @code{NaN} and @code{Inf}, depends highly on the operating system, since that is what happens with the @Python{} interpreter (AFAIK). I have no access to a platform other than Linux, so I may be wrong. @sp 1 @item At the present moment, it is not possible to pass @Python{} functions to those @R{} functions which requires callables as arguments, such as @code{integrate}, for example. It would be necessary to embed the @Python{} interpreter in @R{} (and only a step forward: an @R{} package for calling @Python{} :-) @end itemize Now, some Windows' specific notes. Most of these are due to my ignorance on the Windows OS; if you have suggestions for solving some of these points, please, contact me (see @ref{Contact info and contributing}). @itemize @bullet @item The interruption from keyboard (Ctrl-C) when @RPy{} is imported in a @Python{} instance running on a console, is completely non-operational. I tried to deal with the @code{SIGINT} and @code{SIGBREAK} signals in a similar fashion than with Linux, but I failed. So, the code you run in a console is uninterruptible. @sp 1 @item Running the @R{} event loop in a separate thread doesn't work. This point, together with the previous one, means that if you want to use a console and you need to make a plot, you must do something like the following: @example >>> r.plot(data) >>> while 'windows' in r_events(): ... pass @end example Then, the loop is unbreakable with Ctrl-C. The only way to stop it is to close the graphic window. @sp 1 @item The Windows version of @R{} always displays the output from the @code{help} command in a separate window. This window must be refreshed by the @R{} event loop. But, now, the problem is that the device of that window doesn't appear listed on the return value of @code{r_events}; so, there is no way to make a loop like the previous one. @end itemize @strong{Suggestion for Windows users:} the problems listed before @emph{only} occur when @Python{} runs on a console (a @acronym{MS-DOS} window). I strongly suggest that, for interactive sessions, you use the @acronym{IDLE} shell instead. With @acronym{IDLE}, the keyboard interruption works as expected and the graphics and help windows are completely functional without the need to use the @code{r_events} function. @node Acknowledgements, , Caveat and bugs, Top @chapter Acknowledgements I want to thank to these people for their feedback and help on the @RPy{} project: @table @asis @item Tim Churches for his advocacy, suggestions and for contributing with the @code{faithful} demo. @item Gregory Warnes for his many patches and help with the compilation and testing of @RPy{} in the Solaris system. @item Rene Hagendoorn for his patches and help for making the Windows version of @RPy{}. Also, for the idea of the @R{} event loop functions. @item Duncan Temple Lang for his work on @acronym{RSPython} and for detecting bugs in the initial version of @RPy{}. @end table @bye rpy-1.0.3/examples/0000755000076700000240000000000011012207656013327 5ustar warnesstaffrpy-1.0.3/examples/animation.py0000644000076700000240000000044410411116620015652 0ustar warnesstaff# Make a simple animation with the chi-squared density # import chisquared import time from rpy import * def anim(from_=1, to=30, pause=0.5): for i in range(from_, to+1): r.par(yaxt='n') chisquared.draw(i) time.sleep(pause) if __name__ == '__main__': anim() rpy-1.0.3/examples/chisquared.py0000644000076700000240000000067710411116620016033 0ustar warnesstaff# Simple script for drawing the chi-squared density # from rpy import * def draw(df, start=0, end=10): grid = r.seq(start, end, by=0.1) l = [r.dchisq(x, df) for x in grid] r.par(ann=0, yaxt='n') r.plot(grid, l, type='lines') if __name__ == '__main__': print " to quit." while 1: try: df = int(raw_input('Degrees of freedom> ')) draw(df) except ValueError: break rpy-1.0.3/examples/faithful.py0000644000076700000240000000434310411116620015477 0ustar warnesstaff# Contributed by Tim Churches, with a minor hack for detecting some # graphical device. from rpy import * # hack d = r.capabilities() if d['png']: device = r.png ext='png' elif d['jpeg']: device = r.jpeg ext='jpg' else: device = r.postscript ext='ps' faithful_data = {"eruption_duration":[], "waiting_time":[]} f = open('faithful.dat','r') for row in f.readlines()[1:]: # skip the column header line splitrow = row[:-1].split(" ") faithful_data["eruption_duration"].append(float(splitrow[0])) faithful_data["waiting_time"].append(int(splitrow[1])) f.close() ed = faithful_data["eruption_duration"] edsummary = r.summary(ed) print "Summary of Old Faithful eruption duration data" for k in edsummary.keys(): print k + ": %.3f" % edsummary[k] print print "Stem-and-leaf plot of Old Faithful eruption duration data" print r.stem(ed) file = 'faithful_histogram.'+ext device(file,width=733,height=550) r.hist(ed,r.seq(1.6, 5.2, 0.2), prob=1,col="lightgreen",main="Old Faithful eruptions",xlab="Eruption duration (seconds)") r.lines(r.density(ed,bw=0.1),col="orange") r.rug(ed) r.dev_off() long_ed = filter(lambda x: x > 3, ed) file = 'faithful_ecdf.'+ext device(file,width=733,height=550) r.library('stepfun') r.plot(r.ecdf(long_ed), do_points=0, verticals=1, main="Empirical cumulative distribution function of Old Faithful eruptions longer than 3 seconds") x = r.seq(3,5.4,0.01) r.lines(r.seq(3,5.4,0.01),r.pnorm(r.seq(3,5.4,0.01),mean=r.mean(long_ed), sd=r.sqrt(r.var(long_ed))), lty=3, lwd=2, col="red") r.dev_off() file = 'faithful_qq.'+ext device(file,width=733,height=550) r.par(pty="s") r.qqnorm(long_ed, col="blue") r.qqline(long_ed, col="red") r.dev_off() r.library('ctest') print print "Shapiro-Wilks normality test of Old Faithful eruptions longer than 3 seconds" sw = r.shapiro_test(long_ed) print "W = %.4f" % sw['statistic']['W'] print "p-value = %.5f" % sw['p.value'] print print "One-sample Kolmogorov-Smirnov test of Old Faithful eruptions longer than 3 seconds" ks = r.ks_test(long_ed,"pnorm", mean=r.mean(long_ed), sd=r.sqrt(r.var(long_ed))) print "D = %.4f" % ks['statistic']['D'] print "p-value = %.4f" % ks['p.value'] print "Alternative hypothesis: %s" % ks['alternative'] print rpy-1.0.3/examples/nnet.py0000644000076700000240000000114410757621447014662 0ustar warnesstafffrom rpy import * # avoid automatic conversion set_default_mode(NO_CONVERSION) r.library("nnet") model = r("Fxy~x+y") df = r.data_frame(x = r.c(0,2,5,10,15) ,y = r.c(0,2,5,8,10) ,Fxy = r.c(0,2,5,8,10)) NNModel = r.nnet(model, data = df , size =10, decay =1e-3 , lineout=True, skip=True , maxit=1000, Hess =True) XG = r.expand_grid(x = r.seq(0,7,1), y = r.seq(0,7,1)) x = r.seq(0,7,1) y = r.seq(0,7,1) # turn automatic conversion back on set_default_mode(BASIC_CONVERSION) fit = r.predict(NNModel,XG) print fit rpy-1.0.3/examples/README0000644000076700000240000000127510411116620014204 0ustar warnesstaffExamples. This is a small collection of examples. All contributions are welcome. To run the scripts do (for example): python animation.py Here is a list of the scripts: faithful.py make very nice graphs from the 'Old faithful' data. (Contributed by Tim Churches.) chisquared.py plotting of the chi-squared density. animation.py plotting of the chi-squared density with different degrees of freedom. These are small examples of the use of conversion modes. See the manual for details. useful/erobj.py Enhanced version of the Robj type, using the PROC_CONVERSION mode. useful/dataframe.py DataFrame Python class to mimic the data frame R class. rpy-1.0.3/examples/useful/0000755000076700000240000000000011012207656014632 5ustar warnesstaffrpy-1.0.3/examples/useful/dataframe.py0000644000076700000240000000060110411116617017123 0ustar warnesstafffrom rpy import * import erobj class DataFrame(erobj.ERobj): def __init__(self, robj): erobj.ERobj.__init__(self, robj) def rows(self): return r.attr(self.robj, 'row.names') def __getattr__(self, attr): o = self.__dict__['robj'] if attr in as_list(r.colnames(o)): return r['$'](o, attr) return self.__dict__[attr] rpy-1.0.3/examples/useful/erobj.py0000644000076700000240000000124210411116617016302 0ustar warnesstafffrom rpy import * class ERobj: def __init__(self, robj): self.robj = robj def as_r(self): return self.robj def __str__(self): a = with_mode(NO_CONVERSION, lambda: r.textConnection('tmpobj', 'w'))() r.sink(file=a, type='output') r.print_(self.robj) r.sink() r.close_connection(a) str = with_mode(BASIC_CONVERSION, lambda: r('tmpobj'))() return '\n'.join(as_list(str)) def __getattr__(self, attr): e = with_mode(BASIC_CONVERSION, lambda: r['$'](self.robj, attr))() if e: return e return self.__dict__[attr] rpy-1.0.3/INSTALL.UNIX0000644000076700000240000000527610411116620013326 0ustar warnesstaffLinux and Unix Binary Installation ---------------------------------- Binary packages for rpy are available for Debian GNU/Linux via the standard mechanisms. Other binary packages may be available from the rpy download site. Linux and Unix Source Installation: ---------------------------- If you have Numeric (NumPy) installed, it can be used by RPy; normally it is autodetected, you don't have to do anything. If Numeric cannot be found, then R arrays will be converted to Python lists, which are a lot more inefficient than Numeric arrays. I strongly suggest to install Numeric. If you have installed some previous version of RPy, just go to (c). To install RPy follow the steps: (a) First of all, you *must* check that you have built R with the configure option '--enable-R-shlib', in order to make R as a shared library. If not, the following steps should be enough: make distclean ./configure --enable-R-shlib make make install (Solaris users, please, see the note (a) below.) (b) Then, configure the path to the R library. You have several ways to do this (substitute RHOME with the path where R is installed, usually /usr/local/lib/R): o make a link to RHOME/bin/libR.so in /usr/local/lib or /usr/lib, then run 'ldconfig', o or, put the following line in your .bashrc (or equivalent): export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:RHOME/bin o or, edit the file /etc/ld.so.conf and add the following line: RHOME/bin and then, run 'ldconfig'. (c) Now, just type: python setup.py install and that's all! If you want, you can run the regression tests located in the 'tests' directory, just read the README file in that directory. For a quickier test, launch the Python interpreter and import the module 'rpy': Python 2.2 (#2, Dec 23 2001, 16:30:35) [GCC 2.95.4 20010703 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import rpy >>> If you get some error, refer to TROUBLESHOOTING below. If you want to test the module without installing it, do: python setup.py build Then, cd to build/lib.-/ and try to import the module. *** NOTES *** (a) Solaris users must change the line: LIBR_LDFLAGS = -shared in the file 'Makeconf' on the R source directory, for the line: LIBR_LDFLAGS = -shared -symbolic before recompiling the R library. (b) It has been reported that it may be necessary, in some situations, to completely remove the R sources, to unpack it again, and to compile to R library with the new options. rpy-1.0.3/INSTALL.WINDOWS0000644000076700000240000000231710723562012013674 0ustar warnesstaff Windows Binary Installation: ---------------------------- The Windows version of RPy is provided as a binary bundle. It is compiled with Python 2.3 and with Numeric support. Before installing RPy, make sure you have installed: o Python 2.2 o R (a recent version) o Either the "NumPy" or "Numeric" python module. Main page: http://numpy.sf.net/ Download from: http://sourceforge.net/project/showfiles.php?group_id=1369 o win32all, windows extensions from Mark Hammond (included in ActiveState python) and is also available from http://starship.python.net/crew/mhammond/win32/Downloads.html Now, download and install the appropriate RPy install file. Each file is named something like: rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe This file is rpy version 0.4.6, which has been compiled for R versions 2.0.0 through 2.2.1, and Python version 2.4. Windows Source Installation (MingGW) ------------------------------------- **NEW SIMPLER INSTRUCTIONS** 1. Install MinGW into C:\MinGW (http://prdownloads.sourceforge.net/mingw/MinGW-5.0.2.exe) 2. Check that the paths in setup.bat and setup.Win32 are correct for where you installed MinGW. 3. Run setup.bat rpy-1.0.3/MANIFEST.in0000644000076700000240000000056110411116620013241 0ustar warnesstaffglobal-include *.py *.c *.h debian* README TODO Makefile *.texi global-exclude *[0-9].[ch] include COPYING ChangeLog INSTALL.UNIX INSTALL.WINDOWS MANIFEST.in include NEWS README TODO global-exclude .cvsignore *.pyc *.bak .tnatr* *.tgz *.tar.gz *~ global-exclude core* *patch* *diff* .svn include debian/* prune debian/.svn prune CVS prune dist prune doc/manual_html rpy-1.0.3/NEWS0000644000076700000240000003560311012207236012211 0ustar warnesstaffCHANGES IN RPY 1.0.3 - 2008-05-12 --------------------------------- Bug fixes: - Correct issue with R 2.7.0. (R 2.7.0 exports the symbol 'Rf_KillAllDevices' instead of 'KillAllDevices') CHANGES IN RPY 1.0.2 - 2008-04-02 --------------------------------- New features: - The 'Robj' type is now exported. - Add simple neural net example. Bug fixes: - Stack checking code was incorrectly disabled on all platforms, corrected so that it is properly included for R 2.3.0 and later everywhere except Win32. - Fixes for compatibility with Python 2.4 and later. - Updates to debian install files (Dirk Eddelbuettel) - Correct simple line plot example in the documentation - Minor internal changes to code and tests - Automatic build tool now uses 'tail -n 1' instead of 'tail -1' when calling 'R RHOME' to make recent versions of tail happy - Add startup options to prevent initialization of console read/write/showfiles which causes problems with R when run without a controlling console. Other changes: - Deletion of R's temporary directory now uses R's own internal function for this task for R versions after 2.4.0. CHANGES IN RPY 1.0.1 - 2007-11-29 --------------------------------- Bug Fixes: - Correct silent termination on load on MS-Windows (really this time!) - Improve detection of installed R versions during build process on MS-Windows CHANGES IN RPY 1.0.0 - 2007-11-15 --------------------------------- New Features: - Complete support for NumPy - Add new exception types to provide better information on the source of the error: RPyException: Base exception class for all RPy Exceptions RPyTypeConversionException: Error in conversion between R and Python RPyRException Error raised within R (RException is set equal to RPyException for backwards compatibility) Bug Fixes: - All Numeric and NumPy data types are either properly handled, or an appropriate exception is generated. - Properly handle unicode strings. - Fix silent failure to start up on Win32 Other: - Misc improvments to the test code. CHANGES IN RPY 1.0 RC 3 - 2007-06-26 ------------------------------------ Bug Fixes: - Only apply code to fix C Stack Limit error to recent versions of R that require the fix. CHANGES IN RPY 1.0 RC 2 - 2007-05-18 ------------------------------------ New Features: - Initial work to provide support for NumPy Bug Fixes: - Fix "C stack limit" error produced by R in some contexts - Moved some code so no longer necessary to have R/bin in PATH - Skip tests for features not supported on Win32 CHANGES in RPY 1.0 RC 1 - 2006-08-08 ------------------------------------ Bug Fixes - Improve R version parsing to cope with new R startup message CHANGES IN RPY 0.99.2 - 2006-03-24 ---------------------------------- Bug fixes: - Windows binaries in 0.99.1 were built without Numeric support. Corrected for 0.99.2 CHANGES IN RPY 0.99.1 - 2006-03-24 ---------------------------------- New features: - RPy is now available under the terms of the Mozilla Public License (MPL), the GNU Public License (GPL), or the Library or Lesser GNU Public License (LGPL) Bug fixes: - Fix crash on win32 due to omission (was commented out during debugging!) of explicit dll load. CHANGES IN RPY 0.99.0 - 2006-03-15 ---------------------------------- New features: - Dramatically simplify the build process for Win32: The gcc and ld included in MinGW 5.0.2 can now linking directly against DLL's, removing the need for much of the previous complexity. See INSTALL.WINDOWS to see exactly how easy it now is! - It is now possible to use setup.cfg to control various aspects of the build process. 'config.in' contains a template containing all available options and what they do. Bug fixes: - RPy compiled with Numeric support will no longer crash when run with Numeric available. - 1267731: Crash during import when R is missing from the registry - 1247722: Problem using R Wavelets library with RPy - 1428256: RPy does not build on OS X, easy fix - 1432578: Plotting with RPy crashes Python Other: - The rpy.py now communicates RHOME, RVER, RVERSION, RUSER from python to the _rpy module using environment variables. This avoids the need to have duplicate C code to obtain these values, and makes things both more maintainable and more robust. CHANGES IN RPY 0.4.6 - 2005-07-28 --------------------------------- Bug fixes - Some unit tests don't properly restore the default conversion mode, causing following tests to fail. Short term fix: reset the default mode in testall.py before running each test. - Fix bug reported by Wei-Hao Lin: missing import and typo in rpy.py for Win32 - Fix bug reported by Nicolas Lebas: Segfault when accessing R objects via r.. The code was was only properly handling R function objects, and failed for other object types. - setup.py was always overwriting the .c files (used to allow binaries for mulitple R versions to be included in the same package). setup.py now create/overwrite the .c files only if they don't exist or are out of date. This should be the last release for some time. ;^) CHANGES IN RPY 0.4.5 -------------------- New features - Based on changes suggested by Bo Peng (Thanks Bo!), setup.py can now build and install a version of Rpy which will work with multiple versions of R. To use this, set the environment varaible 'RHOMES' to a list of R HOME directories. Look at the file description at the top of setup.py for details. - Improved build instructions for Windows by Bo Peng. Bug fixes - Fixed a install bug on Windows. CHANGES IN RPY 0.4.4 -------------------- New features - Rpy now checks for Numeric at runtime and avoids calling it when it is not present. This allows a single binary library to be used whether or not Numeric is available at runtime, significantly simplyfing creation and distribution of binary packages. - Warning messages from R are now properly displayed at the completion of the offending call. Bug fixes - Compilation on Windows and for R versions below 2.1.0 has been fixed. Unresolved bugs - Reception of a SIGINT signal sometimes causes a segfault. Under Linux, I see about 1 segfault per 100 signals. On Solaris, I'm seeing appriximatley 3 out of 4. Help debuging this issue is most welcome. CHANGES IN RPY 0.4.3 -------------------- New features - R Logical objects (TRUE/FALSE) are now mapped into python Boolean objects. - New conversion mode 'VECTOR_CONVERSION' In R there is no such thing as a straight scalar. All values are vectors, and scalars are simple vectors of length one. In Python, however, there is a representational and conceptual difference between scalars and lists, plus Python's immutable lists (a.k.a. tuples). Thus, An R vector of length one can thus be translated into any of three Python forms : r("as.integer(1)") --> int(1) --> [int(1),] --> (int(1),) It is impossible to tell from the R object itself, which of these is correct. Given that [] and () are almost equivalent, we don't worry about (). But we still must decide between int(1) and [int(1)]. As documented in the Rpy manual, BASIC_CONVERSION, simply assumes that a vector of length one should be translated as scalar, and that vectors with other lengths (including 0) should be translated into Python [] lists. The new 'VECTOR_CONVERSION' mode always returns a python list, regardless of the length of the R vector. EG, with_mode( BASIC_CONVERSION, r.c)(1) --> int(1) with_mode( VECTOR_CONVERSION, r.c)(1) --> [int(1),] - R source headers no longer needed, and are no longer included in the source package (yea!) - Previous versions of rpy have permitted multiple copies of the R interpreter wrapper to be instantiated (via "newR = rpy.R()" ). However R's design imposes a limit of one interpreter per python process. To avoid confusion on this point, attempts to instantiate more than one R interpreter object will now generate RuntimeError exceptions. - On Windows, RPy now always looks at the registry to see where to find the R DLL. This should avoid the nasty popup error message when the DLL isn't on the path. Patch by Peter (maubp@users.sourceforge.net) - The R integer 'NA' value is now accessible as the 'NA' attribute of the Python 'r' object. - The R floating point 'NA' value is now accessible as the 'NAN' attribute of the Python 'r' object. - The build process now creates version-specific shared libraries, and rpy will load the appropriate version specific library. This should help avoid problems arising from version conflicts, it will also make packaging 'universal' binary packages easier. Bug fixes: - Fix build error for R 2.0.0+ on Mac OSX ('darwin') - The R interpreter is now properly shutdown when python exits. This ensures that all temporary directories and files are removed, resolving a long-standing issue. - r.help() now works as expected by users. (Some time ago help() started returning an object that had to be explicitly printed to complete the processing. RPy now special-cases calls to r.help to ensure that this happens properly.) - All unit tests now pass. - Fix compilation error on Win32 due to a change in field names in R-2.1.1 [ 1238226 ] rpymodule.c needs updating for R 2.1.1 or later. Bo Peng identified both the bug and the fix. - Fix error (potential segfault!) when handling conversion of factor objects containing missing values - Fix bug in R.__call__ that could cause problems when the 'r' object is not present. Behind the scenes: - Some work has been done "under the hood" to allow an R interpreter to be shut down and then started up again. This is *not* currently working. CHANGES IN RPY 0.4.2 -------------------- New features: - Add headers to enable building for R 2.1.0. Bug fixes: - Fix build error under gcc 4.X CHANGES IN RPY 0.4.1 -------------------- New features: - Headers for R 2.0.1 are now included, allowing build against R 2.0.1 without additional effort. Bug fixes: - Provide alternative getstatusoutput for Windows, resolving a build issue there. CHANGES IN RPY 0.4.0 -------------------- New features: - More fixes for R 2.0.0 - R header files for R 1.8.0 through R 2.0.0 are now included with rpy. This should make it easier to build. CHANGES IN RPY 0.3.6 -------------------- New features: - Compatible with R 2.0.0 - Better build instructions for Windows - New assistant maintaner: Nitin Jain Bug Fixes: - Fix build issue on Windows, due to a path problem. CHANGES IN RPY 0.3.5 -------------------- New features: - Now compiles cleanly on Mac OS X. - Rename io.py to rpy_io.py to avoid conflict with another python package. - Some bug fixes for windows. The Windows port is still not stable. So exercise caution! CHANGES IN RPy 0.3.4 -------------------- New features: - The path to the R shared library (unix) / DLL (win32) is now included in the compiled shared rpy library/DLL so that the R shared library/DLL will be found even when it is not in the library search path (unix:LD_LIBRARY_PATH, win32:PATH). - Tests now run against the local build rather than the installed build Fixed bugs: - The unit test for the lcall method was incorrect. CHANGES IN RPy 0.3.3 -------------------- Fixed bugs - Removed link error for 'jump_now' with R 1.8.X - Removed redefinition of malloc() - Fixes to unit tests New features - Now works with R 1.8.X - Windows changes integrated into the Unix source tree - Added lcall() method for calling R functions using a list of (name, value) pairs for the parameters. This is works around the python (mis-)feature of using unordered python dictonaries for named parameters, resulting in the loss of order for named parameters. CHANGES IN RPy 0.3.1 -------------------- Fixed bugs - There was several memory leaks due to bad management of Python refcounts. - There was wrong synchronization of the thread running the R event loop and the calls to the R interpreter. - There was a bug with signal handling which caused segfault when 'Ctrl-C' were pressed. - The R event loop shouldn't be run in non-interactive sessions. - The i/o Python callbacks were wrong synchronized with the R event loop thread. New features - Added a rpy_version symbol. CHANGES IN RPy 0.3 ------------------ Fixed bugs - There was a bug in the conversion of factors (when it has duplicate entries). - The R computations were unbreakable, due to the interception of the SIGINT signal. Now, it is working properly; CTRL-C aborts any Python or R evaluation with a KeyboardInterrupt exception. - The input/output of the R interpreter was directed to the C stdin/stdout instead of the Python streams. New features - Added functions to manipulate the R event loop. - Added functions to customize the input and output of the R interpreter (the default is, now, sys.stdin and sys.stdout). Now, RPy works well with IDLE or other IDE's. - The output from the R help command is also customizable. - Added the R boolean objects TRUE and FALSE, as attributes of the Python 'r' object. Documentation - Updated (and a bit expanded) the docs to reflect the changes. Added sections with acknowledgements and known bugs. Distribution - Included a 'setenv.c' for POSIX compliance. - Support for Windows platform. CHANGES IN RPy 0.2 ------------------ Fixed bugs - There were several bugs related to memory and R and Python garbage collectors, which caused Python segfaults. - There was a problem with signals traped by R, which made Python crash when was pressed. - R objects of class 'factor' or 'data.frame' were incorrect converted to Python. - Instances of any class converted to R were treated as sequences and made Python segfault. Conversion - RPy has now a new system for conversion of types from R to Python (see the docs), which includes user defined conversion functions. - The conversion to R types is also customizable. - Some utility functions are added. - When Numeric (NumPy) is available, it is used for the standard conversion between R arrays and Python objects. Documentation - The documentation is converted to texinfo format, updated and enlarged. In particular, better documentation for the compilation procedure and for the location of libraries is included. Distribution - There are now some examples included in the distribution. - Regression tests are also included. CHANGES IN RPy 0.1 ------------------ Initial release rpy-1.0.3/PKG-INFO0000644000076700000240000000074011012207656012607 0ustar warnesstaffMetadata-Version: 1.0 Name: rpy Version: 1.0.3 Summary: Python interface to the R language Home-page: http://rpy.sourceforge.net Author: Gregory R. Warnes Author-email: warnes@bst.rochester.edu License: GPL Description: RPy provides a robust Python interface to the R programming language. It can manage all kinds of R objects and can execute arbitrary R functions. All the errors from the R language are converted to Python exceptions. Platform: UNKNOWN rpy-1.0.3/README0000644000076700000240000003177410411116620012375 0ustar warnesstaff RPy - Python interface to the R Programming Language 1. WHAT IS RPy? RPy is a very simple, yet robust, Python interface to the R Programming Language (http://www.r-project.org). It can manage all kinds of R objects and can execute arbitrary R functions (including the graphic functions). All the errors from the R language are converted to Python exceptions. Any module that later were installed on the R system, can easily be used from within Python, without introducing any changes. Versions 0.1 and 0.2 work only on POSIX systems. Version 0.3 and later also include Windows support (although, some capabilities are missing, see the reference manual for details). See the file NEWS for details on the lastest changes. This code is inspired in RSPython from the Omegahat project (http://www.omegahat.org/RSPython). 2. INSTALLATION You need Python and R interpreters. At least, Python 2.1 and R 1.5.0 is required. I have tested it only on Linux and Solaris, but it should compile on any POSIX system. It has been reported successful compilations on Linux, Solaris, FreeBSD and MacOS X. Please, send me a note if you can compile it with other versions or under other platforms. Linux and Unix Binary Installation ---------------------------------- Binary packages for rpy are available for Debian GNU/Linux via the standard mechanisms. Other binary packages may be available from the rpy download site. Linux and Unix Source Installation: ---------------------------- If you have Numeric (NumPy) installed, it can be used by RPy; normally it is autodetected, you don't have to do anything. If Numeric cannot be found, then R arrays will be converted to Python lists, which are a lot more inefficient than Numeric arrays. I strongly suggest to install Numeric. If you have installed some previous version of RPy, just go to (c). To install RPy follow the steps: (a) First of all, you *must* check that you have built R with the configure option '--enable-R-shlib', in order to make R as a shared library. If not, the following steps should be enough: make distclean ./configure --enable-R-shlib make make install (Solaris users, please, see the note (a) below.) (b) Then, configure the path to the R library. You have several ways to do this (substitute RHOME with the path where R is installed, usually /usr/local/lib/R): o make a link to RHOME/bin/libR.so in /usr/local/lib or /usr/lib, then run 'ldconfig', o or, put the following line in your .bashrc (or equivalent): export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:RHOME/bin o or, edit the file /etc/ld.so.conf and add the following line: RHOME/bin and then, run 'ldconfig'. (c) Now, just type: python setup.py install and that's all! If you want, you can run the regression tests located in the 'tests' directory, just read the README file in that directory. For a quickier test, launch the Python interpreter and import the module 'rpy': Python 2.2 (#2, Dec 23 2001, 16:30:35) [GCC 2.95.4 20010703 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import rpy >>> If you get some error, refer to TROUBLESHOOTING below. If you want to test the module without installing it, do: python setup.py build Then, cd to build/lib.-/ and try to import the module. *** NOTES *** (a) Solaris users must change the line: LIBR_LDFLAGS = -shared in the file 'Makeconf' on the R source directory, for the line: LIBR_LDFLAGS = -shared -symbolic before recompiling the R library. (b) It has been reported that it may be necessary, in some situations, to completely remove the R sources, to unpack it again, and to compile to R library with the new options. Windows Binary Installation: ---------------------------- The Windows version of RPy is provided as a binary bundle. It is compiled with Python 2.3 and with Numeric support. Before installing RPy, make sure you have installed: o Python 2.2 o R (a recent version) o Numeric (http://numpy.sf.net) o win32all, windows extensions from Mark Hammond (http://starship.python.net/crew/mhammond/win32/Downloads.html) Then, just download the file 'rpy-0.3.win32-py2.2.exe', and execute it. You may want to download the documentation, also, which is in a separate bundle. Finally, make sure that the R bin directory is in your path. This holds the R.dll that python needs to load for rpy to work. For R version 1.6.1 this path is (by default) C:\Program Files\R\rw1061\bin\ For windows 98 or ME it is easier to use the path C:\Progra~1\R\rw1061\bin instead. Under Windows 2000 right click on "My Computer" select properties. Now click the Advanced tab and select environment variables. Finally edit the path variable under system variables and add C:\Program Files\R\rw1061\bin\ to your path. Make sure that all paths are seperated by semi-colons. All others need to edit the Autoexec.bat file and add a line similar to: set PATH=%PATH%;C:\Progra~1\R\rw1061\bin near the end. *** NOTES *** Please, read the section 'Caveat and bugs' of the reference manual, for details on some limitations of the Windows version. Many thanks to Rene Hagendoorn, who provides the patches for making the Windows version. Windows Source Installation --------------------------- To build RPy for Windows from scratch using Visual C++: Step 0: Unpack the rpywin source package (rpy-X.YY.zip) Step 1: Install the latest version of Windows R from cran.r-project.org I put R 2.0.0 into C:\Program Files\R\rw2000 Step 2: Install the latest source code for R from cran.r-project.org I put this into C:\Program Files\R\src\R-2.0.0 Step 3: Install the tools described on the "Building R for Windows" web portal: http://www.murdoch-sutherland.com/Rtools/ I installed MinGW into C:\Program Files\MinGW I installed the "tools bundle" into C:\Program Files\R\tools Step 4: Modify the system path to include all of the tools you will need. I did this on Win2000 using Start -> Settings -> Control Panel -> System -> Advanced -> Environment Variables My path [with a newline added after each ';' for clarity, remove these for the actual variable value!] is: C:\Progra~1\Micros~3\Common\MSDev98\Bin; C:\Progra~1\Micros~3\VC98\BIN; C:\Progra~1\Micros~3\Common\TOOLS; C:\Progra~1\Micros~3\Common\TOOLS\WINNT; C:\Progra~1\Micros~2\Office; C:\WINNT\system32; C:\WINNT; C:\WINNT\System32\Wbem; C:\Progra~1\R\rw1081\bin; C:\Progra~1\R\tools; C:\Progra~1\R\tools\bin; C:\python23; IMPORTANT: Use the alternative 8 character name for any long names or names that contain spaces anywhere in the path. Note that this list includes several Visual C directories, the bin directory of the installed version of R, the tools directory, the MinGW bin directory, and the python directory. Step 5: Create a windows library entry point (lib) file from the R symbols file to use during linking. Open a command window, and change to the rpy directory. Then do set RHOME=C:\Progra~1\R\rw2000 lib /def:%RHOME%\src\gnuwin32\R.exp /machine:ix86 /out:%RHOME%/bin/Rdll.lib [The lib command should be all on one line.] ALTERNATIVE (added by Matjaz Kukar) You may also using pexports, see distutils documentation or http://starship.python.net/crew/kernr/mingw32/Notes.html): pexports %RHOME%/bin/R.dll > %RHOME%/bin/Rdll.def lib/def:%RHOME%/bin/Rdll.def /out:%RHOME%/bin/Rdll.lib /machine:ix86 Somehow, by this approach more external variables from R.dll may be linked with, if declared as __declspec(dllimport) FILE *R_Outputfile; __declspec(dllimport) int UserBreak; Puzzling fact: UserBreak can be linked with in both cases, whereas R_Outputfile only in the second (pexports) case. Step 6: Build rpy: Start the compilation with python setup.py build Step 7: Install rpy: python setup.py install Step 8: Create binary install file (optional) python setup.py bdist --formats=windist The installer will be placed in the dist/ subdirectory. All done! ***NOTE*** ------------------------------------------------------ For Visual C++ 7 for Python 2.3, you may get the following error message: "Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed." This is a bug in how msvccompiler.py (distutils module) handles VC7. To correct this change line 212 from if len (self.__paths) == 0: to if False: # len (self.__paths) == 0: 3. USING RPy For details see the documentation in the 'doc' directory. As a quick example, try the following session: >>> from rpy import * >>> >>> values = [r.dchisq(x, 4) for x in r.seq(0, 10, by=0.1)] >>> r.par(ask=1, ann=0) >>> r.plot(values, type='lines') and voila!, the graph of the density of a chi squared distribution with four degrees of freedom should appear. Some more sofisticated examples can be found in the 'examples' directory. Refer to the RPy documentation for more info on the interface, and to the R Programming Language manuals, which can be found on http://www.r-project.org In general, every line of the R manuals can be translated almost directly to Python. 4. TROUBLESHOOTING If you get a Distutils execution error which says that R couldn't be executed: Traceback (most recent call last): ... distutils.errors.DistutilsExecError: couldn't execute the R interpreter. Check whether R is in the execution path then make sure that you have R installed and that it is in the execution path. The setup.py script uses the command 'R RHOME' to find out the location of the R libraries. You should check that this command returns the correct path. If you get errors from the C compiler or linker, then you should check that the headers files are under ${RHOME}/include and that 'libR.so' is under ${RHOME}/bin, where RHOME is what the execution of 'R RHOME' returns. If you get an error when importing the 'rpy' module from Python, check that you have built R with the configure option '--enable-R-shlib'. Make sure that you followed steps (a) and (b) of the installation procedure, described in section 2. If you have other problems, please, check the FAQ on the website or send me a message to the address below. 5. MAILING LIST Please report bugs, comments, questions, and suggestions to the rpy mailing list (rpy-list@lists.sourceforge.net). Subscription information and archives are available at: http://lists.sourceforge.net/lists/listinfo/rpy-list 6. CONTACT INFO Please, report bugs, comments and suggestions to the rpy mailing list. If you prefer, you can fill a bug or feature request form on the Sourceforge project page, http://rpy.sourceforge.net If both of these methods fail to resolve your problem, _then_ you may contact the maintainer. (He does have other work and a life, you know.) 7. LICENSE RPy is subject to the Mozilla Public License Version 1.1 (the "License"); you may not use RPy except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ (or see the file MPL_LICENSE) Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the RPy python module. The Initial Developer of the Original Code is Walter Moreira. Portions created by the Initial Developer are Copyright (C) 2002 the Initial Developer. All Rights Reserved. Contributor(s): Gregory R. Warnes (Maintainer) Alternatively, RPy may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL", see the file GPL_LICENSE), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL", see the file LGPL_LICENSE), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. ====== - Walter Moreira (Author) - Gregory Warnes (Maintainer) rpy-1.0.3/rpy.py0000644000076700000240000002306611001405376012701 0ustar warnesstaff# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # High level module for managing the lookup of R objects. # # $Id: rpy.py 489 2008-04-16 14:19:47Z warnes $ # # from __future__ import nested_scopes from rpy_options import rpy_options import rpy_io import UserDict import time, os, sys, atexit, glob import rpy_tools # If we cannot import Numeric, it should have been detected at # installation time and RPy should have been compiled properly. So, # don't complain. try: from numpy import * HAS_NUMERIC = 3 except ImportError: try: from Numeric import * HAS_NUMERIC = 1 except ImportError: HAS_NUMERIC = 0 pass # Get necessary paths and version information RHOME=os.environ.get('RHOME',None) if not RHOME: if rpy_options['RHOME'] is not None: RHOME = rpy_options['RHOME'] else: RHOME = rpy_tools.get_R_HOME() if rpy_options['RVERSION'] is not None: RVERSION = rpy_options['RVERSION'] else: RVERSION = rpy_tools.get_R_VERSION(RHOME) if rpy_options['RVER'] is not None: RVER = rpy_options['RVER'] else: RVER = rpy_tools.get_R_VERSION_CODE(RVERSION) if rpy_options['RUSER'] is not None: RUSER = rpy_options['RUSER'] else: RUSER = rpy_tools.get_R_USER() VERBOSE=rpy_options['VERBOSE'] if VERBOSE: print "RHOME=",RHOME print "RVERSION=",RVERSION print "RVER=",RVER print "RUSER=",RUSER # Push these into the environment for rpymodule to pick up os.environ['RPY_RHOME']=RHOME os.environ['RPY_RVERSION']=RVERSION os.environ['RPY_RVER']=RVER os.environ['RPY_RUSER']=RUSER # Push R_HOME into the environment for the R shared library/DLL to pick up os.environ['R_HOME']=RHOME if sys.platform=='win32': import win32api os.environ['PATH'] += ';' + os.path.join(RHOME,'bin') os.environ['PATH'] += ';' + os.path.join(RHOME,'modules') os.environ['PATH'] += ';' + os.path.join(RHOME,'lib') # Load the R dll using the explicit path # First try the bin dir: Rlib = os.path.join( RHOME, 'bin', 'R.dll') # Then the lib dir: if not os.path.exists(Rlib): Rlib = os.path.join( RHOME, 'lib', 'R.dll') # Otherwise fail out! if not os.path.exists(Rlib): raise RuntimeError("Unable to locate R.dll within %s" % RHOME) if VERBOSE: print "Loading the R DLL %s .." % Rlib, sys.stdout.flush() win32api.LoadLibrary( Rlib ) if VERBOSE: print "Done." sys.stdout.flush() # load the version of rpy that matches the verison of R we're using if VERBOSE: print "Loading Rpy version %s .." % RVER, sys.stdout.flush() try: command = "import _rpy%s as _rpy" % RVER exec(command) except Exception, e: raise RuntimeError( str(e) + """ RPy module can not be imported. Please check if your rpy installation supports R %s. If you have multiple R versions installed, you may need to set RHOME before importing rpy. For example: >>> from rpy_options import set_options >>> set_options(RHOME='c:/progra~1/r/rw2011/') >>> from rpy import * """ % RVERSION) if VERBOSE: print "Done." sys.stdout.flush() # Version from rpy_version import rpy_version # Symbolic names for conversion modes TOP_CONVERSION = 4 PROC_CONVERSION = 4 CLASS_CONVERSION = 3 BASIC_CONVERSION = 2 VECTOR_CONVERSION = 1 NO_CONVERSION = 0 NO_DEFAULT = -1 # Wrap a function in safe modes to avoid infinite recursion when # called from within the conversion system def with_mode(i, fun): def f(*args, **kwds): try: e = get_default_mode() set_default_mode(i) return fun(*args, **kwds) finally: set_default_mode(e) return f # Manage the global mode def set_default_mode(mode): _rpy.set_mode(mode) def get_default_mode(): return _rpy.get_mode() # Three new exceptions # base exception RPyException = _rpy.RPy_Exception; # R <-> Python conversion exception RPyTypeConversionException = _rpy.RPy_TypeConversionException; # Exception raised by R RPyRException = _rpy.RPy_RException # for backwards compatibility RException = RPyException Robj = _rpy.Robj # I/O setters set_rpy_output = _rpy.set_output set_rpy_input = _rpy.set_input get_rpy_output = _rpy.get_output get_rpy_input = _rpy.get_input if sys.platform != 'win32': set_rpy_showfiles = _rpy.set_showfiles get_rpy_showfiles = _rpy.get_showfiles # Default I/O to functions in the 'rpy_io' module if rpy_options['SETUP_WRITE_CONSOLE']: set_rpy_output(rpy_io.rpy_output) else: print "\nSkipping initialization of R console *write* support.\n" if rpy_options['SETUP_READ_CONSOLE']: set_rpy_input(rpy_io.rpy_input) else: print "\nSkipping initialization of R console *read* support.\n" if rpy_options['SETUP_SHOWFILES']: if sys.platform != 'win32': set_rpy_showfiles(rpy_io.rpy_showfiles) else: print "\nSkipping initialization of R console *file viewer* support\n" # Functions for processing events import threading r_events = _rpy.r_events _r_thread = None _r_events_running = threading.Event() _r_lock = threading.Lock() def r_eventloop(): while _r_events_running.isSet(): _r_lock.acquire() r_events() _r_lock.release() time.sleep(0.2) def start_r_eventloop(): global _r_thread if _r_thread and _r_thread.isAlive(): return _r_thread = threading.Thread(target=r_eventloop) _r_thread.setDaemon(1) _r_events_running.set() _r_thread.start() return _r_thread def stop_r_eventloop(): _r_events_running.clear() if _r_thread: _r_thread.join() if sys.platform != 'win32': atexit.register(stop_r_eventloop) start_r_eventloop() # This function unifies the case of results of length one, which RPy # returns as single values, and results of length greater than one, # which are lists. def as_list(obj): try: obj+[] return obj except: return [obj] # A special dict to wrap the arguments in safe modes. It would be # easier with 2.2, subclassing directly from type 'dict'. class Dict_With_Mode(UserDict.UserDict): def __init__(self, initialdata): self.data = initialdata def __setitem__(self, key, value): val = with_mode(BASIC_CONVERSION, value) if type(key) in [type(''), type(())]: self.data[key] = val else: self.data[with_mode(BASIC_CONVERSION, key)] = val # Tables for {PROC,CLASS}_CONVERSION modes class_table = Dict_With_Mode(_rpy.__class_table__) proc_table = Dict_With_Mode(_rpy.__proc_table__) # main class class R: def __init__(self): if rpy_options['VERBOSE']: print "Creating the R object 'r' ..", sys.stdout.flush() _rpy.r_init(HAS_NUMERIC); _rpy.set_mode(NO_DEFAULT) self.get = _rpy.get_fun('get') # this must happen before any calls to self or its methods! self("options(error = expression(NULL))") # don't abort on errors, just raise them! # necessary for non-interactive execution self.TRUE = self.__getitem__('T') self.FALSE = self.__getitem__('F') self.NA = self('NA') self.NAN = self('as.double(NA)') self.helpfun = with_mode(NO_CONVERSION, self.__getitem__('help')) self.help = self.__help__ # override r.help() # workaround for plotting bug under win32 if sys.platform == 'win32': self('options(windowsBuffered=FALSE)') if rpy_options['VERBOSE']: print " Done" sys.stdout.flush() def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): return object.__getattr__(name) if len(name) > 1 and name[-1] == '_' and name[-2] != '_': name = name[:-1] name = name.replace('__', '<-') name = name.replace('_', '.') return self.__getitem__(name) def __getitem__(self, name): # use r's 'get' function here, because the rpy one only handles functions! obj = self.__dict__[name] = self.__dict__.get(name, self.get(name)) return obj def __call__(self, s): return self.eval(self.parse(text=s)) def __help__(self, *arg, **kw): """ R's help funtion now returns an object of class help that must be printed (by R) in order to be rendered. This function forces printing so that the user get the expected behavior. """ helpobj = self.helpfun(*arg, **kw) self.print_(helpobj) def __repr__(self): Rver = self.__getitem__('R.version.string') return "RPy version %s [%s]" % (rpy_version, Rver) def __str__(self): return repr(self) def __cleanup__(self): _rpy.r_cleanup() del(self) # main instance r = R() # disable the printing of errors from within R, they will be handed by # passing a fault to python r.options(show_error_messages=0) # That's all... rpy-1.0.3/rpy_io.py0000644000076700000240000000305010411116620013352 0ustar warnesstaff# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # Basic io. # # $Id: rpy_io.py 181 2005-07-14 06:37:58Z warnes $ # # import sys import os # Input and output to sys.std{in,out} def rpy_output(s): s = s.replace('_\b','') sys.stdout.write(s) sys.stdout.flush() def rpy_input(prompt, n): rpy_output(prompt) return sys.stdin.readline()[:n-1] # Show the files in a terminal with a standard pager def showfiles_tty(files, headers, title, delete): PAGER = 'less' for file, header in zip(files, headers): os.system('%(PAGER)s %(file)s' %locals()) # Show the files via R_stdout (useful for using with idle) def showfiles_common(files, headers, title, delete): rpy_output(title) for file, header in zip(files, headers): rpy_output(header) for line in open(file).readlines(): rpy_output(line) # Default rpy_showfiles = showfiles_common rpy-1.0.3/rpy_options.py0000755000076700000240000000420010736743616014464 0ustar warnesstaff#!/usr/bin/env python # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # allow users to set RHOME and HAS_NUMERIC explicitly # # $Id$ # import os.path rpy_options = { 'RHOME':None, # R Installation Directory 'RVERSION':None, # R Version *string* 'RVER':None, # R Version *number* 'RUSER':None, # R User's Home Directory 'USE_NUMERIC':None, # Is Numeric module available 'VERBOSE':False, # Should status messages be displated. 'SETUP_READ_CONSOLE': True, # Set to False to prevent standard console read config 'SETUP_WRITE_CONSOLE': True, # Set to False to prevent standard console write config 'SETUP_SHOWFILES': True # Set to False to prevent standard console file viewerd config } def set_options(RHOME=None, USE_NUMERIC=None, VERBOSE=None, SETUP_READ_CONSOLE=None, SETUP_WRITE_CONSOLE=None, SETUP_SHOWFILES=None): if RHOME != None and os.path.isdir(RHOME): rpy_options['RHOME'] = RHOME if USE_NUMERIC != None and USE_NUMERIC in [True, False]: rpy_options['USE_NUMERIC'] = USE_NUMERIC if VERBOSE != None and VERBOSE in [True, False]: rpy_options['VERBOSE'] = VERBOSE if SETUP_READ_CONSOLE != None and SETUP_READ_CONSOLE in [True, False]: rpy_options['SETUP_READ_CONSOLE'] = VERBOSE if SETUP_WRITE_CONSOLE != None and SETUP_WRITE_CONSOLE in [True, False]: rpy_options['SETUP_WRITE_CONSOLE'] = VERBOSE if SETUP_SHOWFILES != None and SETUP_SHOWFILES in [True, False]: rpy_options['SETUP_SHOWFILES'] = VERBOSE rpy-1.0.3/rpy_tools.py0000644000076700000240000001130610746441343014124 0ustar warnesstaffimport os, os.path, sys, re """ rpytools_py provides utility functions used for installing or running rpy """ if sys.platform=="win32": # Windows doesn't define this although it is straightforward... def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import os if os.name in ['nt', 'dos', 'os2'] : # use Dos style command shell for NT, DOS and OS/2 pipe = os.popen(cmd + ' 2>&1', 'r') else : # use Unix style for all others pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text else: from commands import getstatusoutput def get_R_HOME(force_exec=False): """ Determine the R installation path Set force_exec to avoid using the registry. """ # step 1: try using the environment variable rhome = os.getenv("R_HOME") # step 2: (Windows) Try the registry if not rhome and sys.platform == 'win32' and not force_exec: try: import win32api, win32con hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "Software\\R-core\\R", 0, win32con.KEY_QUERY_VALUE ) # get the base directory rhome = win32api.RegQueryValueEx( hkey, "InstallPath" )[0] win32api.RegCloseKey( hkey ) except: print "Unable to determine R version from the registry. Trying another method." pass # failover to exec method # step 3: Try executing R to find out if not rhome or not os.path.exists(rhome): if sys.platform == 'win32': stat, rhome = getstatusoutput('R RHOME') else: stat, rhome = getstatusoutput('R RHOME | tail -n 1') if stat or len(rhome)<=0: raise RuntimeError("Couldn't execute the R interpreter.\n" "Check whether R is in the execution path.") rhome = rhome.strip() return rhome def get_R_VERSION(RHOME=None, force_exec=False): """ Determine the installed version of R. Set force_exec=True to avoid using the registry. """ rver = None # step 1: (Windows) Try the registry if (not RHOME) and (sys.platform == 'win32') and (not force_exec): try: # Use the registry to find where R.dll is import win32api, win32con hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "Software\\R-core\\R", 0, win32con.KEY_QUERY_VALUE ) # get the current version rver = win32api.RegQueryValueEx( hkey, "Current Version" )[0] win32api.RegCloseKey( hkey ) except: print "Unable to determine R version from the registry." + \ " Trying another method." pass # failover to exec method # step 2: Try executing R to determine the version if not rver: if (not RHOME) or (not os.path.exists(RHOME)): RHOME = get_R_HOME(force_exec) rexec = os.path.join(RHOME, 'bin', 'R') stat, output = getstatusoutput('"%s" --version' % rexec ) if stat or len(output)<=0: raise RuntimeError("Couldn't execute the R interpreter" + " `%s'.\n" % rexec ) # edd 05 Apr 2006 version = re.search("R +([0-9]\.[0-9]\.[0-9])", output) version = re.search(" +([0-9]\.[0-9]\.[0-9])", output) if not version: raise RuntimeError("Couldn't obtain version number from output\n" "of `R --version'.\n") rver = version.group(1) return rver.strip() def get_R_VERSION_CODE( verstr=None ): if verstr is None: verstr = get_R_VERSION() rmajor,rminor,rpatch=map( lambda x:int(x), verstr.split('.')) rver = "%1d%02d%1d" % (rmajor, rminor, rpatch) return rver def get_R_USER(): RUSER = os.getenv("R_USER") if not os.path.exists(str(RUSER)): RUSER = os.getenv("HOME") if not os.path.exists(str(RUSER)) and sys.platform == 'win32': RUSER = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") if not os.path.exists(str(RUSER)): RUSER=os.getcwd() return RUSER def get_PYTHON_DIR(): ver = "%d.%d" % sys.version_info[0:2] try: import win32api, win32con hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\InstallPath" % ver, 0, win32con.KEY_QUERY_VALUE ) # get the base directory PYTHON_DIR = win32api.RegQueryValueEx( hkey, "")[0] win32api.RegCloseKey( hkey ) except: raise RuntimeError("Unable to determine Python install location from the registry") if not os.path.exists(PYTHON_DIR): raise RuntimeError("Python install location from the registry does not exist: `%s'" % PYTHON_DIR ) return PYTHON_DIR rpy-1.0.3/rpy_version.py0000644000076700000240000000002611012207206014427 0ustar warnesstaffrpy_version = "1.0.3" rpy-1.0.3/rpy_wintools.py0000644000076700000000000000243410723656257014646 0ustar warneswheel # import os, os.path, sys, shutil import rpy_tools def get_RHOMES(): # Standard R Rhomes = get_RHOMES_inner("R") # RStat, commercially packaged R from Random Technologies LLC Rhomes.extend( get_RHOMES_inner("RStat") ) if os.environ.get('RHOME', None): Rhomes.insert(0, os.environ.get('RHOME', None)) return Rhomes def get_RHOMES_inner(progname="R"): from win32com.shell import shell, shellcon program_files = shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILES, 0, 0) Rdir = os.path.join(program_files, progname) Rhomes = [] if os.path.exists(Rdir): RVersionDirs = os.listdir(Rdir) for thisRVersionDir in RVersionDirs: BasePath = os.path.join(Rdir, thisRVersionDir) DLLPath1 = os.path.join(BasePath, "bin", "R.dll" ) DLLPath2 = os.path.join(BasePath, "lib", "R.dll" ) if os.path.exists(DLLPath1) or os.path.exists(DLLPath2): Rhomes.append( BasePath ) return Rhomes if __name__ == '__main__': RHomes = get_RHOMES() print "Found", len(RHomes), " R Installations:" for path in RHomes: print " ", path print rpy-1.0.3/setup.py0000644000076700000240000001604311001663072013223 0ustar warnesstaff""" This file builds rpy. It has been adapted to allow multiple versions of the rpy shared library to be included in the build. To enable this, set the environment variable "RHOMES" to a colon-delimited (semicolon-delimited on MS-Windows) list of R installation directories. For linux csh derivatives (including tcsh) use something like setenv RHOMES /usr/local/R-2.1.0/lib/R:/usr/local/R-2.1.1/lib/R python setup.py bdist For linux sh derivatives (including bash) use something like: RHOMES=/usr/local/R-2.1.0/lib/R:/usr/local/R-2.1.1/lib/R export RHOMES python setup.py bdist For windows, edit setup.32 to include the correct paths, then use something like: copy setup.Win32 setup.cfg python setup.py build --compiler=mingw32 bdist_wininst setup.py will automatically look in C:\Program Files\R to determine which versions of R are installed, and will build an installer that can be used for each of these R versions. See the files INSTALL.UNIX and INSTALL.WINDOWS for more details. """ DEBUG=True import os, os.path, sys, shutil, re from distutils.core import setup, Extension from distutils.sysconfig import * from distutils.errors import * import rpy_tools if sys.platform=="win32": import rpy_wintools # Get list of R Home directories that we will be processing try: if sys.platform=="win32": RHOMES = os.environ['RHOMES'].split(';') else: RHOMES = os.environ['RHOMES'].split(':') except: RHOMES = [] print "RHOMES=", RHOMES print "DEBUG=", DEBUG if not RHOMES: if sys.platform=="win32": RHOMES=rpy_wintools.get_RHOMES() else: RHOMES = [rpy_tools.get_R_HOME(force_exec=False)] print "Setting RHOMES to ", RHOMES # ensure RHOMES is in ascii, since most command line tools are unhappy with unicode... RHOMES = map( lambda x: x.encode('ascii'), RHOMES ) # On windows, check for/create the python link library #if sys.platform=="win32": # rpy_wintools.CreatePythonWinLib() # On Mac OS X ("darwin") it is necessary to change the symlink # /Library/Frameworks/R.framework/Versions/Current # to point to the current version of R in # /Library/Frameworks/R.framework/Versions/X.Y # for that version of R to execute. So, we need to store the original # symlink here so we can restore it when we are done if sys.platform=="darwin": darwin_original_version = os.readlink("/Library/Frameworks/R.framework/Versions/Current") modules = [] for RHOME in RHOMES: RHOME = RHOME.strip() if DEBUG: # to avoid strict prototypes errors from R includes get_config_vars()['OPT'] = '-g -Wall' else: # to avoid strict prototypes errors from R includes get_config_vars()['OPT'] = '-DNDEBUG -g -O3 -Wall' # get the Python version if sys.version[:3] >= '2.2': DEFINE = [] UNDEF = ['PRE_2_2'] else: DEFINE = [('PRE_2_2', None)] UNDEF = [] # configure the R paths #if sys.platform=="darwin": # version = # if os.symlink("/Library/Frameworks/R.framework/Versions/Current") # if RHOME.endswith('/'): # RHOME = RHOME[:-1] # print "RHOME=",os.path.join(os.path.dirname(RHOME), # os.readlink(RHOME) ) # sys.exit() RVERSION = rpy_tools.get_R_VERSION(RHOME, force_exec=True) RVER = rpy_tools.get_R_VERSION_CODE(RVERSION) print "### Using R verion %s installed at %s ###" % (RVERSION, RHOME) r_libs = [ # Different verisons of R put .so/.dll in different places os.path.join(RHOME, 'bin'), # R 2.0.0+ os.path.join(RHOME, 'lib'), # Pre 2.0.0 ] print "RHOME=",RHOME base_source_files = ["src/rpymodule.c", "src/R_eval.c", "src/io.c"] exists = os.path.exists mtime = os.path.getmtime # Make one copy of the source files for this R version source_files = [] for f in base_source_files: # file.c => file2010.c nfile = f[0:-2] + RVER + '.c' print "copying %s -> %s" % (f, nfile) if (not exists(nfile)) or ( mtime(f) > mtime(nfile) ): shutil.copy(f, nfile) source_files.append(nfile) if sys.platform=='win32': include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src' ] libraries= ['R'] library_dirs = r_libs runtime_libs = [] extra_compile_args= [] source_files = source_files + ["src\\setenv.c"] elif sys.platform=='darwin': include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src' ] libraries=['R'] library_dirs= r_libs runtime_libs = r_libs extra_compile_args=[] elif sys.platform=='osf1V5': include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src' ] libraries=['R','Rlapack'] library_dirs = r_libs runtime_libs = r_libs extra_compile_args=["-shared"] source_files = source_files + ["src/setenv.c"] else: # unix-like systems, this is known to work for Linux and Solaris include_dirs = [ os.path.join(RHOME.strip(), 'include'), 'src', '/usr/share/R/include' ] libraries=['R','Rlapack'] library_dirs = r_libs runtime_libs = r_libs extra_compile_args=["-shared"] source_files = source_files + ["src/setenv.c"] # Discover which array packages are present try: import numpy DEFINE.append(('WITH_NUMERIC', '3')) DEFINE.append(('PY_ARRAY_TYPES_PREFIX', 'PyArray_')) include_dirs.append(numpy.get_include()) except ImportError: # fall back to Numeric try: import Numeric DEFINE.append(('WITH_NUMERIC', '1')) except ImportError: UNDEF.append('WITH_NUMERIC') # get the RPy version from rpy_version import rpy_version LONG_DESC = """RPy provides a robust Python interface to the R programming language. It can manage all kinds of R objects and can execute arbitrary R functions. All the errors from the R language are converted to Python exceptions.""" # use R version specific shared library name shlib_name = "_rpy%s" % RVER DEFINE.append( ('RPY_SHNAME', shlib_name)) DEFINE.append( ('INIT_RPY', 'init_rpy%s' % RVER ) ) # add debugging modules.append( Extension( shlib_name, source_files, include_dirs=include_dirs, libraries=libraries, library_dirs=library_dirs, define_macros=DEFINE, undef_macros=UNDEF, extra_compile_args=extra_compile_args, runtime_library_dirs = runtime_libs, ) ) setup(name="rpy", version=rpy_version, description="Python interface to the R language", maintainer="Gregory R. Warnes", maintainer_email="warnes@bst.rochester.edu", url="http://rpy.sourceforge.net", license="GPL", long_description=LONG_DESC, py_modules=['rpy', 'rpy_io', 'rpy_version', 'rpy_tools', 'rpy_options', 'rpy_wintools'], ext_modules=modules ) rpy-1.0.3/src/0000755000076700000240000000000011012207656012300 5ustar warnesstaffrpy-1.0.3/src/io.c0000644000076700000240000001417310736745436013100 0ustar warnesstaff/* * $Id: io.c 393 2008-01-02 17:34:28Z warnes $ * Input/Output routines */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "RPy.h" #define ENTER_PY { PyThreadState* tstate = NULL;\ if (_PyThreadState_Current == NULL) {\ tstate = PyThreadState_New(my_interp);\ PyEval_AcquireThread(tstate);\ } #define LEAVE_PY if (tstate) {\ PyEval_ReleaseThread(tstate);}\ } PyObject *rpy_output=NULL, *rpy_input=NULL, *rpy_showfiles=NULL; /* Show the traceback of an exception which occurred in a I/O process, except when the error is a KeyboardInterrupt, in which case abort the R interpreter */ void RPy_ShowException() { PyObject *err; if ((err = PyErr_Occurred())) { if (PyErr_GivenExceptionMatches(err, PyExc_KeyboardInterrupt)) { interrupt_R(0); } else { PyErr_WriteUnraisable(err); PyErr_Clear(); } } } void RPy_WriteConsole(char *buf, int len) { PyOS_sighandler_t old_int; PyObject *dummy; /* It is necessary to restore the Python handler when using a Python function for I/O. */ old_int = PyOS_getsig(SIGINT); PyOS_setsig(SIGINT, python_sigint); if (rpy_output) { ENTER_PY dummy = PyObject_CallFunction(rpy_output, "s", buf); Py_XDECREF(dummy); LEAVE_PY } signal(SIGINT, old_int); RPy_ShowException(); } #ifdef _WIN32 int RPy_ReadConsole(char *prompt, char *buf, int len, int addtohistory) #else int RPy_ReadConsole(char *prompt, unsigned char *buf, int len, int addtohistory) #endif { PyObject *input_data; PyOS_sighandler_t old_int; if (!rpy_input) return 0; old_int = PyOS_getsig(SIGINT); PyOS_setsig(SIGINT, python_sigint); ENTER_PY start_events(); input_data = PyObject_CallFunction(rpy_input, "si", prompt, len); stop_events(); LEAVE_PY signal(SIGINT, old_int); RPy_ShowException(); if (!input_data) { PyErr_Clear(); return 0; } snprintf(buf, len, "%s", PyString_AsString(input_data)); Py_DECREF(input_data); return 1; } int RPy_ShowFiles(int nfile, char **file, char **headers, char *wtitle, int del, char *pager) { PyObject *pyfiles, *pyheaders, *result, *f, *h; PyOS_sighandler_t old_int; int i; if (rpy_showfiles==NULL) return 0; old_int = PyOS_getsig(SIGINT); PyOS_setsig(SIGINT, python_sigint); ENTER_PY pyfiles = PyList_New(0); pyheaders = PyList_New(0); if (!(pyfiles && pyheaders)) { return 0; } for (i=0; i (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * Evaluation of R expressions. * * $Id: R_eval.c 363 2007-11-12 23:27:48Z warnes $ * */ #include /* The Python original SIGINT handler */ PyOS_sighandler_t python_sigint; /* Indicates whether the R interpreter was interrupted by a SIGINT */ int interrupted = 0; /* Abort the current R computation due to a SIGINT */ void interrupt_R(int signum) { interrupted = 1; error("Interrupted"); } /* Evaluate a SEXP. It must be constructed by hand. It raises a Python exception if an error ocurred in the evaluation */ SEXP do_eval_expr(SEXP e) { SEXP res; int error = 0; PyOS_sighandler_t old_int; /* Enable our handler for SIGINT inside the R interpreter. Otherwise, we cannot stop R calculations, since SIGINT is only processed between Python bytecodes. Also, save the Python SIGINT handler because it is necessary to temporally restore it in user defined I/O Python functions. */ stop_events(); #ifdef _WIN32 old_int = PyOS_getsig(SIGBREAK); #else old_int = PyOS_getsig(SIGINT); #endif python_sigint = old_int; signal(SIGINT, interrupt_R); interrupted = 0; res = R_tryEval(e, R_GlobalEnv, &error); #ifdef _WIN32 PyOS_setsig(SIGBREAK, old_int); #else PyOS_setsig(SIGINT, old_int); #endif start_events(); if (error) { if (interrupted) { PyErr_SetNone(PyExc_KeyboardInterrupt); } else PyErr_SetString(RPy_RException, get_last_error_msg()); return NULL; } return res; } /* Evaluate a function given by a name (without arguments) */ SEXP do_eval_fun(char *name) { SEXP exp, fun, res; fun = get_fun_from_name(name); if (!fun) return NULL; PROTECT(fun); PROTECT(exp = allocVector(LANGSXP, 1)); SETCAR(exp, fun); PROTECT(res = do_eval_expr(exp)); UNPROTECT(3); return res; } /* * Get an R **function** object by its name. When not found, an exception is * raised. The checking of the length of the identifier is needed to * avoid R raising an error causing Python to dump core. */ SEXP get_fun_from_name(char *ident) { SEXP obj; /* For R not to throw an error, we must check the identifier is neither null nor greater than MAXIDSIZE */ if (!*ident) { PyErr_SetString(RPy_Exception, "attempt to use zero-length variable name"); return NULL; } if (strlen(ident) > MAXIDSIZE) { PyErr_SetString(RPy_Exception, "symbol print-name too long"); return NULL; } #if R_VERSION < 0x20000 obj = Rf_findVar(Rf_install(ident), R_GlobalEnv); #else /* * For R-2.0.0 and later, it is necessary to use findFun to get * functions. Unfortunately, calling findFun on an undefined name * causes a segfault! * * Solution: * * 1) Call findVar on the name * * 2) If something has the name, call findFun * * 3) Raise an error if either step 1 or 2 fails. */ obj = Rf_findVar(Rf_install(ident), R_GlobalEnv); if (obj != R_UnboundValue) obj = Rf_findFun(Rf_install(ident), R_GlobalEnv); #endif if (obj == R_UnboundValue) { PyErr_Format(RPy_Exception, "R Function \"%s\" not found", ident); return NULL; } return obj; } /* Obtain the text of the last R error message */ const char *get_last_error_msg() { SEXP msg; msg = do_eval_fun("geterrmessage"); return CHARACTER_VALUE(msg); } rpy-1.0.3/src/robjobject.h0000644000076700000240000000427710411116614014601 0ustar warnesstaff/* * $Id: robjobject.h 299 2006-03-22 22:13:54Z warnes $ * The Robj type */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* The R object type */ typedef struct { PyObject_HEAD SEXP R_obj; /* R object itself */ int conversion; /* 0: no conversion 1: basic conversion 2: class conversion 3: proc conversion */ } RobjObject; #ifdef _WIN32 extern PyTypeObject Robj_Type; #else extern DL_IMPORT(PyTypeObject) Robj_Type; #endif #define Robj_Check(v) ((v)->ob_type == &Robj_Type) RobjObject *Robj_new(SEXP, int); rpy-1.0.3/src/RPy.h0000644000076700000240000001407210723655756013207 0ustar warnesstaff/* * $Id: RPy.h 384 2007-11-30 00:40:17Z warnes $ * Public API for calling R. */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef _RPY_H #define _RPY_H #ifdef _WIN32 # undef ERROR /* nameclash with Rext/RS.h */ # include # undef ERROR #endif /*_WIN32*/ #include #include #include #include #undef _POSIX_C_SOURCE #include #include #include #ifdef _WIN32 # define Win32 /* needed to get definition for UIMode */ # include "rpy_Rinterface.h" # undef Win32 # if R_VERSION < 0x20000 # include # else # include # endif #else # if R_VERSION < 0x20100 # include "rpy_Rinterface.h" # else # include # endif #endif /* _WIN32 */ #include /* must follow Graphics.h */ /* Missing definitions from Rinterface.h or RStartup.h */ # define CleanEd Rf_CleanEd extern void CleanEd(void); extern int R_CollectWarnings; # define PrintWarnings Rf_PrintWarnings extern void PrintWarnings(void); /****/ #include #ifdef WITH_NUMERIC # if WITH_NUMERIC == 3 # include "numpy/arrayobject.h" # define PY_ARRAY_MODULE_NAME "numpy" typedef npy_intp n_intp; # elif WITH_NUMERIC == 1 # include "Numeric/arrayobject.h" # define PY_ARRAY_MODULE_NAME "multiarray" typedef int n_intp; # else # error "unknown array variant" # endif #else typedef int n_intp; #endif #define xstr(s) str(s) #define str(s) #s #include "robjobject.h" #include "setenv.h" #define MAXIDSIZE 256 /* Conversion */ SEXP to_Robj(PyObject *); PyObject *to_Pyobj(SEXP); PyObject *to_Pyobj_table(SEXP); PyObject *to_Pyobj_with_mode(SEXP, int); #define NO_CONVERSION 0 #define VECTOR_CONVERSION 1 #define BASIC_CONVERSION 2 #define CLASS_CONVERSION 3 #define PROC_CONVERSION 4 #define TOP_MODE 4 /* R Evaluation */ SEXP do_eval_expr(SEXP e); SEXP do_eval_fun(char *); SEXP get_fun_from_name(char *); /* Three new exception */ extern PyObject *RPy_Exception; /* Base RPy exception */ extern PyObject *RPy_TypeConversionException; /* R<->Python conversion errors */ extern PyObject *RPy_RException; /* Errors from R */ const char *get_last_error_msg(void); /* For initializing R */ extern int Rf_initEmbeddedR(int argc, char *argv[]); extern void init_io_routines(void); /* I/O functions */ //#ifdef _WIN32 //__declspec(dllimport) FILE *R_Outputfile; //#else extern FILE *R_Outputfile; //#endif #ifdef _WIN32 extern void RPy_WriteConsole(char *, int); extern int RPy_ReadConsole(char *, char *, int, int); #endif extern void (*ptr_R_WriteConsole)(char *, int); extern int (*ptr_R_ReadConsole)(char *, unsigned char *, int, int); extern int (*ptr_R_ShowFiles)(int, char **, char **, char *, int, char *); #ifdef _WIN32 extern void R_WriteConsole(char *, int); extern int R_ReadConsole(char *, unsigned char *, int, int); extern void R_ProcessEvents(void); /* Windows R DLL Calls */ extern char *getDLLVersion(); extern void R_DefParams(Rstart); extern void R_SetParams(Rstart); extern void setup_term_ui(void); extern char *getRHOME(void); __declspec(dllimport) int UserBreak; #endif /* Setters for io functions */ PyObject *set_output(PyObject *self, PyObject *args); PyObject *set_input(PyObject *self, PyObject *args); PyObject *set_showfiles(PyObject *self, PyObject *args); PyObject *get_output(PyObject *self, PyObject *args); PyObject *get_input(PyObject *self, PyObject *args); PyObject *get_showfiles(PyObject *self, PyObject *args); /* Interrupt the R interpreter */ void interrupt_R(int); /* The Python original SIGINT handler */ extern PyOS_sighandler_t python_sigint; /* R function for jumping to toplevel context */ extern void jump_now(void); /* Global interpreter */ extern PyInterpreterState *my_interp; /* Signal whether R is running interactively */ extern int R_interact; /* RPy namespace */ extern PyObject *rpy; extern PyObject *rpy_dict; /* Pause/continue the event loop */ void stop_events(void); void start_events(void); /* Translation functions */ extern int to_Pyobj_proc(SEXP robj, PyObject **obj); extern int to_Pyobj_class(SEXP robj, PyObject **obj); extern int to_Pyobj_basic(SEXP robj, PyObject **obj); extern int to_Pyobj_vector(SEXP robj, PyObject **obj, int mode); /* Macros for handing quoted macro variables defined via command line arguments to compiler. */ #define MacroQuote_(x) #x #define MacroQuote(x) MacroQuote_(x) #endif /* _RPY_H */ rpy-1.0.3/src/rpy_Rinterface.h0000644000076700000240000001126310411116614015423 0ustar warnesstaff/* * $Id: rpy_Rinterface.h 299 2006-03-22 22:13:54Z warnes $ * This header file is to provide hooks for external GUIs such as GNOME and Cocoa. It is only used on Unix-alikes */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef RINTERFACE_H_ #define RINTERFACE_H_ #ifdef __cplusplus extern "C" { #endif #include #ifdef _WIN32 # if R_VERSION > 0x20010 # include # else # include "rpy_Startup.h" # endif #else # if R_VERSION < 0x20100 # include "rpy_Startup.h" # else # include # endif #endif /* from Defn.h */ /* this duplication will be removed in due course */ extern Rboolean R_Interactive; /* TRUE during interactive use*/ extern Rboolean R_Quiet; /* Be as quiet as possible */ extern Rboolean R_Slave; /* Run as a slave process */ extern Rboolean R_Verbose; /* Be verbose */ extern void R_RestoreGlobalEnv(void); extern void R_RestoreGlobalEnvFromFile(const char *, Rboolean); extern void R_SaveGlobalEnv(void); extern void R_SaveGlobalEnvToFile(const char *); extern void R_FlushConsole(void); extern void R_ClearerrConsole(void); extern void R_Suicide(char*); extern char* R_HomeDir(void); extern int R_DirtyImage; /* Current image dirty */ extern char* R_GUIType; extern void R_setupHistory(); extern char* R_HistoryFile; /* Name of the history file */ extern int R_HistorySize; /* Size of the history file */ extern int R_RestoreHistory; /* restore the history file? */ extern char* R_Home; /* Root of the R tree */ # define jump_to_toplevel Rf_jump_to_toplevel # define mainloop Rf_mainloop # define onintr Rf_onintr void jump_to_toplevel(void); void mainloop(void); void onintr(); #ifndef DEFN_H_ extern void* R_GlobalContext; /* Need opaque pointer type for export */ #endif void process_site_Renviron(); void process_system_Renviron(); void process_user_Renviron(); #include extern FILE * R_Consolefile; extern FILE * R_Outputfile; /* in sys-unix.c */ void R_setStartTime(void); void fpu_setup(Rboolean); /* formerly in src/unix/devUI.h */ #ifdef R_INTERFACE_PTRS #include #ifdef __SYSTEM__ # define extern #endif extern void (*ptr_R_Suicide)(char *); extern void (*ptr_R_ShowMessage)(char *); extern int (*ptr_R_ReadConsole)(char *, unsigned char *, int, int); extern void (*ptr_R_WriteConsole)(char *, int); extern void (*ptr_R_ResetConsole)(); extern void (*ptr_R_FlushConsole)(); extern void (*ptr_R_ClearerrConsole)(); extern void (*ptr_R_Busy)(int); extern void (*ptr_R_CleanUp)(SA_TYPE, int, int); extern int (*ptr_R_ShowFiles)(int, char **, char **, char *, Rboolean, char *); extern int (*ptr_R_ChooseFile)(int, char *, int); extern int (*ptr_R_EditFile)(char *); extern void (*ptr_R_loadhistory)(SEXP, SEXP, SEXP, SEXP); extern void (*ptr_R_savehistory)(SEXP, SEXP, SEXP, SEXP); extern int (*R_timeout_handler)(); extern long R_timeout_val; #ifdef HAVE_AQUA extern int (*ptr_R_EditFiles)(int, char **, char **, char *); #endif #endif #ifdef __SYSTEM__ # undef extern #endif #ifdef __cplusplus } #endif #endif /* RINTERFACE_H_ */ rpy-1.0.3/src/rpy_Startup.h0000644000076700000240000000676310411116614015014 0ustar warnesstaff/* * $Id: rpy_Startup.h 299 2006-03-22 22:13:54Z warnes $ * Definitions needed to interface with the R shared library */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef STARTUP_H_ #define STARTUP_H_ #include /* TRUE/FALSE */ #ifdef Win32 typedef int (*blah1) (char *, char *, int, int); typedef void (*blah2) (char *, int); typedef void (*blah3) (); typedef void (*blah4) (char *); typedef int (*blah5) (char *); typedef void (*blah6) (int); typedef enum {RGui, RTerm, LinkDLL} UImode; #endif /* Startup Actions */ typedef enum { SA_NORESTORE,/* = 0 */ SA_RESTORE, SA_DEFAULT,/* was === SA_RESTORE */ SA_NOSAVE, SA_SAVE, SA_SAVEASK, SA_SUICIDE } SA_TYPE; typedef struct { Rboolean R_Quiet; Rboolean R_Slave; Rboolean R_Interactive; Rboolean R_Verbose; Rboolean LoadSiteFile; Rboolean LoadInitFile; Rboolean DebugInitFile; SA_TYPE RestoreAction; SA_TYPE SaveAction; unsigned long vsize; unsigned long nsize; unsigned long max_vsize; unsigned long max_nsize; unsigned long ppsize; int NoRenviron; #ifdef Win32 char *rhome; /* R_HOME */ char *home; /* HOME */ blah1 ReadConsole; blah2 WriteConsole; blah3 CallBack; blah4 message; blah5 yesnocancel; blah6 busy; UImode CharacterMode; Rboolean DebugMenuitem; #endif } structRstart; typedef structRstart *Rstart; void R_DefParams(Rstart); void R_SetParams(Rstart); void R_SetWin32(Rstart); void R_SizeFromEnv(Rstart); void R_common_command_line(int *, char **, Rstart); void R_set_command_line_arguments(int argc, char **argv); void setup_Rmainloop(void); /* originally from Defn.h : */ void R_CleanUp(SA_TYPE, int, int); void R_StartUp(void); FILE *R_OpenInitFile(void); FILE *R_OpenSysInitFile(void); FILE *R_OpenSiteFile(void); #endif rpy-1.0.3/src/rpymodule.c0000644000076700000240000014063511011137502014464 0ustar warnesstaff/* * $Id: rpymodule.c 510 2008-05-09 21:16:59Z warnes $ * Implementation of the module '_rpy' and the 'Robj' type. */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include #if (R_VERSION >= R_Version(2,3,0)) # ifndef _WIN32 # define CSTACK_DEFNS // Enable definitions needed for stack checking control # endif #endif #include "RPy.h" #define NONAMELESSUNION #include #include #include /* Flag indicating whether Numpy/Numeric is available in this session * * This is necessary since Numpy/Numeric may not available at run time, even if * it was available at compile time. */ static int use_numeric=0; /* Local function definitions */ DL_EXPORT(void) INIT_RPY(void); /* Module initializer */ static PyObject *r_init(PyObject *self, /* Class initializer */ PyObject *args); static PyObject *r_cleanup(void); /* Clean up R & release resources */ #ifdef _WIN32 static void init_embedded_win32(int argc, char *argv[]); #endif /* Global objects */ static SEXP get_item; static SEXP set_item; static SEXP length; static SEXP aperm; static PyObject *class_table; static PyObject *proc_table; static int default_mode; static PyObject *r_lock; PyObject *RPy_Exception; PyObject *RPy_TypeConversionException; PyObject *RPy_RException; static char RHOME[BUFSIZ]; static char RVERSION[BUFSIZ]; static char RVER[BUFSIZ]; static char RUSER[BUFSIZ]; char *defaultargv[] = {"rpy", "-q", "--vanilla"}; int defaultargc = sizeof(defaultargv) / sizeof(defaultargv[0]); /* Global interpreter */ PyInterpreterState *my_interp; /* Signal whether R is running interactively */ int R_interact; /* RPy namespace */ PyObject *rpy; PyObject *rpy_dict; #ifdef WITH_NUMERIC static PyObject *Py_transpose; #endif /* Global list to protect R objects from garbage collection */ /* This is inspired in $R_SRC/src/main/memory.c */ static SEXP R_References; static SEXP RecursiveRelease(SEXP obj, SEXP list) { if (!isNull(list)) { if (obj == CAR(list)) return CDR(list); else SETCDR(list, RecursiveRelease(obj, CDR(list))); } return list; } /* Robj methods. Following xxmodule.c from Python distro. */ static void Robj_dealloc(RobjObject *self) { /* Remove the object from the list of protected objects */ R_References = RecursiveRelease(self->R_obj, R_References); SET_SYMVALUE(install("R.References"), R_References); PyObject_Del(self); } RobjObject * Robj_new(SEXP robj, int conversion) { RobjObject *self; self = PyObject_New(RobjObject, &Robj_Type); if (!self) return NULL; if (!robj) return NULL; /* Protect the R object */ R_References = CONS(robj, R_References); SET_SYMVALUE(install("R.References"), R_References); self->R_obj = robj; self->conversion = conversion; return self; } #ifndef PRE_2_2 static PyObject * Robj_tpnew(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *self; self = type->tp_alloc(type, 0); return self; } #endif /* Type conversion routines. See documentation for details */ /* These are auxiliaries for a state machine for converting Python list to the coarsest R vector type */ #define ANY_T 0 #define BOOL_T 1 #define INT_T 2 #define FLOAT_T 3 #define COMPLEX_T 4 #define STRING_T 5 #define ROBJ_T 6 static int type_to_int(PyObject *obj) { if (PyBool_Check(obj)) return BOOL_T; else if (PyInt_Check(obj)) return INT_T; else if (PyFloat_Check(obj)) return FLOAT_T; else if (PyComplex_Check(obj)) return COMPLEX_T; else if (PyNumber_Check(obj)) return ANY_T; else if (PyString_Check(obj)) return STRING_T; else if (PyUnicode_Check(obj)) return STRING_T; else if (Robj_Check(obj)) return ROBJ_T; else return ANY_T; } /* Make a R list or vector from a Python sequence */ static SEXP seq_to_R(PyObject *obj) { PyObject *it; SEXP robj, rit; int i, len, state; /* This matrix defines what mode a vector should take given what it already contains and a new item E.g. Row 0 indicates that if we've seen an any, the vector will always remain an any. Row 3 indicates that if we've seen a float, then seeing an boolean, integer, or float will preserve the vector as a float vector, while seeing a string or an Robj will convert it into an any vector. */ int fsm[7][7] = { {0, 0, 0, 0, 0, 0, 0}, // any {0, 1, 2, 3, 4, 0, 0}, // bool {0, 2, 2, 3, 4, 0, 0}, // int {0, 3, 3, 3, 4, 0, 0}, // float {0, 4, 4, 4, 4, 0, 0}, // complex {0, 0, 0, 0, 0, 5, 0}, // string {0, 0, 0, 0, 0, 0, 6} // RObj }; len = PySequence_Length(obj); if (len == 0) return R_NilValue; PROTECT(robj = NEW_LIST(len)); state = -1; for (i=0; idimensions; type = obj->descr->type_num; size = PyArray_Size( (PyObject*) obj); /* Handle a vector without dimensions, just length */ if(obj->nd==0) { PROTECT(Rdims = allocVector(INTSXP, 1)); PROTECT(tRdims = allocVector(INTSXP, 1)); INTEGER(Rdims)[0] = size; INTEGER(tRdims)[0] = size; } else { PROTECT(Rdims = allocVector(INTSXP, obj->nd)); PROTECT(tRdims = allocVector(INTSXP, obj->nd)); for (i=0; ind; i++) { if (dims[i] == 0) { UNPROTECT(2); return R_NilValue; } INTEGER(Rdims)[i] = dims[(obj->nd)-i-1]; INTEGER(tRdims)[i] = (obj->nd)-i; } } switch(type) { /*******************/ /* String Variants */ /*******************/ /* TODO: Add proper handling of NumPy character arrays. The following code DOES NOT WORK: #if WITH_NUMERIC==3 case PyArray_UNICODE: case PyArray_STRING: case PyArray_CHAR: obj = (PyArrayObject *)PyArray_ContiguousFromObject((PyObject *)obj, PyArray_STRING, 0, 0); #endif The problem is that the PyArray call throws an exception, presumably because we haven't given a width specifier. NumPy strings are fixed-width, and may not be null terminated. R only handles null terminated (varying width) strings. We need a separate code path to handle this, as it requires quite different handling than the numeric arrays dealt with below. */ /******************************************/ /* All complex to (double,double) complex */ /******************************************/ #if WITH_NUMERIC==1 /* Numeric */ case PyArray_CFLOAT: case PyArray_CDOUBLE: #else /* NumPy */ case PyArray_COMPLEX64: case PyArray_COMPLEX128: #endif obj = (PyArrayObject *)PyArray_ContiguousFromObject((PyObject *)obj, PyArray_CDOUBLE, 0, 0); break; /**********************************************************************************/ /* Convert all integers to platform integer (except 64 bit int on 32 bit platforms) */ /************************************************************************************/ #if WITH_NUMERIC==1 /* Numeric */ case PyArray_UBYTE: case PyArray_SBYTE: case PyArray_SHORT: case PyArray_INT: case PyArray_LONG: obj = (PyArrayObject *)PyArray_ContiguousFromObject((PyObject *)obj, PyArray_INT, 0, 0); break; #else /* NumPy */ case PyArray_BOOL: case PyArray_INT8: case PyArray_UINT8: case PyArray_INT16: case PyArray_UINT16: case PyArray_INT32: case PyArray_UINT32: #if PyArray_INT==PyArray_INT64 /* 64 bit platform */ case PyArray_INT64: case PyArray_UINT64: #else obj = (PyArrayObject *)PyArray_ContiguousFromObject((PyObject *)obj, PyArray_INT, 0, 0); break; #endif #endif /**************************************************/ /* All floats (and over-sized integers) to double */ /**************************************************/ #if WITH_NUMERIC==1 /* Numeric */ case PyArray_FLOAT: case PyArray_DOUBLE: #else /* NumPy */ case PyArray_FLOAT32: case PyArray_FLOAT64: #if PyArray_INT!=PyArray_INT64 /* 32 bit platform */ case PyArray_INT64: case PyArray_UINT64: #endif #endif obj = (PyArrayObject *)PyArray_ContiguousFromObject((PyObject *)obj, PyArray_DOUBLE, 0, 0); break; default: UNPROTECT(2); PyErr_Format(RPy_TypeConversionException, "Numeric/NumPy arrays containing %s are not supported.", obj->ob_type->tp_name); return R_NilValue; break; } pytl = Py_BuildValue("[i]", size); nobj = PyArray_Reshape(obj, pytl); Py_XDECREF(pytl); Py_XDECREF(obj); if (nobj == NULL) { UNPROTECT(2); return R_NilValue; } PROTECT(Rarray = seq_to_R(nobj)); if (Rarray == NULL) { UNPROTECT(3); return R_NilValue; } Py_XDECREF(nobj); SET_DIM(Rarray, Rdims); PROTECT(e = allocVector(LANGSXP, 3)); SETCAR(e, aperm); SETCAR(CDR(e), Rarray); SETCAR(CDR(CDR(e)), tRdims); PROTECT(Rarray = do_eval_expr(e)); UNPROTECT(5); return Rarray; } #endif /* Convert a Python object to a R object. An Robj is passed w/o * modifications, an object which provides a '.as_r()' method, is * passed as the result of that method */ SEXP to_Robj(PyObject *obj) { SEXP robj; Py_complex c; PyObject *to_r_meth; PyObject *tempObj; int do_decref = 0; if (obj==NULL) return NULL; if (obj == Py_None) { return R_NilValue; } to_r_meth = PyObject_GetAttrString(obj, "as_r"); if (to_r_meth) { obj = PyObject_CallObject(to_r_meth, NULL); Py_DECREF(to_r_meth); if (obj==NULL) return NULL; do_decref = 1; } PyErr_Clear(); if (Robj_Check(obj)) { PROTECT(robj = ((RobjObject *)obj)->R_obj); } else if (PyBool_Check(obj)) { PROTECT(robj = NEW_LOGICAL(1)); LOGICAL_DATA(robj)[0] = (Py_True==obj); } else if (PyInt_Check(obj)) { PROTECT(robj = NEW_INTEGER(1)); INTEGER_DATA(robj)[0] = (int) PyInt_AsLong(obj); } else if (PyFloat_Check(obj)) { PROTECT(robj = NEW_NUMERIC(1)); NUMERIC_DATA(robj)[0] = PyFloat_AsDouble(obj); } else if (PyComplex_Check(obj)) { PROTECT(robj = NEW_COMPLEX(1)); c = PyComplex_AsCComplex(obj); COMPLEX_DATA(robj)[0].r = c.real; COMPLEX_DATA(robj)[0].i = c.imag; } else if (PyUnicode_Check(obj)) { /** Handle Unicode Strings. * * Ideally: Python Unicode -> R Unicode, * * Unfortunately, the R documentation is not forthcoming on how * to accomplish this * * So, for the moment: * python Unicode -> Python ASCII -> ordinary string -> R string * */ PROTECT(robj = NEW_STRING(1)); SET_STRING_ELT(robj, 0, COPY_TO_USER_STRING(PyString_AsString(PyUnicode_AsASCIIString(obj)))); } else if (PyString_Check(obj)) { PROTECT(robj = NEW_STRING(1)); SET_STRING_ELT(robj, 0, COPY_TO_USER_STRING(PyString_AsString(obj))); } #ifdef WITH_NUMERIC else if (use_numeric && PyArray_Check(obj)) { PROTECT(robj = to_Rarray(obj)); } #endif else if ((PySequence_Check(obj)) && (PySequence_Size(obj) >= 0)) { PROTECT(robj = seq_to_R(obj)); /* No labels */ } else if ((PyMapping_Check(obj)) && (PyMapping_Size(obj) >= 0)) { PROTECT(robj = dict_to_R(obj)); } else if (PyNumber_Check(obj)) /* generic number interface */ { tempObj = PyNumber_Float(obj); if(!tempObj) goto error; PROTECT(robj = NEW_NUMERIC(1)); NUMERIC_DATA(robj)[0] = PyFloat_AsDouble(tempObj); Py_DECREF(tempObj); } else { error: PyErr_Format(RPy_TypeConversionException, "cannot convert from type '%s'", obj->ob_type->tp_name); PROTECT(robj = NULL); /* Protected to avoid stack inbalance */ } if (do_decref) { Py_DECREF(obj); } UNPROTECT(1); return robj; } /* Convert a R named vector or list to a Python dictionary */ static PyObject * to_PyDict(PyObject *obj, SEXP names) { int len, i; PyObject *it, *dict; const char *name; if ((len = PySequence_Length(obj)) < 0) return NULL; dict = PyDict_New(); for (i=0; i 1) && (res[l-1] == '_') && (res[l-2] != '_')) res[l-1]=0; while ((r=strchr(r, '_'))) *r = '.'; return res; } /* Convert a dict to keywords arguments for a R function */ int make_kwds(int lkwds, PyObject *kwds, SEXP *e) { SEXP r; const char *s; int i; PyObject *citems=NULL, *it; PyObject *kwname; if (kwds) { citems = PyMapping_Items(kwds); } for (i=0; iR_obj); e = CDR(e); if (!make_args(largs, args, &e)) { UNPROTECT(1); return NULL; } if (!make_kwds(lkwds, kwds, &e)) { UNPROTECT(1); return NULL; } PROTECT(res = do_eval_expr(exp)); if (!res) { UNPROTECT(2); return NULL; } if (default_mode < 0) conv = ((RobjObject *)self)->conversion; else conv = default_mode; obj = to_Pyobj_with_mode(res, conv); UNPROTECT(2); PrintWarnings(); /* show any warning messages */ return obj; } /* Convert a sequence of (name, value) pairs to arguments to an R function call */ int make_argl(int largl, PyObject *argl, SEXP *e) { SEXP rvalue; const char *name; int i; PyObject *it, *nobj, *value; if( !PySequence_Check(argl) ) goto fail_arg; for (i=0; i0) { SET_TAG(*e, Rf_install(name)); PyMem_Free((void*) name); } /* Move index to new end of call */ *e = CDR(*e); } return 1; fail_arg: PyErr_SetString(PyExc_ValueError, "Argument must be a sequence of (\"name\", value) pairs.\n"); fail: return 0; } /* Methods for the 'Robj' type */ /* Explicitly call an R object with a list containing (name, value) * * argument pairs. 'name' can be None or '' to provide unnamed * arguments. This function is necessary when the *order* of named * arguments needs to be preserved. */ static PyObject * Robj_lcall(PyObject *self, PyObject *args) { SEXP exp, e, res; int largs, largl, conv; PyObject *obj, *argl; /* Check arguments, there should be *exactly one* unnamed sequence. */ largs = 0; if (args) largs = PyObject_Length(args); if (largs<0) return NULL; if(largs != 1 || !PySequence_Check(args) ) { PyErr_SetString(PyExc_ValueError, "Argument must be a sequence of (\"name\", value) pairs.\n"); return NULL; } // extract our one argument argl = PySequence_GetItem(args, 0); Py_DECREF(args); largl = 0; if (argl) largl = PyObject_Length(argl); if (largl<0) return NULL; // A SEXP with the function to call and the arguments PROTECT(exp = allocVector(LANGSXP, largl+1)); e = exp; SETCAR(e, ((RobjObject *)self)->R_obj); e = CDR(e); // Add the arguments to the SEXP if (!make_argl(largl, argl, &e)) { UNPROTECT(1); return NULL; } // Evaluate PROTECT(res = do_eval_expr(exp)); if (!res) { UNPROTECT(2); return NULL; } // Convert if (default_mode < 0) conv = ((RobjObject *)self)->conversion; else conv = default_mode; obj = to_Pyobj_with_mode(res, conv); UNPROTECT(2); // Return return obj; } /* Without args return the value of the conversion flag. With an argument set the conversion flag to the truth value of the argument. */ static PyObject * Robj_autoconvert(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *obj; int conversion=-2; char *kwlist[] = {"val", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:autoconvert", kwlist, &conversion)) return NULL; if (conversion > TOP_MODE) { PyErr_SetString(PyExc_ValueError, "wrong mode"); return NULL; } if (conversion == -2) { obj = PyInt_FromLong((long)((RobjObject *)self)->conversion); } else { ((RobjObject *)self)->conversion = conversion; obj = Py_None; Py_XINCREF(obj); } return obj; } static PyObject * Robj_as_py(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *obj; char *kwlist[] = {"mode", 0}; int conv=default_mode; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:as_py", kwlist, &conv)) return NULL; if (conv <= -2 || conv > TOP_MODE) { PyErr_SetString(PyExc_ValueError, "wrong mode"); return NULL; } if (conv < 0) conv = TOP_MODE; obj = to_Pyobj_with_mode(((RobjObject *)self)->R_obj, conv); return obj; } static PyMethodDef Robj_methods[] = { {"autoconvert", (PyCFunction)Robj_autoconvert, METH_VARARGS|METH_KEYWORDS}, {"local_mode", (PyCFunction)Robj_autoconvert, METH_VARARGS|METH_KEYWORDS}, {"as_py", (PyCFunction)Robj_as_py, METH_VARARGS|METH_KEYWORDS}, {"lcall", (PyCFunction)Robj_lcall, METH_VARARGS}, {NULL, NULL} /* sentinel */ }; /* Sequence protocol implementation */ /* len(a) */ static int Robj_len(PyObject *a) { SEXP e, robj; PROTECT(e = allocVector(LANGSXP, 2)); SETCAR(e, length); SETCAR(CDR(e), ((RobjObject *)a)->R_obj); if (!(robj = do_eval_expr(e))) { UNPROTECT(1); return -1; } UNPROTECT(1); return INTEGER_DATA(robj)[0]; } /* a[i] = v */ static int Robj_ass_item(PyObject *a, int i, PyObject *v) { SEXP e, ri, robj; PROTECT(e = allocVector(LANGSXP, 4)); ri = NEW_INTEGER(1); INTEGER_DATA(ri)[0] = i+1; SETCAR(e, set_item); SETCAR(CDR(e), ((RobjObject *)a)->R_obj); SETCAR(CDR(CDR(e)), ri); SETCAR(CDR(CDR(CDR(e))), to_Robj(v)); if(PyErr_Occurred()) return -1; if (!(robj = do_eval_expr(e))) { UNPROTECT(1); return -1; } ((RobjObject *)a)->R_obj = robj; UNPROTECT(1); return 0; } /* a[i] */ static PyObject * Robj_item(PyObject *a, int i) { SEXP ri, robj, e; PyObject *obj; int len, c; if ((len = Robj_len(a)) < 0) return NULL; if (i >= len || i < 0) { PyErr_SetString(PyExc_IndexError, "R object index out of range"); return NULL; } PROTECT(ri = NEW_INTEGER(1)); INTEGER_DATA(ri)[0] = i+1; PROTECT(e = allocVector(LANGSXP, 3)); SETCAR(e, get_item); SETCAR(CDR(e), ((RobjObject *)a)->R_obj); SETCAR(CDR(CDR(e)), ri); if (!(robj = do_eval_expr(e))) { UNPROTECT(2); return NULL; } UNPROTECT(2); /* If there is a default mode, use it; otherwise, use the top mode. */ if (default_mode < 0) c = TOP_MODE; else c = default_mode; obj = to_Pyobj_with_mode(robj, c); return obj; } /* Get a slice: a[x:y] */ /*FIXME: starting with Python 2.5, ilow and ihigh should probably * be of type Py_ssize_t. */ static PyObject * Robj_slice(PyObject *a, int ilow, int ihigh) { SEXP robj, e, index; PyObject *obj; int robjLen, sliceLen, c; int ii; robjLen = Robj_len(a); if (robjLen < 0) return NULL; if (ilow < 0) { PyErr_SetString(PyExc_IndexError, "R object index out of range (lowest index is negative)"); return NULL; //ilow = 0; } else if (ilow > robjLen) { PyErr_SetString(PyExc_IndexError, "R object index out of range (lowest index > object length)"); return NULL; //ilow = robjLen; } if (ihigh < ilow) { PyErr_SetString(PyExc_IndexError, "R object index out of range (highest index < lowest index)"); return NULL; //ihigh = ilow; } else if (ihigh > robjLen) { PyErr_SetString(PyExc_IndexError, "R object index out of range (highest index > object length)"); //return NULL; ihigh = robjLen; } sliceLen = ihigh - ilow; /* if (ilow >= robjLen || ilow < 0) { */ /* PyErr_SetString(PyExc_IndexError, "R object index out of range"); */ /* return NULL; */ /* } */ PROTECT(index = allocVector(INTSXP, sliceLen)); for (ii = 0; ii < sliceLen; ii++) { INTEGER_POINTER(index)[ii] = ii + ilow + 1; } PROTECT(e = allocVector(LANGSXP, 3)); SETCAR(e, get_item); SETCAR(CDR(e), ((RobjObject *)a)->R_obj); SETCAR(CDR(CDR(e)), index); if (!(robj = do_eval_expr(e))) { UNPROTECT(2); return NULL; } UNPROTECT(2); /* If there is a default mode, use it; otherwise, use the top mode. */ if (default_mode < 0) c = TOP_MODE; else c = default_mode; obj = to_Pyobj_with_mode(robj, c); return obj; } /* FIXME: * Python 2.5 will feel happier with ssizeargfunc and ssizessizeargfunc */ /* We should implement sq_slice, sq_contains ... */ static PySequenceMethods Robj_as_sequence = { (inquiry)Robj_len, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (intargfunc)Robj_item, /* sq_item */ (intintargfunc)Robj_slice, /* sq_slice */ (intobjargproc)Robj_ass_item, /* sq_ass_item */ 0, /* sq_ass_slice */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0 /* sq_inplace_repeat */ }; /* The 'Robj' table. When compiled under Python 2.2, the type 'Robj' is subclassable. */ #ifdef PRE_2_2 static PyObject * Robj_getattr(RobjObject *self, char *name) { return Py_FindMethod(Robj_methods, (PyObject *)self, name); } #endif PyTypeObject Robj_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ #if defined(PRE_2_2) || defined(_WIN32) // Matjaz PyObject_HEAD_INIT(NULL) #else PyObject_HEAD_INIT(&PyType_Type) #endif 0, /*ob_size*/ "Robj", /*tp_name*/ sizeof(RobjObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)Robj_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ #ifdef PRE_2_2 (getattrfunc)Robj_getattr, #else 0, #endif 0, 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ &Robj_as_sequence, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ (ternaryfunc)Robj_call, /*tp_call*/ 0, /*tp_str*/ #if defined(PRE_2_2) || defined(_WIN32) 0, #else PyObject_GenericGetAttr, /*tp_getattro*/ #endif 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ #ifdef PRE_2_2 0, #else Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ #endif 0, /*tp_doc*/ 0, /*tp_traverse*/ #ifndef PRE_2_2 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Robj_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ #ifdef _WIN32 0, /*tp_alloc*/ #else PyType_GenericAlloc, /*tp_alloc*/ #endif Robj_tpnew, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ #endif }; /* Module functions */ /* Obtain an R object via its name. 'autoconvert' is the keyword to set the autoconversion flag. */ static PyObject * get_fun(PyObject *self, PyObject *args, PyObject *kwds) { char *obj_str; int conversion=TOP_MODE; SEXP robj; static char *kwlist[] = {"name", "autoconvert", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|i:get", kwlist, &obj_str, &conversion)) return NULL; robj = get_fun_from_name(obj_str); if (!robj) return NULL; return (PyObject *)Robj_new(robj, conversion); } static PyObject * set_mode(PyObject *self, PyObject *args) { int i=-1; if (!PyArg_ParseTuple(args, "i:set_mode", &i)) return NULL; if (i<-1 || i>TOP_MODE) { PyErr_SetString(PyExc_ValueError, "wrong mode"); return NULL; } default_mode = i; Py_INCREF(Py_None); return Py_None; } static PyObject * get_mode(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":get_mode")) return NULL; return PyInt_FromLong(default_mode); } static PyObject * r_events(PyObject *self, PyObject *args, PyObject *kwds) #ifdef _WIN32 { return NULL; } #else { fd_set *what; int usec=10000; static char *kwlist[] = {"usec", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:r_events", kwlist, &usec)) return NULL; if (R_interact) { Py_BEGIN_ALLOW_THREADS what = R_checkActivity(usec, 0); R_runHandlers(R_InputHandlers, what); Py_END_ALLOW_THREADS } Py_INCREF(Py_None); return Py_None; } #endif void stop_events(void) { PyObject *o; if (!rpy_dict) return; if (!r_lock) r_lock = PyDict_GetItemString(rpy_dict, "_r_lock"); o = PyObject_CallMethod(r_lock, "acquire", NULL); Py_XDECREF(o); } void start_events(void) { PyObject *o; if (!rpy_dict) return; if (!r_lock) r_lock = PyDict_GetItemString(rpy_dict, "_r_lock"); o = PyObject_CallMethod(r_lock, "release", NULL); Py_XDECREF(o); } /* * Based on code from Rstd_CleanUp(); * from src/unix/sys-std.c */ void r_finalize(void) { unsigned char buf[1024]; char * tmpdir; R_dot_Last(); R_RunExitFinalizers(); CleanEd(); #if (R_VERSION >= R_Version(2,7,0)) Rf_KillAllDevices(); #else KillAllDevices(); #endif #if (R_VERSION >= R_Version(2,4,0)) R_CleanTempDir(); #else if((tmpdir = getenv("R_SESSION_TMPDIR"))) { # ifdef _WIN32 snprintf((char *)buf, 1024, "rmdir /S /Q %s", tmpdir); # else snprintf((char *)buf, 1024, "rm -rf %s", tmpdir); # endif R_system((char *)buf); } #endif PrintWarnings(); /* from device close and .Last */ R_gc(); /* Remove any remaining R objects from memory */ } static PyObject * r_cleanup(void) { r_finalize(); Py_INCREF(Py_None); return Py_None; } #ifdef WITH_NUMERIC static void init_numeric(void) { PyObject *multiarray, *dict; if(use_numeric) { import_array(); multiarray = PyImport_ImportModule(PY_ARRAY_MODULE_NAME); if (multiarray) { dict = PyModule_GetDict(multiarray); if (dict) Py_transpose = PyDict_GetItemString(dict, "transpose"); } } } #endif static PyObject * r_init(PyObject *self, PyObject *args) { static int first=1; int i; if (!PyArg_ParseTuple(args, "i:r_init", &i)) return NULL; use_numeric = i; #ifdef WITH_NUMERIC if(use_numeric) init_numeric(); #endif if(first==1) { first=0; Py_INCREF(Py_None); return Py_None; } else { PyErr_SetString(PyExc_RuntimeError, "Only one R object may be instantiated per session"); return NULL; } } /* List of functions defined in the module */ static PyMethodDef rpy_methods[] = { {"get_fun", (PyCFunction)get_fun, METH_VARARGS | METH_KEYWORDS}, {"set_mode", (PyCFunction)set_mode, METH_VARARGS}, {"get_mode", (PyCFunction)get_mode, METH_VARARGS}, {"set_output", (PyCFunction)set_output, METH_VARARGS}, {"set_input", (PyCFunction)set_input, METH_VARARGS}, {"set_showfiles", (PyCFunction)set_showfiles, METH_VARARGS}, {"get_output", (PyCFunction)get_output, METH_VARARGS}, {"get_input", (PyCFunction)get_input, METH_VARARGS}, {"get_showfiles", (PyCFunction)get_showfiles, METH_VARARGS}, {"r_events", (PyCFunction)r_events, METH_VARARGS | METH_KEYWORDS}, {"r_cleanup", (PyCFunction)r_cleanup, METH_NOARGS}, {"r_init", (PyCFunction)r_init, METH_VARARGS}, {NULL, NULL} /* sentinel */ }; #ifdef _WIN32 static void char_message( char *s ) { if (!s) return; R_WriteConsole(s, strlen(s)); } static int char_yesnocancel( char *s ) { return 1; } static void RPyBusy( int which ) { /* set a busy cursor ... in which = 1, unset if which = 0 */ } static void RPyDoNothing( void ) { } /* initialise embedded R; based on rproxy_impl.c from the R distribution */ static void init_embedded_win32(int argc, char *argv[]) { structRstart rp; Rstart Rp = &rp; char Rversion[25]; int index; snprintf( Rversion, 25, "%s.%s", R_MAJOR, R_MINOR ); if( strcmp( getDLLVersion(), Rversion ) != 0 ) { PyErr_SetString( PyExc_ImportError, "R.DLL version does not match" ); return; } R_DefParams(Rp); /* set R_HOME */ Rp->rhome = RHOME; index = strlen(RUSER) - 1; if (RUSER[index] == '/' || RUSER[index] == '\\') RUSER[index] = '\0'; Rp->home = RUSER; Rp->CharacterMode = LinkDLL; Rp->ReadConsole = (blah1) RPy_ReadConsole; // Matjaz Rp->WriteConsole = (blah2) RPy_WriteConsole; // Matjaz Rp->CallBack = (blah3) RPyDoNothing; #if R_VERSION < 0x20100 Rp->message = char_message; Rp->yesnocancel = char_yesnocancel; Rp->busy = RPyBusy; #else Rp->ShowMessage = char_message; Rp->YesNoCancel = char_yesnocancel; Rp->Busy = RPyBusy; #endif Rp->R_Quiet = TRUE; /* run as "interactive", so server won't be killed after an error */ Rp->R_Slave = Rp->R_Verbose = 0; Rp->R_Interactive = TRUE; Rp->RestoreAction = SA_NORESTORE; /* no restore */ Rp->SaveAction = SA_NOSAVE; /* no save */ #if R_VERSION < 0x20000 // pre-R-2.0.0 Rp->CommandLineArgs = NULL; Rp->NumCommandLineArgs = 0; #else R_set_command_line_arguments(argc, argv); #endif R_SetParams(Rp); /* so R_ShowMessage is set */ R_SizeFromEnv(Rp); R_SetParams(Rp); setup_term_ui(); setup_Rmainloop(); } #endif /* Initialization function for the module */ DL_EXPORT(void) INIT_RPY(void) { PyObject *m, *d; PyOS_sighandler_t old_int; #ifndef _WIN32 PyOS_sighandler_t old_usr1, old_usr2; #endif SEXP interact; /* Get path and version information from environment */ strncpy(RHOME, getenv("RPY_RHOME"), BUFSIZ); strncpy(RVERSION, getenv("RPY_RVERSION"), BUFSIZ); strncpy(RVER, getenv("RPY_RVER"), BUFSIZ); strncpy(RUSER, getenv("RPY_RUSER"), BUFSIZ); if( !strlen(RHOME) || !strlen(RVERSION) || !strlen(RVER) || !strlen(RUSER)) { PyErr_Format(RPy_Exception, "Unable to load R path or version information"); return; } Robj_Type.ob_type = &PyType_Type; #if defined( _WIN32 ) && ! defined( PRE_2_2 ) Robj_Type.tp_getattro = PyObject_GenericGetAttr; Robj_Type.tp_alloc = PyType_GenericAlloc; #endif /* Initialize the module with its content */ if (PyType_Ready(&Robj_Type) < 0) return; m = Py_InitModule3(xstr(RPY_SHNAME), rpy_methods, "Python interface to the R Programming Language"); Py_INCREF(&Robj_Type); PyModule_AddObject(m, Robj_Type.tp_name, (PyObject *)&Robj_Type); d = PyModule_GetDict(m); /* Save this interpreter */ PyEval_InitThreads(); my_interp = PyThreadState_Get()->interp; /* Save the Python signal handlers. If R inserts its handlers, we cannot return to the Python interpreter. */ old_int = PyOS_getsig(SIGINT); python_sigint = old_int; #ifndef _WIN32 old_usr1 = PyOS_getsig(SIGUSR1); old_usr2 = PyOS_getsig(SIGUSR2); #endif #ifdef _WIN32 init_embedded_win32(defaultargc, defaultargv); #else Rf_initEmbeddedR(defaultargc, defaultargv); #endif #ifdef CSTACK_DEFNS /* Disable C stack checking, which is incompatible with use as a shared library. */ R_CStackLimit = (uintptr_t)-1; #endif /* Restore Python handlers */ PyOS_setsig(SIGINT, old_int); #ifndef _WIN32 PyOS_setsig(SIGUSR1, old_usr1); PyOS_setsig(SIGUSR2, old_usr2); #endif /* Several new exceptions: */ RPy_Exception = PyErr_NewException("rpy.RPy_Exception", NULL, NULL); RPy_TypeConversionException = PyErr_NewException("rpy.RPy_TypeConversionException", RPy_Exception, NULL); RPy_RException = PyErr_NewException("rpy.RPy_RException", RPy_Exception, NULL); if (!RPy_Exception || !RPy_TypeConversionException || !RPy_RException ) { PyErr_Format(RPy_Exception, "Unable create RPy exceptions"); return; } PyDict_SetItemString(d, "RPy_Exception", RPy_Exception); PyDict_SetItemString(d, "RPy_TypeConversionException", RPy_TypeConversionException); PyDict_SetItemString(d, "RPy_RException", RPy_RException); // The conversion table class_table = PyDict_New(); proc_table = PyDict_New(); PyDict_SetItemString(d, "__class_table__", class_table); PyDict_SetItemString(d, "__proc_table__", proc_table); // The globals R objects for the sequence protocol get_item = get_fun_from_name("["); set_item = get_fun_from_name("[<-"); length = get_fun_from_name("length"); // Function to transpose arrays aperm = get_fun_from_name("aperm"); // Initialize the list of protected objects R_References = R_NilValue; SET_SYMVALUE(install("R.References"), R_References); // Initialize the default mode default_mode = -1; // Check whether R is interactive or no interact = do_eval_fun("interactive"); R_interact = INTEGER(interact)[0]; // I/O routines init_io_routines(); rpy = PyImport_ImportModule("rpy"); rpy_dict = PyModule_GetDict(rpy); // r_lock = PyDict_GetItemString(rpy_dict, "_r_lock"); // PyObject_Print(r_lock, stderr, Py_PRINT_RAW); r_lock = NULL; if( Py_AtExit( r_finalize ) ) { fprintf(stderr, "Warning: Unable to set R finalizer."); fflush(stderr); } } rpy-1.0.3/src/setenv.c0000644000076700000240000000417410411116614013751 0ustar warnesstaff/* * $Id: setenv.c 299 2006-03-22 22:13:54Z warnes $ * For POSIX compliance. */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include #include #include #include "setenv.h" int setenv(const char *name, const char *value, int clobber) { char *cp; if (clobber == 0 && getenv(name) != 0) return (0); if ((cp = malloc(strlen(name) + strlen(value) + 2)) == 0) return (1); sprintf(cp, "%s=%s", name, value); return (putenv(cp)); } rpy-1.0.3/src/setenv.h0000644000076700000240000000361010411116614013750 0ustar warnesstaff/* * $Id: setenv.h 299 2006-03-22 22:13:54Z warnes $ * For POSIX compliance */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the RPy python module. * * The Initial Developer of the Original Code is Walter Moreira. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gregory R. Warnes (Maintainer) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef _SETENV_H #define _SETENV_H int setenv(const char *name,const char *value, int clobber); #endif rpy-1.0.3/tests/0000755000076700000240000000000011012207656012653 5ustar warnesstaffrpy-1.0.3/tests/README0000644000076700000240000000057310411116616013535 0ustar warnesstaffRegressions tests. These tests can be run one by one or all togheter. For separate runs do (for example): python test_modes.py To run all the tests (ecept test_cleanup.py, which should be run separately) do: python testall.py This last invocation has an optional parameter: --random run the tests in random order For example: python testall.py --random rpy-1.0.3/tests/test_array.py0000644000076700000240000000467110716241772015421 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * idx = r['[['] idx.autoconvert(BASIC_CONVERSION) def to_r(obj): r.list.autoconvert(NO_CONVERSION) idx.autoconvert(NO_CONVERSION) o = idx(r.list(obj),1) idx.autoconvert(BASIC_CONVERSION) return o def all_equal_3d(vec1, vec2): if len(vec1) != len(vec2): return False for i in range(len(vec1)): if len(vec1[i]) != len(vec2[i]): return False for j in range( len(vec1[i]) ): if len(vec1[i][j])!=len(vec2[i][j]): return False for k in range( len(vec1[i][j]) ): if vec1[i][j][k] != vec2[i][j][k]: return False return True class ArrayTestCase(unittest.TestCase): def setUp(self): self.py = [[[0,6,12,18],[2,8,14,20],[4,10,16,22]], [[1,7,13,19],[3,9,15,21],[5,11,17,23]]] set_default_mode(NO_DEFAULT) try: r.array.autoconvert(NO_CONVERSION) self.ra = r.array(range(24),dim=(2,3,4)) finally: r.array.autoconvert(BASIC_CONVERSION) def testConversionToPy(self): self.failUnless(all_equal_3d(self.py,self.ra.as_py()), 'wrong conversion to Python') def testConversionToR(self): py_c = to_r(self.py) self.failUnless(r.all_equal(self.ra, py_c), 'R array not equal') def testDimensions(self): self.failUnless(r.dim(self.ra) == [len(self.py), len(self.py[0]), len(self.py[0][0])], 'wrong dimensions') def testElements(self): msg = 'Numeric array not equal' self.failUnless(self.py[0][0][0] == idx(self.ra, 1,1,1), msg) self.failUnless(self.py[1][2][3] == idx(self.ra, 2,3,4), msg) self.failUnless(self.py[1][1][2] == idx(self.ra, 2,2,3), msg) self.failUnless(self.py[1][0][3] == idx(self.ra, 2,1,4), msg) def testPyOutOfBounds(self): self.failUnlessRaises(IndexError, lambda: self.py[5][5][5]) def testROutOfBounds(self): self.failUnlessRaises(RPyException, lambda: idx(self.ra, 5,5,5)) def testBigArray(self): a = r.array(range(100000), dim=(100,1000)) self.failUnless(a[10][10] and a[80][900]) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_boolean.py0000644000076700000240000000102710716155505015710 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * import sys class BooleanTestCase(unittest.TestCase): def setup(self): set_default_mode(NO_DEFAULT) def testTRUE(self): self.failUnless(r.typeof(r.TRUE) == 'logical' and r.as_logical(r.TRUE)) def testFALSE(self): self.failUnless(r.typeof(r.FALSE) == 'logical' and not r.as_logical(r.FALSE)) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_cleanup.py0000644000076700000240000000077310777442514015735 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") import os, os.path class CleanupTestCase(unittest.TestCase): def setUp(self): pass def testCleanup(self): # run rpy in a separate process os.system("python testscript_cleanup.py") # make sure the temp dir has been removed tempdir = open('tempdir').read() self.failUnless(os.path.exists(tempdir)==False) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_init.py0000644000076700000240000000107010716155505015232 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") import os.path, time import rpy class InitTestCase(unittest.TestCase): def testInitFails(self): """ R does not support multiple R interpraters. Further, rpy doesn't support restarting a deleted interpreter. So, we need to check that an exception is raised if someone tries to do either. """ self.failUnlessRaises(RuntimeError, lambda: rpy.R() ) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_io.py0000644000076700000240000000354510716735364014716 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * class DummyOut: def write(self, *args, **kwds): pass class IOTestCase(unittest.TestCase): def setUp(self): sys.stdout = sys.stderr = DummyOut() def tearDown(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ # reset i/o defaults set_rpy_output(rpy_io.rpy_output) set_rpy_input(rpy_io.rpy_input) def testIOstdin(self): def dummy(prompt, n): return prompt+'\n' set_rpy_input(dummy) self.failUnless(r.readline('foo') == 'foo') def testIOstdout(self): out = [] def dummy(s): out.append(s) set_rpy_output(dummy) r.print_(5) self.failUnless(out == ['[1]', ' 5', '\n']) def testIOshowfiles(self): if sys.platform != 'win32': out = [] def dummy(files, headers, title, delete): out.append('foo') print "Names curently defined" dir() set_rpy_showfiles(dummy) r.help() self.failUnless(out == ['foo']) def testIOstdoutException(self): def stdout(s): raise Exception set_rpy_output(stdout) self.assert_(r.print_(5)) def testIOstdinException(self): def stdin(prompt, n): raise Exception set_rpy_input(stdin) self.assert_(r.readline() == '') def testIOshowfilesException(self): if sys.platform != 'win32': def showfiles(files, headers, title, delete): raise Exception set_rpy_showfiles(showfiles) self.assert_(r.help() == None) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_lapack_load.py0000644000076700000240000000110610716155505016521 0ustar warnesstafffrom __future__ import nested_scopes import unittest import os,sys sys.path.insert(1, "..") import os, os.path class LapackLoadTestCase(unittest.TestCase): def setUp(self): pass def testLapackLoad(self): from rpy import r fi = 'logit.r' #--load the functions r.source(fi) #--test a example x =50000 n = [x, x-500,x+460,x-400,x-100,x-4] y = [12, 24, 23, 2,4,5] f = [2,2,2,1,1,1] jk = r.logit_1fact(n,y,f) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_modes.py0000644000076700000240000001464110716743024015405 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * # only needed when debugging #import gc #gc.set_debug(gc.DEBUG_LEAK) class ModeConversionTestCase(unittest.TestCase): def setUp(self): set_default_mode(NO_DEFAULT) def testAs_pyArgs(self): self.failUnlessRaises(ValueError, lambda: r.seq.as_py(TOP_CONVERSION+1)) self.failUnlessRaises(ValueError, lambda: r.seq.as_py(-2)) self.failUnlessRaises(TypeError, lambda: r.seq.as_py('foo')) def testAs_py(self): try: r.c.autoconvert(NO_CONVERSION) a = r.c(4) assert(a.as_py() == 4) assert(a.as_py(PROC_CONVERSION) == 4) assert(a.as_py(BASIC_CONVERSION) == 4) assert(a.as_py(VECTOR_CONVERSION) == [4]) assert(r['=='](a.as_py(NO_CONVERSION), a)) finally: r.c.autoconvert(PROC_CONVERSION) def testAs_pyDefaultArg(self): set_default_mode(NO_CONVERSION) a = r.seq(1,3) b = r.t_test([1,2,3]) assert(type(a.as_py()) == type(a)) set_default_mode(BASIC_CONVERSION) assert(a.as_py() == [1,2,3]) set_default_mode(VECTOR_CONVERSION) assert(a.as_py() == [1,2,3]) class_table['htest'] = lambda o: 5 set_default_mode(PROC_CONVERSION) assert(b.as_py() == 5) set_default_mode(NO_DEFAULT) def testDefaultModes(self): set_default_mode(PROC_CONVERSION) assert(get_default_mode() == PROC_CONVERSION) set_default_mode(CLASS_CONVERSION) assert(get_default_mode() == CLASS_CONVERSION) set_default_mode(BASIC_CONVERSION) assert(get_default_mode() == BASIC_CONVERSION) set_default_mode(VECTOR_CONVERSION) assert(get_default_mode() == VECTOR_CONVERSION) set_default_mode(NO_CONVERSION) assert(get_default_mode() == NO_CONVERSION) set_default_mode(NO_DEFAULT) assert(get_default_mode() == NO_DEFAULT) def testBadModes(self): self.failUnlessRaises(ValueError, lambda: set_default_mode(-2)) self.failUnlessRaises(ValueError, lambda: set_default_mode(TOP_CONVERSION+1)) def testNoDefaultMode(self): set_default_mode(NO_DEFAULT) r.t_test.autoconvert(CLASS_CONVERSION) r.array.autoconvert(NO_CONVERSION) r.seq.autoconvert(BASIC_CONVERSION) assert(type(r.array(1,3)) == type(r.array)) assert(r.seq(1,3) == [1,2,3]) class_table['htest'] = lambda o: 5 assert(r.t_test([1,2,3]) == 5) def testIndividualConversions(self): r.c.autoconvert(BASIC_CONVERSION) r.seq.autoconvert(PROC_CONVERSION) r.min.autoconvert(VECTOR_CONVERSION) set_default_mode(NO_CONVERSION) assert(type(r.c(4)) == type(r.c)) assert(type(r.seq(1,3)) == type(r.seq)) assert(type(r.min(1,3)) == type(r.min)) set_default_mode(NO_DEFAULT) assert(r.c.autoconvert() == BASIC_CONVERSION) assert(r.seq.autoconvert() == PROC_CONVERSION) assert(r.min.autoconvert() == VECTOR_CONVERSION) assert(r.c(4) == 4) assert(r.seq(1,3) == [1,2,3]) assert(r.min(1,3) == [1]) set_default_mode(BASIC_CONVERSION) assert(r.c.autoconvert() == BASIC_CONVERSION) assert(r.seq.autoconvert() == PROC_CONVERSION) assert(r.min.autoconvert() == VECTOR_CONVERSION) assert(r.c(4) == 4) assert(r.seq(1,3) == [1,2,3]) assert(r.min(1,3) == 1) set_default_mode(VECTOR_CONVERSION) assert(r.c.autoconvert() == BASIC_CONVERSION) assert(r.seq.autoconvert() == PROC_CONVERSION) assert(r.min.autoconvert() == VECTOR_CONVERSION) assert(r.c(4) == [4]) assert(r.seq(1,3) == [1,2,3]) assert(r.min(1,3) == [1]) def testVectorConversion(self): set_default_mode(VECTOR_CONVERSION) assert( r.c(True) == [True] ) assert( r.c(4) == [4] ) assert( r.c('A') == ['A'] ) assert( r.c(1,'A',2) == ['1','A','2'] ) assert( r.c(a=1, b='A', c=2) == {'a':'1', 'b':'A', 'c':'2'} ) assert( r.list(a=1, b='A', c=2) == {'a': [1], 'c': [2], 'b': ['A']} ) assert( type(r('x ~ y')) == type(r.c) ) def testBasicConversion(self): set_default_mode(BASIC_CONVERSION) assert( r.c(True) == True ) assert( r.c(4) == 4 ) assert( r.c('A') == 'A' ) assert( r.c(1,'A',2) == ['1','A','2'] ) assert( r.c(a=1, b='A', c=2) == {'a':'1', 'b':'A', 'c':'2'} ) assert( r.list(a=1, b='A', c=2) == {'a': 1, 'c': 2, 'b': 'A'} ) assert( type(r('x ~ y')) == type(r.c) ) def testClassTable(self): def f(o): if len(r['[['](o, 1)) > 2: return 5 else: return 'bar' class_table.clear() class_table['htest'] = lambda o: 'htest' class_table['data.frame'] = f set_default_mode(CLASS_CONVERSION) assert(r.t_test([1,2,3]) == 'htest') assert(r.as_data_frame([1,2,3]) == 5) assert(r.as_data_frame([1,2]) == 'bar') set_default_mode(NO_DEFAULT) def testMultipleClassTable(self): set_default_mode(NO_CONVERSION) f = r.class__(r.c(4), 'foo') g = r.class__(r.c(4), ('bar', 'foo')) class_table['foo'] = lambda o: 'foo' class_table['bar'] = lambda o: 'bar' class_table[('bar', 'foo')] = lambda o: 5 set_default_mode(CLASS_CONVERSION) assert(f.as_py() == 'foo') assert(g.as_py() == 5) del class_table[('bar','foo')] assert(g.as_py() == 'bar') del class_table['bar'] assert(g.as_py() == 'foo') set_default_mode(NO_DEFAULT) class_table.clear() proc_table.clear() def testProcTable(self): def f(o): return r['$'](o, 'alternative') def t(o): e = r.attr(o, 'names') if e =='alternative' or \ (type(e)==type([]) and 'alternative' in e): return 1 return 0 proc_table.clear() class_table.clear() proc_table[t] = f set_default_mode(NO_DEFAULT) r.t_test.autoconvert(PROC_CONVERSION) assert(r.t_test([1,2,3]) == 'two.sided') proc_table.clear() class_table.clear() def main(): unittest.main(__name__) if __name__ == '__main__': main() rpy-1.0.3/tests/test_noninteractive.py0000644000076700000240000000105310716155505017320 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") import os.path, time from rpy_tools import getstatusoutput class NonInteractiveTestCase(unittest.TestCase): def testNonInteractiveErrors(self): """ Ensure that when rpy is used non-interactively, errors don't cause abort. """ flag, message = getstatusoutput("echo 'import rpy; rpy.r(\"foobar()\")' | python") assert( message.find('Execution halted') == -1 ) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_numeric.py0000644000076700000240000001761310716740406015743 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys try: from numpy import * ArrayLib='NumPy' except ImportError: try: from Numeric import * ArrayLib='Numeric' except ImportError: print '\nNumeric not available. Skipping.\n' sys.exit(0) import sys sys.path.insert(1, "..") from rpy import * idx = r['[['] idx.autoconvert(NO_CONVERSION) def to_r(obj): # For some reason, these two lines stop working after a few # iterations of `testall.py --loop'. I'm not sure why # r.list.autoconvert(NO_CONVERSION) # return idx(r.list(obj),1) # These three lines accomplish the same thing, but more # doesn't stop working after a few iterations. f = r("function(x) x") f.autoconvert(NO_CONVERSION) return f(obj) class ArrayTestCase(unittest.TestCase): def setUp(self): set_default_mode(NO_DEFAULT) py = array(range(24)) self.py = reshape(py, (2,3,4)) py_to_r = to_r(self.py) self.py_c = py_to_r.as_py() r.array.autoconvert(NO_CONVERSION) self.ra = r.array(range(24), dim=(2,3,4)) ra_to_py = self.ra.as_py() self.ra_c = to_r(ra_to_py) r.array.autoconvert(PROC_CONVERSION) def testZeroDimToR(self): set_default_mode(NO_CONVERSION) a = zeros((0,7)) ra = r.c(a) set_default_mode(NO_DEFAULT) self.failUnless(r.is_null(ra)) def testZeroDimToPy(self): self.failUnless(r.array(0,dim=(0,7)) == None) def testToPyDimensions(self): self.failUnless(self.py_c.shape == self.py.shape, 'wrong dimensions in Numeric array') def testToRDimensions(self): self.failUnless(r.dim(self.ra) == r.dim(self.ra_c), 'wrong dimensions in R array') def testPyElements(self): self.failUnless(self.py[0,0,0] == self.py_c[0,0,0] and self.py[1,2,3] == self.py_c[1,2,3] and self.py[1,1,2] == self.py_c[1,1,2] and self.py[1,0,3] == self.py_c[1,0,3], 'Numeric array not equal') def testRElements(self): try: idx.autoconvert(BASIC_CONVERSION) self.failUnless(idx(self.ra, 1,1,1) == idx(self.ra_c, 1,1,1) and idx(self.ra, 2,3,4) == idx(self.ra_c, 2,3,4) and idx(self.ra, 2,2,3) == idx(self.ra_c, 2,2,3) and idx(self.ra, 2,1,4) == idx(self.ra_c, 2,1,4), 'R array not equal') finally: idx.autoconvert(NO_CONVERSION) def testPyOutOfBounds(self): self.failUnlessRaises(IndexError, lambda: self.py_c[5,5,5]) def testROutOfBounds(self): self.failUnlessRaises(RPyException, lambda: idx(self.ra_c, 5,5,5)) def test64BitIntArray(self): # 64 bit ints try: if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int64' ) else: a = array( [1,2,3], Int64 ) except: print "\nInt64 not found (32 bit platform?), skipping this test.\n" return b = r.c(a) def test32BitIntArray(self): # 32 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int32' ) else: a = array( [1,2,3], Int32 ) b = r.c(a) def test16BitIntArray(self): # 16 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int16' ) else: a = array( [1,2,3], Int16 ) b = r.c(a) def test8BitIntArray(self): # 8 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int8' ) else: a = array( [1,2,3], Int8 ) b = r.c(a) def testBoolArray(self): # 8 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Bool' ) else: print "\nBool arrays not supported by Numeric, skipping this test.\n" return b = r.c(a) def test64BitFloatArray(self): if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Float64' ) else: a = array( [1,2,3], Float64 ) b = r.c(a) def test32BitFloatArray(self): # 32 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Float32' ) else: a = array( [1,2,3], Float32 ) b = r.c(a) def testCharArray(self): if(ArrayLib=='NumPy'): a = array( ['A', 'B', 'C'], character ) else: a = array( ['A', 'B', 'C'], Character ) self.failUnlessRaises(RPyTypeConversionException, lambda: r.c(a) ) def testStringArray(self): if(ArrayLib=='NumPy'): a = array( ['ABCDEFHIJKLM', 'B', 'C C C'], 'S10' ) else: # not available on Numeric print "\nString arrays not supported by Numeric, skipping this test.\n" return self.failUnlessRaises(RPyTypeConversionException, lambda: r.c(a) ) def testObjArray(self): if(ArrayLib=='NumPy'): a = array( ['A','B', 'C'], 'object' ) else: a = array( ['A','B', 'C'], PyObject ) self.failUnlessRaises(RPyTypeConversionException, lambda: r.c(a) ) def test64BitIntScalar(self): # 64 bit ints try: if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int64' ) else: a = array( [1,2,3], Int64 ) except: print "\nInt64 not found (32 bit platform?), skipping this test.\n" return b = r.c(a[0]) def test32BitIntScalar(self): # 32 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int32' ) else: a = array( [1,2,3], Int32 ) b = r.c(a[0]) def test16BitIntScalar(self): # 16 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int16' ) else: a = array( [1,2,3], Int16 ) b = r.c(a[0]) def test8BitIntScalar(self): # 8 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Int8' ) else: a = array( [1,2,3], Int8 ) b = r.c(a[0]) def testBoolScalar(self): # 8 bit ints if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Bool' ) else: print "\nBool arrays not supported by Numeric, skipping this test.\n" return b = r.c(a[0]) def test64BitFloatScalar(self): if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Float64' ) else: a = array( [1,2,3], Float64 ) b = r.c(a[0]) def test32BitFloatScalar(self): if(ArrayLib=='NumPy'): a = array( [1,2,3], 'Float32' ) else: a = array( [1,2,3], Float32 ) b = r.c(a[0]) def testCharScalar(self): if(ArrayLib=='NumPy'): a = array( ['A', 'B', 'C'], character ) self.failUnless( r.c(a[0])=='A' ) else: # RPy does not handle translation oc Numeric.Character objects a = array( ['A', 'B', 'C'], Character ) self.failUnlessRaises( RPyTypeConversionException, lambda:r.c(a[0])=='A' ) def testStringScalar(self): if(ArrayLib=='NumPy'): a = array( ['ABCDEFHIJKLM', 'B', 'C C C'], 'S10' ) self.failUnless( r.c(a[0])=='ABCDEFHIJK' ) else: # String class not available on Numeric print "\nString arrays not supported by Numeric, skipping this test.\n" return def testObjScalar(self): if(ArrayLib=='NumPy'): a = array( ['A', 'B', 'C'], 'object' ) else: a = array( ['A', 'B', 'C'], PyObject ) self.failUnless( r.c(a[0])=='A' ) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_robj.py0000644000076700000240000001016110775772010015225 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * class RobjTestCase(unittest.TestCase): def setUp(self): self.robj = type(r.array) set_default_mode(NO_DEFAULT) class_table.clear() proc_table.clear() def testType(self): self.failUnless(type(r.array) == type(r.seq)) def testCall(self): self.failUnless(callable(r.seq)) def testGetItem(self): r.seq.autoconvert(NO_CONVERSION) step = 10 pySeq = range(10, 50+step, step) d = r.seq(10, 50, by = step) for i in range(len(pySeq)): self.failUnless(pySeq[i] == d[i]) self.failUnless(pySeq[-1] == d[-1]) def testGetItemSlice(self): r.seq.autoconvert(NO_CONVERSION) step = 10 pySeq = range(10, 50+step, step) d = r.seq(10, 50, by=step) self.failUnless(pySeq[0:4] == d[0:4]) self.failUnless(pySeq[:4] == d[:4]) self.failUnless(pySeq[1:] == d[1:]) self.failUnless(pySeq[2:5] == d[2:5]) # FIXME: # The one below deserves attention: a one-element slice # should return a one-element sequence. # However, the conversion system in RPy is making it # somewhat problematic (or is it me ?)-- Laurent # self.failUnless(pySeq[0:1] == d[0:1]) self.failUnlessRaises(IndexError, d.__getslice__, -1, 2) self.failUnlessRaises(IndexError, d.__getslice__, 5, 2) def testKeywordParameters(self): r.list.autoconvert(BASIC_CONVERSION) d = r.list(foo='foo', bar_foo='bar.foo', print_='print', as_data_frame='as.data.frame') for k in d.keys(): #print k, d[k] self.failUnless(k == d[k]) def testBadKeywordParameters(self): def badkwname(): # Normally, the python C API catches this, but rpymodule does it's # own keyword arg processing, and inadequate error checking meant # rpy was dereferencing a null pointer. r.list(**{None: 1}) self.failUnlessRaises(TypeError, badkwname) def testBadKeywordDict(self): # This happens if the user accidently passes an object that is # superficially like a dictionary, but the object returned by it's # items() method raises an exception when fetching items. A missed # error check meant rpymodule was dereferencing a null pointer. class A(dict): def items(self): return B() class B(list): def __getitem__(self, n): raise TypeError def badkwdict(): r.list(**A(x=1)) self.failUnlessRaises(TypeError, badkwdict) def testNameConversions(self): self.failUnless(r.array is r['array'] and r.print_ is r['print'] and r.as_data_frame is r['as.data.frame'] and r.attr__ is r['attr<-']) def testNotFound(self): self.failUnlessRaises(RPyException, lambda: r.foo) def testNameLengthOne(self): self.failUnless(r.T) def testAutoconvert(self): r.seq.autoconvert(1) self.failUnless(r.seq(10) == range(1,11)) r.seq.autoconvert(NO_CONVERSION) self.failUnless(type(r.seq(10)) == type(r.seq)) r.seq.autoconvert(BASIC_CONVERSION) def testBadAutoconvert(self): self.failUnlessRaises(ValueError, lambda : r.seq.autoconvert(TOP_CONVERSION+1)) def testGetAutoconvert(self): a = r.seq.autoconvert() self.failUnless(type(a) is type(1) and -1<=a<=2) def testRgc(self): r.seq.autoconvert(NO_CONVERSION) a = r.seq(100000) r.gc() assert(a[10]) r.seq.autoconvert(BASIC_CONVERSION) def testLCall(self): "Test if lcall preserves named argument ordering." set_default_mode(NO_CONVERSION) a = r.c.lcall( (('',0),('a',1),('b',2),('c',3)) ) set_default_mode(BASIC_CONVERSION) self.failUnless(r.names(a) == ['','a','b','c']) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_sigint.py0000644000076700000240000000116410740446242015566 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * import sys import os import signal import time def sendsig(): "Send myself a keyboard interrupt" if sys.platform=="win32": #FIXME: ugy hack so that win32 passes raise KeyboardInterrupt else: os.kill(os.getpid(), signal.SIGINT) time.sleep(1) class SigintTestCase(unittest.TestCase): def testSigint(self): "test handling of keyboard interrupt signals" self.failUnlessRaises(KeyboardInterrupt, sendsig) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_topy.py0000644000076700000240000001105510716155505015266 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * # For testing the array conversion, try 'test-numeric.py' and # 'test-array.py' depending on whether you have Numeric or not. class TypeConversionToPyTestCase(unittest.TestCase): def setUp(self): set_default_mode(NO_DEFAULT) r.seq.autoconvert(BASIC_CONVERSION) r.c.autoconvert(BASIC_CONVERSION) def testNullToNone(self): assert(r.attributes(r.seq) is None) def testFactorToList(self): assert(r.factor([1,2,3,4]) == ['1','2','3','4']) assert(r.factor([1,1,1,2]) == ['1','1','1','2']) assert(r.factor(['a','b','c']) == ['a','b','c']) def testNAint(self): assert(r.NA == -2147483648) assert(r.is_na(r.NA)) assert( r(-2147483648) == r.NA ) def testNAreal(self): assert(repr(r.NAN) == repr(r("as.numeric(NA)")) ) def testNAstring(self): assert(r("as.character(NA)") == 'NA') assert(r.as_character(r.NA) == 'NA') assert(r.as_character(r.NAN) == 'NA') def testFactorNA(self): assert(r.factor(r.NA)=='NA') # int assert(r.factor(r.NAN)=='NA') # double assert(r.factor(r("as.character(NA)"))=='NA') # string xi = [1,2,r.NA,r.NAN,4] assert(r.factor(xi) == ['1','2','NA','NA','4']) xd = [1.01,2.02,r.NA,r.NAN,4.04] assert(r.factor(xd) == ['1.01','2.02','NA','NA','4.04']) def testNAList(self): xi = [1,2,r.NA,r.NAN,4] assert(r.as_character(xi) == ['1', '2', 'NA', 'NA', '4']) assert(repr(r.as_numeric(xi)) == repr([1.0, 2.0, r.NAN, r.NAN, 4.0])) assert(repr(r.as_integer(xi)) == repr([1, 2, r.NA, r.NA, 4])) assert(r.as_factor(xi) == ['1', '2', 'NA', 'NA', '4']) assert(r.is_na(xi) == [False, False, True, True, False] ) xd = [1.01,2.02,r.NA,r.NAN,4.04] assert(r.as_character(xd) == ['1.01', '2.02', 'NA', 'NA', '4.04']) assert(repr(r.as_numeric(xd)) == repr([1.01, 2.02, r.NAN, r.NAN, 4.04])) assert(r.as_integer(xd) == [1, 2, r.NA, r.NA, 4]) assert(r.as_factor(xd) == ['1.01', '2.02', 'NA', 'NA', '4.04']) assert(r.is_na(xd) == [False, False, True, True, False] ) def testDataFrameToList(self): r.read_table.autoconvert(BASIC_CONVERSION) assert(r.read_table('table.txt', header=1) == {'A': ['X1', 'X2', 'X3'], 'C': [5, 8, 2], 'B': [4.0, 7.0, 6.0], 'D': ['6', '9', 'Foo']}) def testLogicalToBoolean(self): assert( r('TRUE') == True) assert( r('T') == True ) assert( type(r('TRUE')) == type(True)) assert( type(r('T')) == type(True)) assert( r('FALSE') == False) assert( r('F') == False ) assert( type(r('FALSE')) == type(False)) assert( type(r('F')) == type(False)) def testIntToInt(self): assert(r.as_integer(5) == 5 and r.as_integer(-3) == -3) def testFloatToFloat(self): assert(r.as_real(5) == 5.0 and r.as_real(3.1) == 3.1) def testCplxToCplx(self): assert(r.as_complex(1+2j) == 1+2j and r.as_complex(1.5-3.4j) == 1.5-3.4j) def testStrToStr(self): r.as_data_frame.autoconvert(NO_CONVERSION) assert(r.class_(r.as_data_frame([1,2,3])) == 'data.frame') r.as_data_frame.autoconvert(BASIC_CONVERSION) def testVectorLengthOne(self): assert(r.c(1) == 1) assert(r.c('foo') == 'foo') def testIntVectorToList(self): assert(r.seq(10) == [1,2,3,4,5,6,7,8,9,10]) def testFloatVectorToList(self): assert(r.seq(1,2,by=0.5) == [1.0, 1.5, 2.0]) def testCplxVectorToList(self): assert(r.c(1+2j, 2-3j) == [1+2j, 2-3j]) def testStrVectorToList(self): assert(r.c('Foo', 'Bar') == ['Foo', 'Bar']) def testListToList(self): r.list.autoconvert(BASIC_CONVERSION) assert(r.list(1,2.0,'foo') == [1, 2.0, 'foo']) def testNamedVectorToDict(self): r.c.autoconvert(NO_CONVERSION) a = r.attr__(r.c(1,2,3), 'names', ['foo', 'bar', 'baz']) r.c.autoconvert(BASIC_CONVERSION) assert(a == {'foo':1, 'bar':2, 'baz':3}) def testVectorCoercion(self): r.c.autoconvert(NO_CONVERSION) assert(r.typeof(r.c(1,2,3)) == 'integer') assert(r.typeof(r.c(1,2.0,3)) == 'double') assert(r.typeof(r.c(1,2+3j,3)) == 'complex') assert(r.typeof(r.c(2,'bar',3.5)) == 'character') r.c.autoconvert(BASIC_CONVERSION) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_tor.py0000644000076700000240000000631710716735617015114 0ustar warnesstafffrom __future__ import nested_scopes import sys import unittest import sys sys.path.insert(1, "..") from rpy import * def with_c(f): try: r.c.autoconvert(NO_CONVERSION) f() finally: r.c.autoconvert(BASIC_CONVERSION) class foo: def __init__(self, x): self.x = x def as_r(self): return self.x class TypeConversionToRTestCase(unittest.TestCase): def setup(self): set_default_mode(NO_DEFAULT) def testRobjToR(self): def f(): r1 = r.c(4) r2 = r.c('foo') r3 = r.c(['a', 'b']) self.failUnless(r['=='](r1, 4)) self.failUnless(r['=='](r2, 'foo')) self.failUnless(r['=='](r3, ['a','b'])) # The following test for bug ID 1277392 self.failUnless(r.typeof(r.eval) == 'closure') self.failUnless(r.typeof(r.eval(r.eval)) == 'closure') self.failUnless(r.typeof(r.eval([r.eval, r.eval])) == 'list') with_c(f) def testEmptyListToNull(self): self.failUnless(r.is_null([])) def testBooleanToRLogical(self): assert( r.c(True) == True) assert( type(r.c(True)) == type(True)) assert( r.c(False) == False) assert( type(r.c(False)) == type(False)) def testIntToRInt(self): def f(): r1 = r.c(4) self.failUnless(r.typeof(r1) == 'integer') with_c(f) def testFloatToRFloat(self): with_c(lambda: self.failUnless(r.typeof(r.c(4.5)) == 'double')) def testCharToRChar(self): with_c(lambda: self.failUnless(r.typeof(r.c('foo')) == 'character')) def testDictToRNamedVector(self): def f(): robj = r.c({'foo':5, 'bar':7}) self.failUnless(r.typeof(robj) == 'integer') self.failUnless('foo' in r.attributes(robj)['names'] and 'bar' in r.attributes(robj)['names']) with_c(f) def testListToRVector(self): def f(): robj = r.c(1,2,3,4) self.failUnless(r.length(robj) == 4) with_c(f) def testNotConvertible(self): self.failUnlessRaises(RPyTypeConversionException, lambda: r.c(range)) def testInstancesNotConvertible(self): class Foo: pass a = Foo() self.failUnlessRaises(RPyTypeConversionException, lambda: r.c(a)) def testAs_rMethod(self): r.c.autoconvert(BASIC_CONVERSION) a = foo(3) b = foo('foo') d = foo(r.seq) self.failUnless(r.c(a) == 3) self.failUnless(r.c(b) == 'foo') self.failUnless(r.c(d)(1,3) == [1,2,3]) def testNAFromR(self): ''' R defines NA value (currently from limits.h MAX_INT) For 64 bit systems this will not be the same as sys.maxint ''' with_mode(BASIC_CONVERSION, lambda: self.failUnless(r.is_na(r.NA)))() def testInfToR(self): with_mode(BASIC_CONVERSION, lambda: self.failUnless(r.is_infinite(r.log(0))))() def testNaNToR(self): with_mode(BASIC_CONVERSION, lambda: self.failUnless(r.is_nan(r.log(-1))))() if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_util.py0000644000076700000240000000251410716155505015250 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") from rpy import * class UtilityTestCase(unittest.TestCase): def testAsList(self): self.failUnless(as_list(5) == [5]) self.failUnless(as_list(['a', 6]) == ['a', 6]) self.failUnless(as_list([5]) == [5]) self.failUnless(as_list((5)) == [(5)]) def testWithMode(self): with_mode(NO_CONVERSION, lambda: self.failUnless(get_default_mode() == NO_CONVERSION))() with_mode(BASIC_CONVERSION, lambda: self.failUnless(get_default_mode() == BASIC_CONVERSION))() with_mode(CLASS_CONVERSION, lambda: self.failUnless(get_default_mode() == CLASS_CONVERSION))() with_mode(PROC_CONVERSION, lambda: self.failUnless(get_default_mode() == PROC_CONVERSION))() self.failUnlessRaises(ValueError, lambda: with_mode(TOP_CONVERSION+1, lambda: 4)()) self.failUnlessRaises(ValueError, lambda: with_mode(-2, lambda: 4)()) def testRCode(self): with_mode(BASIC_CONVERSION, lambda: self.failUnless(r("c(4,5)") == [4,5]))() self.failUnlessRaises(RPyRException, lambda: r("foo")) self.failUnlessRaises(RPyRException, lambda: r("[$%^")) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/test_vars.py0000644000076700000240000000124210716155505015243 0ustar warnesstafffrom __future__ import nested_scopes import unittest import sys sys.path.insert(1, "..") import os.path, time from rpy import * class InitTestCase(unittest.TestCase): def setup(self): set_default_mode(NO_DEFAULT) def testGetVars(self): """ Define and access variables in the R namespace. """ r("f <- function(x) x+1") r.assign("x",100) r.assign("v",range(10)) r.assign("d",{'a':1, 'b':2}) self.failUnless( r.x == 100) self.failUnless( r.v == range(10)) self.failUnless( type(r.f) == type(r.c) ) if __name__ == '__main__': unittest.main() rpy-1.0.3/tests/testall.py0000644000076700000240000000165310716344354014711 0ustar warnesstaffimport os import sys import unittest import random import rpy def run(module): try: unittest.main(module) except SystemExit: pass if __name__ == '__main__': modules = os.listdir('.') if '--random' in sys.argv: shuffle=True sys.argv.remove('--random') else: shuffle=False if '--loop' in sys.argv: niter = 1000 sys.argv.remove('--loop') else: niter = 1 modules = filter( lambda x: not x.endswith('.pyc'), modules) modules = filter( lambda x: x.startswith('test_'), modules) modules = filter( lambda x: x.endswith('.py'), modules) print "Modules to be tested:", modules for iter in range(niter): if shuffle: random.shuffle(modules) for module in modules: name = module[:-3] print 'Testing:', name rpy.set_default_mode(rpy.NO_DEFAULT) # reset to base case run(name) rpy-1.0.3/tests/testscript_cleanup.py0000644000076700000240000000043210716155505017144 0ustar warnesstafffrom rpy import r import os.path # find out where the temp directory is tempdir = r.tempdir() # write its name into a file f = open('tempdir','w') f.write(tempdir) f.close() # put something there.. r.postscript(os.path.join(tempdir,"foo.ps")) r.plot(1,1) r.dev_off() rpy-1.0.3/TODO0000644000076700000240000000107611007445456012213 0ustar warnesstaff C=Critical, I=Important, U=Useful, O=Optional I* Update install instructions to include information about use of 'RHOMES' I* Ensure that either Numarray, Numeric, or NumPy can be used C* Properly clean up R when python exits, even if the user hasn't called 'q()' U* Posibility to pass Python functions to R functions U* More builtin classes for conversion of R classes I* More examples and a tutorial U* Modify setup.py for Mac OSX (darwin) to automagically set RHOMES and appropriately modify (and then restore) the Current symlink durin iteration of RHOMES