rpy-bridge 0.3.9__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rpy_bridge/logging.py ADDED
@@ -0,0 +1,50 @@
1
+ """
2
+ Logging utilities for rpy-bridge.
3
+
4
+ Sets up a loguru-backed logger (fallback to the stdlib logger) and a dedicated
5
+ [RFunctionCaller] sink used throughout the package.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import sys
12
+ from typing import TYPE_CHECKING
13
+
14
+ if TYPE_CHECKING: # pragma: no cover - typing only
15
+ from loguru import Logger as LoguruLogger
16
+
17
+ LoggerType = LoguruLogger | logging.Logger
18
+ else: # pragma: no cover - runtime does not need the alias
19
+ LoggerType = None
20
+
21
+ try:
22
+ from loguru import logger as loguru_logger # type: ignore
23
+
24
+ logger = loguru_logger
25
+ except ImportError: # pragma: no cover - fallback when loguru is absent
26
+ logging.basicConfig()
27
+ logger = logging.getLogger("rpy-bridge")
28
+
29
+ # Remove default handler to override global default
30
+ logger.remove()
31
+
32
+ # Add a sink for RFunctionCaller logs
33
+ _rfc_logger = logger.bind(tag="[RFunctionCaller]")
34
+ _rfc_logger.add(
35
+ sys.stderr,
36
+ format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
37
+ level="INFO",
38
+ )
39
+
40
+
41
+ def log_r_call(func_name: str, source_info: str) -> None:
42
+ """Log an R function call with minimal noise."""
43
+ _rfc_logger.opt(depth=1, record=False).info(
44
+ "[rpy-bridge.RFunctionCaller] Called R function '{}' from {}",
45
+ func_name,
46
+ source_info,
47
+ )
48
+
49
+
50
+ __all__ = ["logger", "_rfc_logger", "log_r_call", "LoggerType"]
rpy_bridge/renv.py ADDED
@@ -0,0 +1,149 @@
1
+ """
2
+ Helpers for locating project roots and activating renv environments.
3
+
4
+ These utilities are shared by RFunctionCaller and exposed for compatibility.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+
12
+ from .logging import logger
13
+ from .rpy2_loader import ensure_rpy2
14
+
15
+
16
+ def normalize_scripts(scripts: str | Path | list[str | Path] | None) -> list[Path]:
17
+ """
18
+ Normalize script inputs to a list of resolved Paths.
19
+ """
20
+ if scripts is None:
21
+ return []
22
+ if isinstance(scripts, (str, Path)):
23
+ return [Path(scripts).resolve()]
24
+ try:
25
+ return [Path(s).resolve() for s in scripts]
26
+ except TypeError as exc:
27
+ raise TypeError(
28
+ f"Invalid type for 'scripts': {type(scripts)}. Must be str, Path, or list/iterable thereof."
29
+ ) from exc
30
+
31
+
32
+ def candidate_project_dirs(base: Path, depth: int = 3) -> list[Path]:
33
+ return [base] + list(base.parents)[:depth]
34
+
35
+
36
+ def has_root_marker(path: Path) -> bool:
37
+ if (path / ".git").exists():
38
+ return True
39
+ if any(path.glob("*.Rproj")):
40
+ return True
41
+ if (path / ".here").exists():
42
+ return True
43
+ if (path / "DESCRIPTION").exists():
44
+ return True
45
+ if (path / "renv.lock").exists():
46
+ return True
47
+ return False
48
+
49
+
50
+ def find_project_root(path_to_renv: Path | None, scripts: list[Path]) -> Path | None:
51
+ bases: list[Path] = []
52
+ if scripts:
53
+ bases.extend(candidate_project_dirs(scripts[0].parent))
54
+ if path_to_renv is not None:
55
+ bases.extend(candidate_project_dirs(path_to_renv))
56
+
57
+ seen = set()
58
+ for cand in bases:
59
+ resolved = cand.resolve()
60
+ if resolved in seen:
61
+ continue
62
+ seen.add(resolved)
63
+ if has_root_marker(resolved):
64
+ return resolved
65
+ return None
66
+
67
+
68
+ def activate_renv(path_to_renv: Path) -> None:
69
+ r = ensure_rpy2()
70
+ robjects = r["robjects"]
71
+
72
+ path_to_renv = Path(path_to_renv).resolve()
73
+
74
+ def _candidates(base: Path) -> list[Path]:
75
+ return [base] + list(base.parents)[:3]
76
+
77
+ project_dir = None
78
+ renv_dir = None
79
+ renv_activate = None
80
+ renv_lock = None
81
+
82
+ for cand in _candidates(path_to_renv):
83
+ cand_is_renv = cand.name == "renv" and (cand / "activate.R").exists()
84
+ if cand_is_renv:
85
+ rd = cand
86
+ pd = cand.parent
87
+ else:
88
+ rd = cand / "renv"
89
+ pd = cand
90
+
91
+ activate_path = rd / "activate.R"
92
+ lock_path = pd / "renv.lock"
93
+ if not lock_path.exists():
94
+ alt_lock = rd / "renv.lock"
95
+ if alt_lock.exists():
96
+ lock_path = alt_lock
97
+
98
+ if activate_path.exists() and lock_path.exists():
99
+ project_dir = pd
100
+ renv_dir = rd
101
+ renv_activate = activate_path
102
+ renv_lock = lock_path
103
+ break
104
+
105
+ if renv_dir is None or renv_activate is None or renv_lock is None:
106
+ raise FileNotFoundError(
107
+ f"[Error] renv environment incomplete: activate.R or renv.lock not found near {path_to_renv}"
108
+ )
109
+
110
+ renviron_file = project_dir / ".Renviron"
111
+ if renviron_file.is_file():
112
+ os.environ["R_ENVIRON_USER"] = str(renviron_file)
113
+ logger.info(f"[rpy-bridge] R_ENVIRON_USER set to: {renviron_file}")
114
+
115
+ rprofile_file = project_dir / ".Rprofile"
116
+ if rprofile_file.is_file():
117
+ try:
118
+ robjects.r(
119
+ f'old_wd <- getwd(); setwd("{project_dir.as_posix()}"); '
120
+ f"on.exit(setwd(old_wd), add = TRUE); "
121
+ f'source("{rprofile_file.as_posix()}")'
122
+ )
123
+ logger.info(f"[rpy-bridge] .Rprofile sourced: {rprofile_file}")
124
+ except Exception as exc: # pragma: no cover - defensive fallback
125
+ logger.warning(
126
+ "[rpy-bridge] Failed to source .Rprofile; falling back to renv::activate(): %s",
127
+ exc,
128
+ )
129
+
130
+ try:
131
+ robjects.r("suppressMessages(library(renv))")
132
+ except Exception:
133
+ logger.info("[rpy-bridge] Installing renv package in project library...")
134
+ robjects.r(
135
+ f'install.packages("renv", repos="https://cloud.r-project.org", lib="{renv_dir / "library"}")'
136
+ )
137
+ robjects.r("library(renv)")
138
+
139
+ robjects.r(f'renv::load("{project_dir.as_posix()}")')
140
+ logger.info(f"[rpy-bridge] renv environment loaded for project: {project_dir}")
141
+
142
+
143
+ __all__ = [
144
+ "activate_renv",
145
+ "normalize_scripts",
146
+ "candidate_project_dirs",
147
+ "has_root_marker",
148
+ "find_project_root",
149
+ ]
@@ -0,0 +1,71 @@
1
+ """
2
+ Lazy loader for rpy2 objects and converters.
3
+
4
+ Provides cached access to rpy2 modules to avoid repeated imports.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ _RPY2: dict[str, Any] | None = None
12
+
13
+
14
+ def _require_rpy2(raise_on_missing: bool = True) -> dict[str, Any] | None:
15
+ """
16
+ Import rpy2 lazily and cache its key objects.
17
+ """
18
+ global _RPY2
19
+ if _RPY2 is not None:
20
+ return _RPY2
21
+
22
+ try:
23
+ import rpy2.robjects as ro
24
+ from rpy2 import robjects
25
+ from rpy2.rinterface_lib.sexp import NULLType
26
+ from rpy2.rlike.container import NamedList
27
+ from rpy2.robjects import pandas2ri
28
+ from rpy2.robjects.conversion import localconverter
29
+ from rpy2.robjects.vectors import (
30
+ BoolVector,
31
+ FloatVector,
32
+ IntVector,
33
+ ListVector,
34
+ StrVector,
35
+ )
36
+
37
+ _RPY2 = {
38
+ "ro": ro,
39
+ "robjects": robjects,
40
+ "pandas2ri": pandas2ri,
41
+ "localconverter": localconverter,
42
+ "BoolVector": BoolVector,
43
+ "FloatVector": FloatVector,
44
+ "IntVector": IntVector,
45
+ "ListVector": ListVector,
46
+ "StrVector": StrVector,
47
+ "NULLType": NULLType,
48
+ "NamedList": NamedList,
49
+ }
50
+ return _RPY2
51
+
52
+ except ImportError as exc:
53
+ if raise_on_missing:
54
+ raise RuntimeError(
55
+ "R support requires rpy2; install it in your Python env (e.g., pip install rpy2)"
56
+ ) from exc
57
+ return None
58
+
59
+
60
+ def ensure_rpy2() -> dict[str, Any]:
61
+ """
62
+ Return the cached rpy2 bundle, raising if unavailable.
63
+ """
64
+ global _RPY2
65
+ if _RPY2 is None:
66
+ _RPY2 = _require_rpy2()
67
+ assert _RPY2 is not None, "_require_rpy2() returned None"
68
+ return _RPY2
69
+
70
+
71
+ __all__ = ["ensure_rpy2", "_require_rpy2"]
@@ -0,0 +1,297 @@
1
+ Metadata-Version: 2.4
2
+ Name: rpy-bridge
3
+ Version: 0.5.0
4
+ Summary: Python-to-R interoperability engine with environment management, type-safe conversions, data normalization, and safe R function execution.
5
+ Author-email: Victoria Cheung <victoriakcheung@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Victoria Cheung
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Acknowledgement: This project builds on work originally developed at
29
+ Revolution Medicines and interfaces with the rpy2 project, which is licensed
30
+ under the GNU General Public License version 2 or later.
31
+
32
+ Project-URL: Homepage, https://github.com/vic-cheung/rpy-bridge
33
+ Project-URL: Issue Tracker, https://github.com/vic-cheung/rpy-bridge/issues
34
+ Keywords: python,r,rpy2,python-r,interoperability,data-science,statistics,bioinformatics
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Intended Audience :: Developers
41
+ Classifier: Intended Audience :: Science/Research
42
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
43
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
44
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
45
+ Requires-Python: >=3.11
46
+ Description-Content-Type: text/markdown
47
+ License-File: LICENSE
48
+ Requires-Dist: numpy>=1.24
49
+ Requires-Dist: pandas>=2.0
50
+ Requires-Dist: loguru>=0.7
51
+ Provides-Extra: r
52
+ Requires-Dist: rpy2>=3.5; extra == "r"
53
+ Provides-Extra: dev
54
+ Requires-Dist: ipykernel>=7.1.0; extra == "dev"
55
+ Provides-Extra: docs
56
+ Requires-Dist: sphinx; extra == "docs"
57
+ Requires-Dist: myst-parser; extra == "docs"
58
+ Dynamic: license-file
59
+
60
+ # rpy-bridge
61
+
62
+ **rpy-bridge** is a Python-controlled **R execution orchestrator** that enables
63
+ Python code to run R functions, scripts, and packages with **reproducible
64
+ filesystem and environment semantics**.
65
+
66
+ It is built on top of `rpy2`, but unlike thin wrappers, rpy-bridge stabilizes how
67
+ R code is executed when invoked from Python: project roots are inferred, `renv`
68
+ environments can be activated out-of-tree, relative paths behave as expected,
69
+ and return values are normalized for safe Python consumption.
70
+
71
+ This makes rpy-bridge suitable for production pipelines, CI, and bilingual
72
+ Python/R teams where R code must run reliably outside an interactive R session.
73
+
74
+ **Latest release:** [`rpy-bridge` on PyPI](https://pypi.org/project/rpy-bridge/)
75
+
76
+ ---
77
+
78
+ ## What this is (and is not)
79
+
80
+ rpy-bridge **is not a thin rpy2 wrapper**.
81
+
82
+ Typical rpy2 usage assumes:
83
+ - the Python working directory is the R project root
84
+ - `renv` lives next to the executing script
85
+ - relative paths resolve correctly by default
86
+ - all R code executes in `globalenv()`
87
+
88
+ These assumptions break quickly in real-world Python workflows.
89
+
90
+ rpy-bridge instead provides a **controlled R runtime** with explicit guarantees
91
+ around execution context, filesystem behavior, and environment activation.
92
+
93
+ ---
94
+
95
+ ## Core capabilities
96
+
97
+ ### 1. R execution orchestration
98
+
99
+ - Embeds R via `rpy2` with deterministic startup behavior
100
+ - Disables interactive and GUI-dependent hooks for headless execution
101
+ - Loads R scripts into isolated namespaces (not `globalenv()`)
102
+
103
+ ### 2. Project root inference and path stability
104
+
105
+ - Infers R project roots using markers such as:
106
+ `.git`, `.Rproj`, `renv.lock`, `DESCRIPTION`, `.here`
107
+ - Executes R code from the inferred project root regardless of Python CWD
108
+ - Preserves relative-path behavior expected by R scripts
109
+ - Supports R code using `here::here()` or project-local data
110
+
111
+ ### 3. Out-of-tree `renv` activation
112
+
113
+ - Activates `renv` projects located **outside** the calling Python directory
114
+ - Sources `.Rprofile` and `.Renviron` to reproduce R startup semantics
115
+ - Does not require R scripts and `renv` to live in the same directory
116
+
117
+ ### 4. Python ↔ R data conversion
118
+
119
+ - Converts Python scalars, lists, dicts, and pandas objects into R equivalents
120
+ - Converts R vectors, lists, and data.frames back into Python-native types
121
+ - Handles nested structures, missing values, and mixed types robustly
122
+
123
+ ### 5. Data normalization and diagnostics
124
+
125
+ - Post-processes R data.frames to fix dtype, timezone, and NA semantics
126
+ - Normalizes column types for reliable Python-side comparison
127
+ - Supports structured mismatch diagnostics between Python and R data
128
+
129
+ ### 6. Function invocation across scripts and packages
130
+
131
+ - Calls functions defined in sourced R scripts, base R, or installed packages
132
+ - Supports qualified function names (e.g. `stats::median`)
133
+ - Executes functions within the active project and library context
134
+
135
+ ---
136
+
137
+ ## Calling base R functions and managing packages
138
+
139
+ In addition to sourcing local R scripts, rpy-bridge supports calling functions
140
+ from base R and installed packages directly from Python.
141
+
142
+ Current support includes:
143
+
144
+ - Calling base R functions without a local R script
145
+ - Executing functions from installed R packages within the active environment
146
+
147
+ Planned extensions (roadmap):
148
+
149
+ - Programmatic installation of R packages into the active `renv` or system
150
+ environment when explicitly enabled
151
+ - Declarative package requirements at the Python call site
152
+ - Safe, opt-in package installation for CI and ephemeral environments
153
+
154
+ Package installation is intentionally **not automatic by default** to preserve
155
+ reproducibility and avoid side effects during execution.
156
+
157
+ ---
158
+
159
+ ## Installation
160
+
161
+ ### Prerequisites
162
+
163
+ - System R installed and available on `PATH`
164
+ - Python 3.12+
165
+
166
+ ### From PyPI
167
+
168
+ Install rpy-bridge with rpy2 for full R support:
169
+
170
+ ```bash
171
+ python3 -m pip install rpy-bridge rpy2
172
+ ```
173
+
174
+ Using `uv`:
175
+
176
+ ```bash
177
+ uv add rpy-bridge rpy2
178
+ ```
179
+
180
+ ### Development install
181
+
182
+ ```bash
183
+ python3 -m pip install -e .
184
+ ```
185
+
186
+ or:
187
+
188
+ ```bash
189
+ uv sync
190
+ ```
191
+
192
+ ### Required Python dependencies
193
+
194
+ - `rpy2`
195
+ - `pandas`
196
+ - `numpy`
197
+
198
+ ---
199
+
200
+ ## Usage
201
+
202
+ ### Call a function from a local R script
203
+
204
+ ```python
205
+ from pathlib import Path
206
+ from rpy_bridge import RFunctionCaller
207
+
208
+ project_dir = Path("/path/to/your-r-project")
209
+ script = project_dir / "scripts" / "example.R"
210
+
211
+ caller = RFunctionCaller(
212
+ path_to_renv=project_dir,
213
+ script_path=script,
214
+ )
215
+
216
+ result = caller.call("some_function", 42, named_arg="value")
217
+ ```
218
+
219
+ ### Call base R functions (no local script)
220
+
221
+ ```python
222
+ from rpy_bridge import RFunctionCaller
223
+
224
+ caller = RFunctionCaller(path_to_renv=None)
225
+
226
+ samples = caller.call("stats::rnorm", 10, mean=0, sd=1)
227
+ median_val = caller.call("stats::median", samples)
228
+ ```
229
+
230
+ ---
231
+
232
+ ## Round-trip Python ↔ R behavior
233
+
234
+ rpy-bridge attempts to convert Python objects to R and back. Most objects used in
235
+ scientific and ML pipelines round-trip cleanly, but some heterogeneous Python
236
+ structures may be wrapped or slightly altered due to differences in R’s type
237
+ system.
238
+
239
+ | Python type | Round-trip fidelity | Notes |
240
+ | ---------------------------------------------- | ------------------- | --------------------------------------------------------------------- |
241
+ | `int`, `float`, `bool`, `str` | High | Scalars convert directly |
242
+ | Homogeneous `list` of numbers/strings | High | Converted to atomic R vectors |
243
+ | Nested homogeneous lists | High | Converted to nested R lists |
244
+ | `pandas.DataFrame` / `pd.Series` | High | Converted to `data.frame` and normalized on return |
245
+ | Mixed-type `list` or `dict` | Partial | May be wrapped in single-element vectors |
246
+ | `None` / `pd.NA` | High | Converted to R `NULL` |
247
+
248
+ ---
249
+
250
+ ## R setup helpers
251
+
252
+ Helper scripts are provided in `examples/r-deps/` to prepare R environments.
253
+
254
+ - Install system R dependencies (macOS / Homebrew):
255
+
256
+ ```bash
257
+ bash examples/r-deps/install_r_dev_deps_homebrew.sh
258
+ ```
259
+
260
+ - Initialize an `renv` project:
261
+
262
+ ```r
263
+ source("examples/r-deps/setup_env.R")
264
+ ```
265
+
266
+ - Restore the environment on a new machine:
267
+
268
+ ```r
269
+ renv::restore()
270
+ ```
271
+
272
+ ---
273
+
274
+ ## Who this is for
275
+
276
+ rpy-bridge is designed for:
277
+
278
+ - Python-first pipelines that rely on mature R code
279
+ - Teams where R logic must remain authoritative
280
+ - CI or production systems that cannot rely on interactive R sessions
281
+ - Multi-repo or multi-directory projects with non-trivial filesystem layouts
282
+
283
+ It is **not** intended as a convenience wrapper for exploratory R usage.
284
+
285
+ ---
286
+
287
+ ## Licensing
288
+
289
+ - rpy-bridge is released under the MIT License © 2025 Victoria Cheung
290
+ - Depends on [`rpy2`](https://rpy2.github.io), licensed under the GNU GPL (v2 or later)
291
+
292
+ ---
293
+
294
+ ## Acknowledgements
295
+
296
+ This package was spun out of internal tooling I wrote at Revolution Medicines.
297
+ Thanks to the team there for supporting its open-source release.
@@ -0,0 +1,15 @@
1
+ rpy_bridge/__init__.py,sha256=3UP1OOLuBaX7I9XsTaRsxr3EPYsGJere-Jh3xgc24QI,313
2
+ rpy_bridge/compare.py,sha256=pwNOYLMrm7zJlsxzTooPl7OSmhPw-dc7owngJvV-7-0,4129
3
+ rpy_bridge/convert.py,sha256=7DzdIGWl0eUYKzsfA5npL1DWKyhfk3gZ0CT2zAg2xfs,1952
4
+ rpy_bridge/core.py,sha256=pkdsYsy0mXM7CDOkGA8Hev2KdfPn5NCsl_pP6zBalp0,18493
5
+ rpy_bridge/dataframe.py,sha256=nocmc3yTyk1omCRKb1otNuwO73FzfxFeoVunH8oZC-Y,2310
6
+ rpy_bridge/env.py,sha256=YN3tvl1eUp9IhbTmPgjSVKpRLTuf0OARgkMobQJd0Ks,3581
7
+ rpy_bridge/logging.py,sha256=9U2RJHmxLqrXEwS38TkrSqeETXxn1AAfL8BGTjnzSGY,1360
8
+ rpy_bridge/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ rpy_bridge/renv.py,sha256=BYBFXP8SslKzD-GZ0yi7T-nMwqcIx2hYPY3BC_xSSZU,4511
10
+ rpy_bridge/rpy2_loader.py,sha256=rQEnAiJbzkTzb4UlcOsG8D4MXZ0LWtYLMP8DequBNzg,1874
11
+ rpy_bridge-0.5.0.dist-info/licenses/LICENSE,sha256=JwbWVcSfeoLfZ2M_ZiyygKVDvhBDW3zbqTWwXOJwmrA,1276
12
+ rpy_bridge-0.5.0.dist-info/METADATA,sha256=6bkzCM7gFr1gtOUF007Zrhhjy9vvNtduX9Vq4o7_YN4,10188
13
+ rpy_bridge-0.5.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
+ rpy_bridge-0.5.0.dist-info/top_level.txt,sha256=z9UZ77ZuUPoLqMDQEpP4btstsaM1IpXb9Cn9yBVaHmU,11
15
+ rpy_bridge-0.5.0.dist-info/RECORD,,