polyester 0.1.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.
- polyester/__init__.py +5 -0
- polyester/channels.py +22 -0
- polyester/interpreter.py +143 -0
- polyester/pyinterpreter.py +29 -0
- polyester/rinterpreter.py +50 -0
- polyester/utils.py +17 -0
- polyester/workers/__init__.py +0 -0
- polyester/workers/pyworker.py +149 -0
- polyester-0.1.0.dist-info/METADATA +168 -0
- polyester-0.1.0.dist-info/RECORD +13 -0
- polyester-0.1.0.dist-info/WHEEL +5 -0
- polyester-0.1.0.dist-info/licenses/LICENSE +201 -0
- polyester-0.1.0.dist-info/top_level.txt +1 -0
polyester/__init__.py
ADDED
polyester/channels.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import subprocess
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class JsonChannel:
|
|
6
|
+
"""Communicate messages through LJSON over stdin/stdout of a subprocess."""
|
|
7
|
+
def __init__(self, args):
|
|
8
|
+
self._remote = subprocess.Popen(
|
|
9
|
+
args,
|
|
10
|
+
stdin=subprocess.PIPE,
|
|
11
|
+
stdout=subprocess.PIPE,
|
|
12
|
+
text=True,
|
|
13
|
+
bufsize=1
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
def write(self, msg):
|
|
17
|
+
msg = json.dumps(msg)
|
|
18
|
+
self._remote.stdin.write(msg)
|
|
19
|
+
self._remote.stdin.write("\n")
|
|
20
|
+
|
|
21
|
+
def read(self):
|
|
22
|
+
return json.loads(self._remote.stdout.readline())
|
polyester/interpreter.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import abc
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
4
|
+
from json import JSONDecodeError
|
|
5
|
+
from typing import Type, Any
|
|
6
|
+
|
|
7
|
+
import narwhals as nw
|
|
8
|
+
import pyarrow.ipc as ipc
|
|
9
|
+
|
|
10
|
+
ARROW_PROTOCOLS = [
|
|
11
|
+
"__arrow_c_schema__",
|
|
12
|
+
"__arrow_c_array__",
|
|
13
|
+
"__arrow_c_stream__"
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Interpreter(metaclass=abc.ABCMeta):
|
|
18
|
+
remote_object: Type["RemoteObject"]
|
|
19
|
+
remote_name: Type["RemoteName"]
|
|
20
|
+
|
|
21
|
+
def __init__(self, channel, df_backend='polars'):
|
|
22
|
+
self._channel = channel
|
|
23
|
+
self.df_backend = df_backend
|
|
24
|
+
|
|
25
|
+
def __getitem__(self, item: str) -> "RemoteName":
|
|
26
|
+
return self.remote_name(self, item)
|
|
27
|
+
|
|
28
|
+
def __setitem__(self, name: str, source: "Remote"):
|
|
29
|
+
self.cmd("assign", target=name, source=source.to_dict())
|
|
30
|
+
|
|
31
|
+
def module(self, name: str) -> Any:
|
|
32
|
+
raise NotImplementedError("This interpreter doesn't support modules.")
|
|
33
|
+
|
|
34
|
+
def cmd(self, cmd: str, **kwargs) -> dict:
|
|
35
|
+
self._channel.write({"cmd": cmd, **kwargs})
|
|
36
|
+
msg = self._channel.read()
|
|
37
|
+
status = msg["status"]
|
|
38
|
+
if status == "ok":
|
|
39
|
+
return msg
|
|
40
|
+
else:
|
|
41
|
+
raise ValueError(f"{msg}")
|
|
42
|
+
|
|
43
|
+
def insert(self, data: Any, target_type=None) -> "RemoteObject":
|
|
44
|
+
"""Insert data.
|
|
45
|
+
|
|
46
|
+
This either writes the data to a temporary file or encodes it in the json.
|
|
47
|
+
"""
|
|
48
|
+
if any(hasattr(data, protocol) for protocol in ARROW_PROTOCOLS):
|
|
49
|
+
table = nw.from_native(data).to_arrow()
|
|
50
|
+
with tempfile.NamedTemporaryFile(delete=False, mode="wb") as tmp:
|
|
51
|
+
with ipc.new_stream(tmp, table.schema) as writer:
|
|
52
|
+
writer.write_table(table)
|
|
53
|
+
|
|
54
|
+
msg = self.cmd("insert", encoding="arrow", path=tmp.name, type=target_type)
|
|
55
|
+
else:
|
|
56
|
+
# Serialize value to json
|
|
57
|
+
try:
|
|
58
|
+
msg = self.cmd("insert", value=data)
|
|
59
|
+
except JSONDecodeError:
|
|
60
|
+
raise ValueError("Value {type(data)} not a dataframe or json-serializable.")
|
|
61
|
+
|
|
62
|
+
return self.remote_object(self, msg["id"])
|
|
63
|
+
|
|
64
|
+
def get(self, obj: "Remote", df_backend=None) -> Any:
|
|
65
|
+
msg = self.cmd("get", **obj.to_dict())
|
|
66
|
+
try:
|
|
67
|
+
value = msg["value"]
|
|
68
|
+
except KeyError:
|
|
69
|
+
with open(msg["path"], "rb") as f:
|
|
70
|
+
arrow = ipc.open_stream(f).read_all()
|
|
71
|
+
value = nw.from_arrow(arrow, backend=df_backend or self.df_backend)
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
os.remove(msg["path"])
|
|
75
|
+
except OSError:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
return value
|
|
79
|
+
|
|
80
|
+
def call(self, function: "Remote", /, *args, **kwargs) -> "RemoteObject":
|
|
81
|
+
packed_function = function.to_dict()
|
|
82
|
+
packed_args = list(map(self._prepare_arg, args))
|
|
83
|
+
packed_kwargs = {k: self._prepare_arg(v) for k, v in kwargs.items()}
|
|
84
|
+
msg = self.cmd("call", function=packed_function, args=packed_args, kwargs=packed_kwargs)
|
|
85
|
+
return RemoteObject(self, msg["id"])
|
|
86
|
+
|
|
87
|
+
@staticmethod
|
|
88
|
+
def _prepare_arg(obj) -> dict:
|
|
89
|
+
if isinstance(obj, Remote):
|
|
90
|
+
return obj.to_dict()
|
|
91
|
+
else:
|
|
92
|
+
return {'value': obj}
|
|
93
|
+
|
|
94
|
+
def eval(self, code: str) -> "RemoteObject":
|
|
95
|
+
msg = self.cmd("eval", code=code)
|
|
96
|
+
return self.remote_object(self, msg["id"])
|
|
97
|
+
|
|
98
|
+
def exec(self, code: str) -> None:
|
|
99
|
+
self.cmd("exec", code=code)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Remote(metaclass=abc.ABCMeta):
|
|
103
|
+
_interpreter: Interpreter
|
|
104
|
+
|
|
105
|
+
@abc.abstractmethod
|
|
106
|
+
def to_dict(self):
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
def get(self, df_backend=None):
|
|
110
|
+
return self._interpreter.get(self, df_backend=df_backend)
|
|
111
|
+
|
|
112
|
+
def __call__(self, *args, **kwargs):
|
|
113
|
+
return self._interpreter.call(self, *args, **kwargs)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class RemoteObject(Remote):
|
|
117
|
+
def __init__(self, interpreter, id):
|
|
118
|
+
self._interpreter = interpreter
|
|
119
|
+
self.id = id
|
|
120
|
+
|
|
121
|
+
def __repr__(self):
|
|
122
|
+
return f"{self.__class__.__name__}{self._interpreter, self.id})"
|
|
123
|
+
|
|
124
|
+
def to_dict(self):
|
|
125
|
+
return {"id": self.id}
|
|
126
|
+
|
|
127
|
+
def __del__(self):
|
|
128
|
+
self._interpreter.cmd("delete", id=self.id)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class RemoteName(Remote):
|
|
132
|
+
def __init__(self, interpreter: Interpreter, name: str):
|
|
133
|
+
self._interpreter = interpreter
|
|
134
|
+
self.name = name
|
|
135
|
+
|
|
136
|
+
def __repr__(self):
|
|
137
|
+
return f"{self.__class__.__name__}{self._interpreter, self.name}"
|
|
138
|
+
|
|
139
|
+
def to_dict(self):
|
|
140
|
+
return {"name": self.name}
|
|
141
|
+
|
|
142
|
+
def __getattr__(self, item) -> "RemoteName":
|
|
143
|
+
raise NotImplementedError(f"Attributes are not implemented for {type(self._interpreter).__name__}")
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from polyester.interpreter import RemoteObject, Interpreter, RemoteName
|
|
5
|
+
from polyester.channels import JsonChannel
|
|
6
|
+
|
|
7
|
+
class RemotePyObject(RemoteObject):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RemotePyName(RemoteName):
|
|
12
|
+
def __getattr__(self, item):
|
|
13
|
+
return RemotePyName(self._interpreter, f"{self.name}.{item}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PyInterpreter(Interpreter):
|
|
17
|
+
remote_object = RemotePyObject
|
|
18
|
+
remote_name = RemotePyName
|
|
19
|
+
worker_path = Path(__file__).parent / "workers/pyworker.py"
|
|
20
|
+
|
|
21
|
+
def __init__(self, interpreter_path=None):
|
|
22
|
+
if interpreter_path is None:
|
|
23
|
+
interpreter_path = sys.executable
|
|
24
|
+
channel = JsonChannel([interpreter_path, "-u", self.worker_path])
|
|
25
|
+
super().__init__(channel)
|
|
26
|
+
|
|
27
|
+
def module(self, name):
|
|
28
|
+
self.exec(f"import {name}")
|
|
29
|
+
return self[name]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from polyester.interpreter import RemoteObject, Interpreter, RemoteName
|
|
4
|
+
from polyester.channels import JsonChannel
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class RemoteRObject(RemoteObject):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RemoteRName(RemoteName):
|
|
12
|
+
def __getattr__(self, item):
|
|
13
|
+
raise NotImplementedError("Ambiguous attribute. Use `obj.dcolon/dollar/at(name)` instead.")
|
|
14
|
+
|
|
15
|
+
def dcolon(self, name):
|
|
16
|
+
"""Insert double colon in name."""
|
|
17
|
+
return RemoteRName(interpreter=self._interpreter, name=f"{self.name}::{name}")
|
|
18
|
+
|
|
19
|
+
def dollar(self, name):
|
|
20
|
+
"""Insert dollar in name."""
|
|
21
|
+
return RemoteRName(interpreter=self._interpreter, name=f"{self.name}${name}")
|
|
22
|
+
|
|
23
|
+
def at(self, name):
|
|
24
|
+
"""Access S4 slot."""
|
|
25
|
+
return RemoteRName(interpreter=self._interpreter, name=f"{self.name}@{name}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RModule:
|
|
29
|
+
def __init__(self, interpreter: Interpreter, name: str):
|
|
30
|
+
self._name = name
|
|
31
|
+
self._interpreter = interpreter
|
|
32
|
+
|
|
33
|
+
def __getattr__(self, item) -> RemoteName:
|
|
34
|
+
return self._interpreter[f"{self._name}::{item}"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RInterpreter(Interpreter):
|
|
38
|
+
remote_object = RemoteRObject
|
|
39
|
+
remote_name = RemoteRName
|
|
40
|
+
worker_path = Path(__file__).parent / "workers/rworker.R"
|
|
41
|
+
|
|
42
|
+
def __init__(self, interpreter_path):
|
|
43
|
+
if interpreter_path is None:
|
|
44
|
+
interpreter_path = "Rscript"
|
|
45
|
+
|
|
46
|
+
channel = JsonChannel([interpreter_path, "--vanilla", self.worker_path])
|
|
47
|
+
super().__init__(channel)
|
|
48
|
+
|
|
49
|
+
def module(self, name: str) -> RModule:
|
|
50
|
+
return RModule(self, name)
|
polyester/utils.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from polyester.pyinterpreter import PyInterpreter
|
|
2
|
+
from polyester.rinterpreter import RInterpreter
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def get_interpreter(lang="R", path=None):
|
|
6
|
+
"""Return an interpreter.
|
|
7
|
+
|
|
8
|
+
:param lang: Which language you want.
|
|
9
|
+
:param path: Where the interpreter is located.
|
|
10
|
+
"""
|
|
11
|
+
match lang.lower():
|
|
12
|
+
case "py" | "python":
|
|
13
|
+
return PyInterpreter(path)
|
|
14
|
+
case "r" | "rlang":
|
|
15
|
+
return RInterpreter(path)
|
|
16
|
+
case unknown_lang:
|
|
17
|
+
raise ValueError(f"Unknown language: {unknown_lang}")
|
|
File without changes
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# #!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
This is the python worker.
|
|
5
|
+
|
|
6
|
+
It is made mostly for reference purposes.
|
|
7
|
+
Although it can be used for sandboxing or for calling a different python interpreter than the main one.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
import narwhals as nw
|
|
15
|
+
|
|
16
|
+
import pyarrow.ipc as ipc
|
|
17
|
+
|
|
18
|
+
ARROW_PROTOCOLS = [
|
|
19
|
+
"__arrow_c_schema__",
|
|
20
|
+
"__arrow_c_array__",
|
|
21
|
+
"__arrow_c_stream__"
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PyWorker:
|
|
26
|
+
def __init__(self):
|
|
27
|
+
self._env = {}
|
|
28
|
+
|
|
29
|
+
def run(self):
|
|
30
|
+
while line := sys.stdin.readline():
|
|
31
|
+
try:
|
|
32
|
+
msg = json.loads(line)
|
|
33
|
+
except json.JSONDecodeError as err:
|
|
34
|
+
response = {"status": "error", "message": str(err)}
|
|
35
|
+
else:
|
|
36
|
+
try:
|
|
37
|
+
match msg["cmd"]:
|
|
38
|
+
case "eval":
|
|
39
|
+
response = self.handle_eval(msg)
|
|
40
|
+
case "exec":
|
|
41
|
+
response = self.handle_exec(msg)
|
|
42
|
+
case "get":
|
|
43
|
+
response = self.handle_get(msg)
|
|
44
|
+
case "insert":
|
|
45
|
+
response = self.handle_insert(msg)
|
|
46
|
+
case "delete":
|
|
47
|
+
response = self.handle_delete(msg)
|
|
48
|
+
case "assign":
|
|
49
|
+
response = self.handle_assign(msg),
|
|
50
|
+
case "call":
|
|
51
|
+
response = self.handle_call(msg)
|
|
52
|
+
case unknown_cmd:
|
|
53
|
+
raise ValueError(f"Unknown command: {unknown_cmd}")
|
|
54
|
+
except Exception as err:
|
|
55
|
+
response = {"status": "err", "message": str(err)}
|
|
56
|
+
|
|
57
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
58
|
+
sys.stdout.flush()
|
|
59
|
+
|
|
60
|
+
def store_obj(self, value):
|
|
61
|
+
"""Store object in memory."""
|
|
62
|
+
self._env['_' + hex(id(value))] = value
|
|
63
|
+
return id(value)
|
|
64
|
+
|
|
65
|
+
def resolve_obj(self, data):
|
|
66
|
+
"""Retrieve object from memory."""
|
|
67
|
+
if "id" in data:
|
|
68
|
+
return self._env['_' + hex(data['id'])]
|
|
69
|
+
elif "name" in data:
|
|
70
|
+
name_parts = iter(data['name'].split('.'))
|
|
71
|
+
obj = self._env[next(name_parts)]
|
|
72
|
+
for part in name_parts:
|
|
73
|
+
obj = getattr(obj, part)
|
|
74
|
+
return obj
|
|
75
|
+
elif "value" in data:
|
|
76
|
+
return data['value']
|
|
77
|
+
else:
|
|
78
|
+
raise ValueError(f"Unable to resolve object: {data}")
|
|
79
|
+
|
|
80
|
+
def delete(self, id):
|
|
81
|
+
del self._env['_' + hex(id)]
|
|
82
|
+
|
|
83
|
+
def handle_eval(self, msg):
|
|
84
|
+
"""Evaluate expression and store."""
|
|
85
|
+
id = self.store_obj(eval(msg["code"], self._env))
|
|
86
|
+
return {"status": "ok", "id": id}
|
|
87
|
+
|
|
88
|
+
def handle_exec(self, msg):
|
|
89
|
+
"""Execute code but don't store result."""
|
|
90
|
+
exec(msg["code"], self._env)
|
|
91
|
+
return {"status": "ok"}
|
|
92
|
+
|
|
93
|
+
def handle_insert(self, msg):
|
|
94
|
+
"""Import value."""
|
|
95
|
+
|
|
96
|
+
if "path" in msg:
|
|
97
|
+
with open(msg["path"], "rb") as f:
|
|
98
|
+
table = ipc.open_stream(f).read_all()
|
|
99
|
+
backend = msg.get("type") or "polars"
|
|
100
|
+
obj = nw.from_arrow(table, backend=backend).to_native()
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
os.remove(msg["path"])
|
|
104
|
+
except OSError:
|
|
105
|
+
pass
|
|
106
|
+
else:
|
|
107
|
+
obj = msg["value"]
|
|
108
|
+
|
|
109
|
+
id = self.store_obj(obj)
|
|
110
|
+
return {"status": "ok", "id": id}
|
|
111
|
+
|
|
112
|
+
def handle_get(self, msg):
|
|
113
|
+
"""Retrieve a stored value."""
|
|
114
|
+
value = self.resolve_obj(msg)
|
|
115
|
+
|
|
116
|
+
if any(hasattr(value, protocol) for protocol in ARROW_PROTOCOLS):
|
|
117
|
+
table = nw.from_native(value).to_arrow()
|
|
118
|
+
|
|
119
|
+
tmp = tempfile.NamedTemporaryFile(suffix=".arrow", delete=False)
|
|
120
|
+
with ipc.new_stream(tmp, table.schema) as writer:
|
|
121
|
+
writer.write_table(table)
|
|
122
|
+
|
|
123
|
+
return {"status": "ok", "encoding": "arrow", "path": tmp.name}
|
|
124
|
+
else:
|
|
125
|
+
return {"status": "ok", "value": value}
|
|
126
|
+
|
|
127
|
+
def handle_delete(self, msg):
|
|
128
|
+
"""Delete a value."""
|
|
129
|
+
self.delete(msg["id"])
|
|
130
|
+
return {"status": "ok"}
|
|
131
|
+
|
|
132
|
+
def handle_assign(self, msg):
|
|
133
|
+
"""Assign value to a name."""
|
|
134
|
+
target = msg["target"]
|
|
135
|
+
source = self.resolve_obj(msg["source"])
|
|
136
|
+
self._env[target] = source
|
|
137
|
+
return {"status": "ok"}
|
|
138
|
+
|
|
139
|
+
def handle_call(self, msg):
|
|
140
|
+
"""Make a call."""
|
|
141
|
+
f = self.resolve_obj(msg['function'])
|
|
142
|
+
args = [self.resolve_obj(arg) for arg in msg['args']]
|
|
143
|
+
id = self.store_obj(f(*args))
|
|
144
|
+
return {"status": "ok", "id": id}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
if __name__ == '__main__':
|
|
148
|
+
worker = PyWorker()
|
|
149
|
+
worker.run()
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: polyester
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run R interpreter from python
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: narwhals>=2.16.0
|
|
10
|
+
Requires-Dist: pyarrow>=23.0.1
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# Polyester
|
|
14
|
+
|
|
15
|
+
**Polyester** makes it possible to use R from Python by running R in a background process and communicating through a lightweight message protocol.
|
|
16
|
+
|
|
17
|
+
The goal is simplicity and reliability — especially on Windows — while keeping the design extensible to other languages in the future.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quick Example
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from polyester import get_interpreter
|
|
25
|
+
|
|
26
|
+
# Start an R interpreter
|
|
27
|
+
rr = get_interpreter(
|
|
28
|
+
"R",
|
|
29
|
+
path=r"C:\Program Files\R\R-4.5.2\bin\Rscript.exe"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Access an R module (namespace)
|
|
33
|
+
rbase = rr.module("base")
|
|
34
|
+
|
|
35
|
+
# Simple calculations
|
|
36
|
+
x = rr.eval("sin(100)")
|
|
37
|
+
y = rbase.cos(100)
|
|
38
|
+
|
|
39
|
+
print(x.get(), y.get())
|
|
40
|
+
|
|
41
|
+
# Bring a dataframe from R to Python
|
|
42
|
+
iris_r = rr.eval("iris") # RemoteObject
|
|
43
|
+
iris_df = iris_r.get("pandas")
|
|
44
|
+
print(iris_df.head())
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Core Concepts
|
|
50
|
+
|
|
51
|
+
Polyester revolves around a single concept: **an interpreter**.
|
|
52
|
+
|
|
53
|
+
An interpreter manages:
|
|
54
|
+
|
|
55
|
+
* A background R process
|
|
56
|
+
* A private remote environment
|
|
57
|
+
* Communication over JSON Lines
|
|
58
|
+
* Data exchange using Apache Arrow
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Interpreter API
|
|
63
|
+
|
|
64
|
+
An interpreter supports the following operations:
|
|
65
|
+
|
|
66
|
+
| Operation | Parameters | Returns | Description |
|
|
67
|
+
| ------------------ | ----------------------------------- | ------------------- | -------------------------------- |
|
|
68
|
+
| `insert` | `x: simple/dataframe` | `RemoteObject` | Send Python data to R |
|
|
69
|
+
| `get` | `x: Remote` | `simple/dataframe` | Retrieve data from R |
|
|
70
|
+
| `rr[name]` | `name: str` | `RemoteName` (lazy) | Reference a remote symbol |
|
|
71
|
+
| `rr[name] = value` | `name: str`, `value: simple/Remote` | – | Assign remotely |
|
|
72
|
+
| `eval` | `code: str` | `RemoteObject` | Evaluate R code |
|
|
73
|
+
| `exec` | `code: str` | – | Execute R code (no return value) |
|
|
74
|
+
| `call` | `f: Remote`, `*args`, `**kwargs` | `RemoteObject` | Call a remote function |
|
|
75
|
+
|
|
76
|
+
### RemoteObject vs RemoteName
|
|
77
|
+
|
|
78
|
+
* **RemoteObject**
|
|
79
|
+
A concrete object that exists in the remote R environment.
|
|
80
|
+
Automatically cleaned up when the Python object is deleted.
|
|
81
|
+
|
|
82
|
+
* **RemoteName**
|
|
83
|
+
A lazy reference to a symbol or expression in R.
|
|
84
|
+
It may or may not exist until evaluated.
|
|
85
|
+
|
|
86
|
+
Example:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
rr["x"] = 10
|
|
90
|
+
result = rr["x"].get() # 10
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Data Exchange
|
|
96
|
+
|
|
97
|
+
DataFrames are transferred using Apache Arrow files for efficiency.
|
|
98
|
+
|
|
99
|
+
You can request a specific backend when retrieving:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
df = iris_r.get("pandas")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Future backends (e.g., polars) may be supported.
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Important Notes
|
|
110
|
+
|
|
111
|
+
⚠ **Do not print to stdout from R.**
|
|
112
|
+
|
|
113
|
+
Polyester uses `stdout` for protocol communication.
|
|
114
|
+
Printing to `stdout()` inside R will corrupt the communication channel.
|
|
115
|
+
|
|
116
|
+
If you need logging inside R, use:
|
|
117
|
+
|
|
118
|
+
```r
|
|
119
|
+
message("debug info")
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
or write to `stderr()`.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Why Not Use rpy2?
|
|
127
|
+
|
|
128
|
+
rpy2 is a mature and powerful solution.
|
|
129
|
+
|
|
130
|
+
However:
|
|
131
|
+
|
|
132
|
+
* rpy2 is currently difficult to use on Windows in many environments.
|
|
133
|
+
* Polyester runs R as a subprocess and avoids tight binary coupling.
|
|
134
|
+
* The architecture is language-agnostic and may support additional languages (e.g., Julia) in the future.
|
|
135
|
+
|
|
136
|
+
If rpy2 becomes reliably usable in all target environments, Polyester may optionally integrate with it.
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Design Goals
|
|
141
|
+
|
|
142
|
+
* ✅ Windows support
|
|
143
|
+
* ✅ Minimal external dependencies
|
|
144
|
+
* ✅ Simple, explicit API
|
|
145
|
+
* ✅ Subprocess isolation
|
|
146
|
+
* 🔄 Possible future multi-language support
|
|
147
|
+
|
|
148
|
+
Performance is important, but clarity and robustness are higher priorities at this stage.
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## Implementation Details
|
|
153
|
+
|
|
154
|
+
* R is started as a background subprocess.
|
|
155
|
+
* Communication happens over JSON Lines.
|
|
156
|
+
* DataFrames are exchanged via Apache Arrow files.
|
|
157
|
+
* Remote objects are reference-tracked and cleaned up automatically.
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Status
|
|
162
|
+
|
|
163
|
+
### Completed
|
|
164
|
+
|
|
165
|
+
* [x] Start R subprocess in background
|
|
166
|
+
* [x] JSON Lines protocol for communication
|
|
167
|
+
* [x] DataFrame transfer using Apache Arrow
|
|
168
|
+
* [x] Remote object lifecycle management
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
polyester/__init__.py,sha256=u-RR1sFIEZLOrZkl-I9vKNIxIv0kC0sy3GPYx5NLhaI,84
|
|
2
|
+
polyester/channels.py,sha256=jC69auxBlLn3Yk95LlCfz4tNvMKpNY_RhQxnjKzS_P8,581
|
|
3
|
+
polyester/interpreter.py,sha256=yEBr8iIcj5Nz_Ghlnenr-iMvBv16jDlCi8OZDt4docM,4588
|
|
4
|
+
polyester/pyinterpreter.py,sha256=9yI84QhFBYo3pe7NISHQjX3F9U4grdzbF6eYPBurNZg,860
|
|
5
|
+
polyester/rinterpreter.py,sha256=5Gfu5p1F2nw89VuA-Z6Zt7hGE4w3QwENwXH5BBbEnuw,1583
|
|
6
|
+
polyester/utils.py,sha256=N0wcVahpcjFLwX6VetzshWTndkZvRhKvLOf1ECxNQPE,543
|
|
7
|
+
polyester/workers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
polyester/workers/pyworker.py,sha256=lXgkepn4SAewgiagB4IiyCHPBp4-_Y07oOCoIcOLJho,4781
|
|
9
|
+
polyester-0.1.0.dist-info/licenses/LICENSE,sha256=1jmuthbpQgxB8s2RfGbIHZMMvkGoe_X_nubVX9Qb2iQ,11545
|
|
10
|
+
polyester-0.1.0.dist-info/METADATA,sha256=m8uJs8HM_OR-Nm0-tWwhnw9miRO6-Fy7d29MbPaYZgw,4633
|
|
11
|
+
polyester-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
|
|
12
|
+
polyester-0.1.0.dist-info/top_level.txt,sha256=rZ80qPLrqfWjhwHsuHMJUzuAgrI-VF8gYwGB24vYoec,10
|
|
13
|
+
polyester-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 L.F. Verweijen
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
polyester
|