scout-rig 0.2.6 → 0.2.7
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.
- checksums.yaml +4 -4
- data/.vimproject +31 -13
- data/README.md +27 -4
- data/Rakefile +1 -0
- data/VERSION +1 -1
- data/doc/Improvements.md +396 -0
- data/doc/StartHere.md +95 -0
- data/doc/developer/Architecture.md +232 -0
- data/doc/developer/DataConversionInternals.md +407 -0
- data/doc/developer/DesignPrinciples.md +254 -0
- data/doc/developer/PythonTaskRunnerInternals.md +371 -0
- data/doc/developer/PythonWorkflowInternals.md +539 -0
- data/doc/developer/ScoutPythonInternals.md +504 -0
- data/doc/user/Cookbook.md +337 -0
- data/doc/user/DefiningPythonTasks.md +708 -0
- data/doc/user/DrivingWorkflowsFromPython.md +418 -0
- data/doc/user/IteratingPythonData.md +142 -0
- data/doc/user/PassingDataToPython.md +223 -0
- data/doc/user/PythonEnvironments.md +197 -0
- data/doc/user/RunningPythonFromRuby.md +267 -0
- data/doc/user/ScriptingPython.md +281 -0
- data/doc/user/TestingAndPackaging.md +487 -0
- data/lib/scout/python/script.rb +11 -2
- data/lib/scout/workflow/python/inputs.rb +33 -23
- data/lib/scout/workflow/python/task.rb +219 -22
- data/lib/scout/workflow/python.rb +236 -9
- data/lib/scout-rig/testing/availability.rb +608 -0
- data/python/README.md +51 -0
- data/python/scout/__init__.py +2 -0
- data/python/scout/runner.py +193 -29
- data/python/scout/task_errors.py +6 -0
- data/research/00_scope_and_themes.md +131 -0
- data/research/data-conversion-and-scripting-analysis.md +209 -0
- data/research/design-philosophy-analysis.md +246 -0
- data/research/python-helper-package-analysis.md +272 -0
- data/research/pythonworkflow-analysis.md +199 -0
- data/research/scoutpython-bridge-analysis.md +185 -0
- data/research/synthesis-report.md +109 -0
- data/research/testing-availability-baseline.md +1625 -0
- data/research/testing-availability-final-report.md +500 -0
- data/research/validation-report.md +149 -0
- data/scout-rig.gemspec +35 -5
- data/test/scout/python/test_util.rb +13 -0
- data/test/scout/test_python.rb +10 -0
- data/test/scout/workflow/python/test_task.rb +1119 -1
- data/test/scout-rig/testing/test_availability.rb +495 -0
- data/test/scout-rig/testing/test_test_support.rb +166 -0
- data/test/test_helper.rb +96 -19
- metadata +47 -4
- data/doc/Python.md +0 -482
- data/doc/PythonWorkflow.md +0 -163
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
This document explains the overall architecture of scout-rig, the
|
|
4
|
+
relationships between its subsystems, and how data flows through the
|
|
5
|
+
system.
|
|
6
|
+
|
|
7
|
+
## Audience
|
|
8
|
+
|
|
9
|
+
This page is intended for:
|
|
10
|
+
|
|
11
|
+
- ✓ Framework contributors
|
|
12
|
+
- ✓ Advanced workflow authors who need to understand internal structure
|
|
13
|
+
- ✗ Users looking for usage instructions (see [User Documentation](../user/))
|
|
14
|
+
|
|
15
|
+
## Module map
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
┌─────────────────────────────────────────────────────────────────────┐
|
|
19
|
+
│ Ruby (Scout) Side │
|
|
20
|
+
│ │
|
|
21
|
+
│ ┌─────────────────────────────────────────────────────────────┐ │
|
|
22
|
+
│ │ ScoutPython (lib/scout/python.rb + sub-files) │ │
|
|
23
|
+
│ │ │ │
|
|
24
|
+
│ │ • run / run_simple / run_direct / run_threaded │ │
|
|
25
|
+
│ │ • import helpers │ │
|
|
26
|
+
│ │ • script() subprocess facility │ │
|
|
27
|
+
│ │ • data converters (tsv2df, numpy2ruby, etc.) │ │
|
|
28
|
+
│ │ • iteration (iterate, collect) │ │
|
|
29
|
+
│ │ │ │
|
|
30
|
+
│ │ extends PyCall::Import │ │
|
|
31
|
+
│ └─────────────────────────────────────────────────────────────┘ │
|
|
32
|
+
│ │ │
|
|
33
|
+
│ │ uses │
|
|
34
|
+
│ ▼ │
|
|
35
|
+
│ ┌─────────────────────────────────────────────────────────────┐ │
|
|
36
|
+
│ │ PythonWorkflow (lib/scout/workflow/python.rb + sub-files) │ │
|
|
37
|
+
│ │ │ │
|
|
38
|
+
│ │ • python_task: Python file → Scout task │ │
|
|
39
|
+
│ │ • read_python_metadata: --scout-metadata introspection │ │
|
|
40
|
+
│ │ • build_python_argv: Ruby values → CLI args │ │
|
|
41
|
+
│ │ • type mapping: Python types ↔ Scout types │ │
|
|
42
|
+
│ │ │ │
|
|
43
|
+
│ │ extends Workflow │ │
|
|
44
|
+
│ └─────────────────────────────────────────────────────────────┘ │
|
|
45
|
+
│ │
|
|
46
|
+
└─────────────────────────────────────────────────────────────────────┘
|
|
47
|
+
│ │
|
|
48
|
+
│ subprocess │ CLI (rbbt / rbbt_exec.rb)
|
|
49
|
+
▼ ▼
|
|
50
|
+
┌─────────────────────────────────────────────────────────────────────┐
|
|
51
|
+
│ Python Side │
|
|
52
|
+
│ │
|
|
53
|
+
│ ┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐ │
|
|
54
|
+
│ │ scout │ │ scout.runner │ │ scout.workflow│ │
|
|
55
|
+
│ │ __init__.py │ │ runner.py │ │ workflow.py │ │
|
|
56
|
+
│ │ │ │ │ │ │ │
|
|
57
|
+
│ │ • tsv IO │ │ • scout.task │ │ • Workflow │ │
|
|
58
|
+
│ │ • cmd() │ │ • describe_func │ │ • Step │ │
|
|
59
|
+
│ │ • run_job() │ │ • CLI dispatch │ │ │ │
|
|
60
|
+
│ │ • save_tsv() │ │ • type mapping │ │ + remote.py │ │
|
|
61
|
+
│ │ │ │ │ │ • RemoteWF │ │
|
|
62
|
+
│ └──────────────────┘ └──────────────────┘ └────────────────┘ │
|
|
63
|
+
│ │
|
|
64
|
+
└─────────────────────────────────────────────────────────────────────┘
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Subsystem responsibilities
|
|
68
|
+
|
|
69
|
+
### ScoutPython
|
|
70
|
+
|
|
71
|
+
**Responsibility:** Execute Python code from Ruby.
|
|
72
|
+
|
|
73
|
+
ScoutPython wraps the `pycall` gem with a layered set of execution modes,
|
|
74
|
+
import helpers, and data converters. It is the foundational Ruby↔Python
|
|
75
|
+
bridge.
|
|
76
|
+
|
|
77
|
+
Key files:
|
|
78
|
+
- `lib/scout/python.rb` — Core module, imports, bindings, iteration.
|
|
79
|
+
- `lib/scout/python/run.rb` — Execution modes, threading, GC.
|
|
80
|
+
- `lib/scout/python/script.rb` — ruby2python serialization, script().
|
|
81
|
+
- `lib/scout/python/util.rb` — Data converters.
|
|
82
|
+
- `lib/scout/python/paths.rb` — sys.path management.
|
|
83
|
+
|
|
84
|
+
See [ScoutPython Internals](ScoutPythonInternals.md).
|
|
85
|
+
|
|
86
|
+
### PythonWorkflow
|
|
87
|
+
|
|
88
|
+
**Responsibility:** Define Scout tasks backed by Python functions.
|
|
89
|
+
|
|
90
|
+
PythonWorkflow extends a Scout `Workflow` module with the `python_task`
|
|
91
|
+
method. At definition time, it introspects the Python function's signature
|
|
92
|
+
and docstring to automatically declare Scout inputs and return types. At
|
|
93
|
+
execution time, it invokes the Python function as a subprocess and decodes
|
|
94
|
+
the return value.
|
|
95
|
+
|
|
96
|
+
Key files:
|
|
97
|
+
- `lib/scout/workflow/python.rb` — Module definition, load_directory.
|
|
98
|
+
- `lib/scout/workflow/python/task.rb` — python_task, metadata reading, type mapping.
|
|
99
|
+
- `lib/scout/workflow/python/inputs.rb` — build_python_argv.
|
|
100
|
+
|
|
101
|
+
See [PythonWorkflow Internals](PythonWorkflowInternals.md).
|
|
102
|
+
|
|
103
|
+
### Python `scout` package
|
|
104
|
+
|
|
105
|
+
**Responsibility:** Let Python code drive Scout workflows.
|
|
106
|
+
|
|
107
|
+
The Python `scout` package is the reverse bridge: it lets Python code call
|
|
108
|
+
Scout workflows. It does this by shelling out to the Ruby CLI. It also
|
|
109
|
+
provides TSV I/O, the `scout.task` decorator (which makes Python functions
|
|
110
|
+
discoverable by PythonWorkflow), and a remote workflow client.
|
|
111
|
+
|
|
112
|
+
Key files:
|
|
113
|
+
- `python/scout/__init__.py` — TSV IO, cmd, run_job.
|
|
114
|
+
- `python/scout/runner.py` — scout.task decorator, describe_function, CLI dispatch.
|
|
115
|
+
- `python/scout/workflow.py` — Workflow, Step (local).
|
|
116
|
+
- `python/scout/workflow/remote.py` — RemoteWorkflow, RemoteStep.
|
|
117
|
+
|
|
118
|
+
## Data flow
|
|
119
|
+
|
|
120
|
+
### Ruby → Python (in-process)
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
Ruby value
|
|
124
|
+
│
|
|
125
|
+
├─ ScoutPython.run { pyimport :numpy; numpy.array(ruby_array) }
|
|
126
|
+
│ │
|
|
127
|
+
│ ├─ PyCall converts Ruby Array → Python list
|
|
128
|
+
│ ├─ Python code executes
|
|
129
|
+
│ └─ PyCall proxy returned to Ruby
|
|
130
|
+
│
|
|
131
|
+
└─ ScoutPython.tsv2df(tsv)
|
|
132
|
+
│
|
|
133
|
+
├─ tsv.values, tsv.fields, tsv.keys extracted in Ruby
|
|
134
|
+
├─ pandas.DataFrame.new(values, columns, index)
|
|
135
|
+
└─ PyCall proxy to DataFrame returned
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Ruby → Python (subprocess via script())
|
|
139
|
+
|
|
140
|
+
```
|
|
141
|
+
Ruby variables
|
|
142
|
+
│
|
|
143
|
+
├─ ruby2python() serializes each to Python literal
|
|
144
|
+
│ ├─ Array → [1, 2, 3]
|
|
145
|
+
│ ├─ TSV → temp file + scout.tsv(filepath)
|
|
146
|
+
│ └─ Hash → {key: value, ...}
|
|
147
|
+
│
|
|
148
|
+
├─ script text + assignments + "save result" snippet
|
|
149
|
+
│
|
|
150
|
+
├─ CMD.cmd_log("python script.py")
|
|
151
|
+
│ └─ new Python process
|
|
152
|
+
│
|
|
153
|
+
└─ result loaded from temp file (pickle or JSON)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Python → Ruby (CLI-based)
|
|
157
|
+
|
|
158
|
+
```
|
|
159
|
+
Python code
|
|
160
|
+
│
|
|
161
|
+
├─ scout.cmd(ruby_code)
|
|
162
|
+
│ ├─ subprocess.run('rbbt_exec.rb', input=...)
|
|
163
|
+
│ └─ stdout returned as string
|
|
164
|
+
│
|
|
165
|
+
├─ scout.Workflow(name).run(task, **inputs)
|
|
166
|
+
│ ├─ save_job_inputs() writes inputs to files
|
|
167
|
+
│ ├─ subprocess.run(['rbbt', 'workflow', 'task', ...])
|
|
168
|
+
│ └─ stdout = result
|
|
169
|
+
│
|
|
170
|
+
└─ RemoteWorkflow(url).job(task, **inputs)
|
|
171
|
+
├─ POST url/task with inputs
|
|
172
|
+
└─ GET url/info, url/result
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Dependencies
|
|
176
|
+
|
|
177
|
+
### External (Ruby gems)
|
|
178
|
+
|
|
179
|
+
- `pycall` — The Ruby↔Python bridge library.
|
|
180
|
+
- `python/pickle` — Ruby pickle parser, used by script() result loading.
|
|
181
|
+
- `scout-essentials` — Foundation: TSV, CMD, Log, Path, TmpFile, etc.
|
|
182
|
+
|
|
183
|
+
### External (Python packages)
|
|
184
|
+
|
|
185
|
+
- `numpy` — Required for numpy2ruby and array conversions.
|
|
186
|
+
- `pandas` — Required for TSV↔DataFrame conversion and TSV I/O.
|
|
187
|
+
- `requests` — Optional, for remote workflow client.
|
|
188
|
+
- `torch` — Not required by the library. It is an *optional test
|
|
189
|
+
prerequisite*: `test_binding` in `test/scout/test_python.rb` needs it and
|
|
190
|
+
is gated with the availability helpers (`omit` +
|
|
191
|
+
`ScoutRig::Testing::Availability.python_modules?('torch', route:
|
|
192
|
+
:embedded)`), so its absence omits the test instead of erroring. `numpy`
|
|
193
|
+
is likewise optional for the tests that use it. Neither is required by any
|
|
194
|
+
production code. See
|
|
195
|
+
[Testing and Packaging](../user/TestingAndPackaging.md).
|
|
196
|
+
|
|
197
|
+
### Internal dependencies (Ruby → Ruby)
|
|
198
|
+
|
|
199
|
+
```
|
|
200
|
+
PythonWorkflow → ScoutPython (for run_file)
|
|
201
|
+
PythonWorkflow → Workflow (extends)
|
|
202
|
+
ScoutPython → PyCall (wraps)
|
|
203
|
+
ScoutPython → CMD, Log, TSV, TmpFile (from scout-essentials)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### Internal dependencies (Python → Ruby CLI)
|
|
207
|
+
|
|
208
|
+
```
|
|
209
|
+
scout.__init__ → rbbt_exec.rb (via cmd())
|
|
210
|
+
scout.workflow → rbbt (via run_job())
|
|
211
|
+
scout.runner → (standalone, run as script)
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## Codebase statistics
|
|
215
|
+
|
|
216
|
+
| Language | Files | Lines (approx) |
|
|
217
|
+
|----------|-------|----------------|
|
|
218
|
+
| Ruby | 8 | 705 |
|
|
219
|
+
| Python | 4 | 934 |
|
|
220
|
+
| Total | 12 | 1,639 |
|
|
221
|
+
|
|
222
|
+
The codebase is intentionally compact. Each file has a single,
|
|
223
|
+
well-defined responsibility. For deeper understanding of any subsystem,
|
|
224
|
+
refer to the [research artifacts](../../research/).
|
|
225
|
+
|
|
226
|
+
## See also
|
|
227
|
+
|
|
228
|
+
- [ScoutPython Internals](ScoutPythonInternals.md)
|
|
229
|
+
- [PythonWorkflow Internals](PythonWorkflowInternals.md)
|
|
230
|
+
- [Data Conversion Internals](DataConversionInternals.md)
|
|
231
|
+
- [Design Principles](DesignPrinciples.md)
|
|
232
|
+
- [Scout-essentials architecture](https://github.com/mikisvaz/scout-essentials/blob/main/doc/developer/Architecture.md)
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
# Data Conversion Internals
|
|
2
|
+
|
|
3
|
+
This document explains how scout-rig converts data between Ruby and Python,
|
|
4
|
+
both in-process (via PyCall) and across process boundaries (via serialization).
|
|
5
|
+
|
|
6
|
+
## Audience
|
|
7
|
+
|
|
8
|
+
This page is intended for:
|
|
9
|
+
|
|
10
|
+
- ✓ Framework contributors
|
|
11
|
+
- ✗ Workflow authors (see [Passing Data to Python](../user/PassingDataToPython.md) and [Scripting Python](../user/ScriptingPython.md))
|
|
12
|
+
|
|
13
|
+
## Why this exists
|
|
14
|
+
|
|
15
|
+
Ruby and Python have different object models. PyCall provides live object
|
|
16
|
+
proxies, but proxy objects can't be iterated, indexed, or manipulated with
|
|
17
|
+
standard Ruby methods. For cross-process communication (`script()` and
|
|
18
|
+
`python_task`), data must be serialized to files.
|
|
19
|
+
|
|
20
|
+
Scout-rig provides two conversion layers:
|
|
21
|
+
|
|
22
|
+
1. **In-process converters** — For use inside `run` blocks where PyCall
|
|
23
|
+
objects are live.
|
|
24
|
+
2. **ruby2python serializer** — For `script()` where Ruby variables must
|
|
25
|
+
become Python literals (and TSVs become temp files), plus a pickle/JSON
|
|
26
|
+
result file read back on the Ruby side.
|
|
27
|
+
|
|
28
|
+
## In-process converters
|
|
29
|
+
|
|
30
|
+
These methods convert PyCall proxy objects to native Ruby types.
|
|
31
|
+
|
|
32
|
+
### numpy2ruby
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
def self.numpy2ruby(numpy)
|
|
36
|
+
list2ruby(numpy.tolist)
|
|
37
|
+
end
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Calls `.tolist` on the numpy array (Python-side conversion to nested lists)
|
|
41
|
+
and recursively converts the result. Because it goes through `list2ruby`,
|
|
42
|
+
the result is a genuinely nested Ruby `Array` — but the elements inside are
|
|
43
|
+
whatever PyCall yields:
|
|
44
|
+
|
|
45
|
+
| numpy dtype | `numpy2ruby` result |
|
|
46
|
+
|-------------|---------------------|
|
|
47
|
+
| `int64` (2D) | `[[1, 2], [3, 4]]` |
|
|
48
|
+
| `float64` with `NaN` | `[1.0, NaN]` (Ruby `Float::NAN`) |
|
|
49
|
+
| `bool` | `[true, false]` |
|
|
50
|
+
| `<U1` strings | `["x", "y"]` |
|
|
51
|
+
| `object` mixed (`1`, `"a"`) | `["1", "a"]` — PyCall stringifies mixed-object elements |
|
|
52
|
+
| `datetime64[D]` | opaque objects inspecting as `datetime.date(2020, 1, 1)` |
|
|
53
|
+
|
|
54
|
+
### py2ruby_a
|
|
55
|
+
|
|
56
|
+
```ruby
|
|
57
|
+
def self.py2ruby_a(array)
|
|
58
|
+
PyCall::List.(array).to_a
|
|
59
|
+
end
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Converts a Python list to a Ruby array **one level deep**. Nested members
|
|
63
|
+
stay as PyCall proxies (they compare equal to the equivalent Ruby array but
|
|
64
|
+
are not `Array`s), so use `list2ruby` for nested data. `to_a` is aliased
|
|
65
|
+
to this method.
|
|
66
|
+
|
|
67
|
+
### list2ruby
|
|
68
|
+
|
|
69
|
+
```ruby
|
|
70
|
+
def self.list2ruby(list)
|
|
71
|
+
return list unless PyCall::List === list
|
|
72
|
+
list.collect do |e|
|
|
73
|
+
list2ruby(e)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Recursive conversion: every `PyCall::List` member is converted again,
|
|
79
|
+
everything else is returned unchanged (including other PyCall proxies such
|
|
80
|
+
as tuples or dicts nested inside the list).
|
|
81
|
+
|
|
82
|
+
### obj2hash / dict2hash
|
|
83
|
+
|
|
84
|
+
```ruby
|
|
85
|
+
def self.obj2hash(obj)
|
|
86
|
+
hash = {}
|
|
87
|
+
ScoutPython.iterate obj.keys do |k|
|
|
88
|
+
hash[k] = obj[k]
|
|
89
|
+
end
|
|
90
|
+
hash
|
|
91
|
+
end
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Iterates `obj.keys` and builds a Ruby hash. Values are **not** converted:
|
|
95
|
+
on a DataFrame `h["x"]` is the live pandas `Series` proxy, so convert it
|
|
96
|
+
yourself or use `df2tsv`.
|
|
97
|
+
|
|
98
|
+
```ruby
|
|
99
|
+
def self.dict2hash(obj)
|
|
100
|
+
keys = py2ruby_a(obj.keys)
|
|
101
|
+
hash = {}
|
|
102
|
+
keys.each do |k|
|
|
103
|
+
hash[k] = obj.get(k)
|
|
104
|
+
end
|
|
105
|
+
hash
|
|
106
|
+
end
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Reads values with `obj.get(k)`, so it is intended for real `dict`s; it
|
|
110
|
+
returns eagerly converted values (`{"x" => 1}`). Calling it on a DataFrame
|
|
111
|
+
does not fail loudly — `get` resolves to something else and the value is
|
|
112
|
+
the Series proxy anyway — so it is not a route to converted DataFrame
|
|
113
|
+
columns.
|
|
114
|
+
|
|
115
|
+
### tsv2df / df2tsv
|
|
116
|
+
|
|
117
|
+
The implementation is significantly different from what earlier drafts of
|
|
118
|
+
this page described; the code below is the real code.
|
|
119
|
+
|
|
120
|
+
```ruby
|
|
121
|
+
def self.tsv2df(tsv)
|
|
122
|
+
df = nil
|
|
123
|
+
ScoutPython.run_direct 'pandas' do
|
|
124
|
+
df = pandas.DataFrame.new(tsv.values, columns: tsv.fields, index: tsv.keys)
|
|
125
|
+
df.columns.name = tsv.key_field
|
|
126
|
+
end
|
|
127
|
+
df
|
|
128
|
+
end
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Builds a pandas DataFrame from TSV values, fields and keys, and records the
|
|
132
|
+
key field as the **column** axis name (`df.columns.name`), not
|
|
133
|
+
`df.index.name`. `tsv.values` is passed as the data argument, which PyCall
|
|
134
|
+
converts to a Python list-of-lists. Because the data is built in-process,
|
|
135
|
+
no pandas inference happens: a `:list` TSV of strings yields an `object`
|
|
136
|
+
column of exactly those strings (including `"NA"` and `"1.5"`).
|
|
137
|
+
|
|
138
|
+
```ruby
|
|
139
|
+
def self.df2tsv(tuple, options = {})
|
|
140
|
+
options = IndiferentHash.add_defaults options, :type => :list
|
|
141
|
+
IndiferentHash.setup options
|
|
142
|
+
tsv = TSV.setup({}, options)
|
|
143
|
+
tsv.key_field = options[:key_field] || tuple.columns.name.to_s
|
|
144
|
+
tsv.fields = py2ruby_a(tuple.columns.values)
|
|
145
|
+
keys = py2ruby_a(tuple.index.values)
|
|
146
|
+
PyCall.len(tuple.index).times do |i|
|
|
147
|
+
k = keys[i]
|
|
148
|
+
tsv[k] = py2ruby_a(tuple.values[i])
|
|
149
|
+
end
|
|
150
|
+
tsv
|
|
151
|
+
end
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The reverse. Notes:
|
|
155
|
+
|
|
156
|
+
- The result is always `type: :list` (overridable with `options[:type]`),
|
|
157
|
+
and `key_field` falls back to `tuple.columns.name.to_s` — which is why
|
|
158
|
+
`tsv2df` setting `columns.name` (not `index.name`) matters for
|
|
159
|
+
round-tripping the key field name.
|
|
160
|
+
- Values are read row-wise with `tuple.values[i]` and converted **flat**
|
|
161
|
+
with `py2ruby_a`; for a DataFrame the row is a numpy array, and this
|
|
162
|
+
works because `py2ruby_a` handles array-likes whose elements are scalars.
|
|
163
|
+
- A `tsv2df` → `df2tsv` round-trip on a well-formed `:list` TSV preserves
|
|
164
|
+
keys, fields, key field name, type and values (verified for values
|
|
165
|
+
containing `;`, `,`, quotes and `":NA"`). It does **not** preserve
|
|
166
|
+
`:double`/`:flat` types (everything becomes `:list`) and it cannot
|
|
167
|
+
preserve values that pandas had already coerced (e.g. a DataFrame read
|
|
168
|
+
from a file by `scout.tsv()`, where `"NA"` is already `NaN`).
|
|
169
|
+
|
|
170
|
+
## ruby2python serializer (for script())
|
|
171
|
+
|
|
172
|
+
The `ruby2python` method serializes Ruby values to Python literal strings:
|
|
173
|
+
|
|
174
|
+
```ruby
|
|
175
|
+
def self.ruby2python(object)
|
|
176
|
+
case object
|
|
177
|
+
when Float::INFINITY
|
|
178
|
+
"inf"
|
|
179
|
+
when nil
|
|
180
|
+
"None"
|
|
181
|
+
when ":NA"
|
|
182
|
+
"None"
|
|
183
|
+
when Symbol
|
|
184
|
+
"#{ object }"
|
|
185
|
+
when String
|
|
186
|
+
object = object.dup if Path === object
|
|
187
|
+
object[0] == ":" ? object[1..-1] : "'#{ object }'"
|
|
188
|
+
when Numeric
|
|
189
|
+
object
|
|
190
|
+
when TrueClass
|
|
191
|
+
"True"
|
|
192
|
+
when FalseClass
|
|
193
|
+
"False"
|
|
194
|
+
when Array
|
|
195
|
+
"[#{object.collect{|e| ruby2python(e) } * ", "}]"
|
|
196
|
+
when Hash
|
|
197
|
+
"{" << object.collect{|k,v| [ruby2python(k.to_s), ruby2python(v)] * ":"} * ", " << "}"
|
|
198
|
+
else
|
|
199
|
+
raise "Type of object not known: #{ object.inspect }"
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Divergences from a "safe" serializer, all verified by probe:
|
|
205
|
+
|
|
206
|
+
- Strings are emitted inside **single quotes with no escaping**, so `"it's"`
|
|
207
|
+
and strings containing newlines produce invalid Python. Double quotes,
|
|
208
|
+
backslashes, tabs and non-ASCII round-trip.
|
|
209
|
+
- A leading `":"` in a `String` **strips the colon** (`":abc"` → the bare
|
|
210
|
+
name `abc`), and the exact string `":NA"` maps to `None`.
|
|
211
|
+
- `Symbol`s are emitted **unquoted**, so they must be valid Python
|
|
212
|
+
identifiers; `:d-f` emits `d-f` and the subprocess fails.
|
|
213
|
+
- `Float::INFINITY` emits the name `inf`, which is undefined unless the
|
|
214
|
+
script imports it.
|
|
215
|
+
- `Hash` keys are coerced with `k.to_s` (so `1` → `"1"`, arrays/booleans →
|
|
216
|
+
their `to_s`) and are then subject to the same leading-colon stripping.
|
|
217
|
+
- `Numeric` (including `Integer`) is interpolated via `to_s`, not quoted.
|
|
218
|
+
- Unknown classes raise `Type of object not known: ...`; a `Path` is dup'd
|
|
219
|
+
into a plain `String` first and serialized as a quoted literal.
|
|
220
|
+
|
|
221
|
+
### TSV handling in ruby2python
|
|
222
|
+
|
|
223
|
+
When a TSV is passed to `script()`, it doesn't become a Python literal.
|
|
224
|
+
Instead (`load_script_variables`, not `ruby2python` itself):
|
|
225
|
+
|
|
226
|
+
1. The TSV is dumped to a temp file with `Open.write(tmp_file, value.to_s)`,
|
|
227
|
+
where `tmp_file` comes from `TmpFile.tmp_file` (a `tmp-<random>` name in
|
|
228
|
+
Scout's tmp dir). Note this is a raw `to_s` dump, **not** an escaped dump.
|
|
229
|
+
2. A Python assignment is generated: `df = scout.tsv('<tmp_file>')` — the
|
|
230
|
+
path is interpolated into a single-quoted literal.
|
|
231
|
+
3. The Python `scout.tsv()` function (`pandas.read_table`) reads the file
|
|
232
|
+
into a pandas DataFrame.
|
|
233
|
+
|
|
234
|
+
This avoids embedding large datasets as inline Python literals. Because
|
|
235
|
+
step 3 goes through `read_table`, the DataFrame the script sees carries
|
|
236
|
+
pandas' own inference (`NA`/`""`/`nan`/`None` → `NaN`, numeric-looking
|
|
237
|
+
columns → `float64`), unlike the in-process `tsv2df` which preserves the
|
|
238
|
+
Ruby strings as an `object` column.
|
|
239
|
+
|
|
240
|
+
### script() assembly
|
|
241
|
+
|
|
242
|
+
The actual implementation (simplified only by eliding the no-variable
|
|
243
|
+
branch, which skips the preamble):
|
|
244
|
+
|
|
245
|
+
```ruby
|
|
246
|
+
def self.script(text, variables = {})
|
|
247
|
+
if variables.any?
|
|
248
|
+
variable_definitions, tmp_files = load_script_variables(variables)
|
|
249
|
+
text = variable_definitions + "\n" + text
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
tmp_file = TmpFile.tmp_file
|
|
253
|
+
path_env = ScoutPython.paths * ":"
|
|
254
|
+
|
|
255
|
+
CMD.cmd_log("env PYTHONPATH=#{path_env} python", {in: text})
|
|
256
|
+
|
|
257
|
+
tmp_files.each{|file| Open.rm_rf file } if tmp_files
|
|
258
|
+
if Open.exists?(tmp_file)
|
|
259
|
+
load_result(tmp_file)
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Points the previous documentation got wrong or omitted:
|
|
265
|
+
|
|
266
|
+
- The program is **not written to a `.py` file**. It is piped on **stdin**
|
|
267
|
+
to `env PYTHONPATH=<ScoutPython.paths joined by ':'> python` via
|
|
268
|
+
`CMD.cmd_log`, so no script file appears in the tmp dir and the assembled
|
|
269
|
+
text never needs a filename-safe encoding.
|
|
270
|
+
- `CMD.cmd_log` (as opposed to `CMD.cmd`) does not return output; it logs
|
|
271
|
+
the subprocess stdout to the Scout log and raises
|
|
272
|
+
`ConcurrentStreamProcessFailed` when the process exits non-zero. That
|
|
273
|
+
exception is the only failure signal `script()` surfaces.
|
|
274
|
+
- The variable preamble (`# Variables\nimport scout\n` plus one
|
|
275
|
+
assignment per variable) is prepended to the user text; `import scout`
|
|
276
|
+
is always present, which is why `scout.tsv` is available even in scripts
|
|
277
|
+
that never import anything themselves.
|
|
278
|
+
- The result file path (`tmp_file`) is **generated but never deleted**;
|
|
279
|
+
the TSV variable dumps (`tmp_files`) are deleted right after
|
|
280
|
+
`cmd_log` returns, on success or failure, because the `each` sits after
|
|
281
|
+
the call rather than in an `ensure`.
|
|
282
|
+
- `load_result(tmp_file)` is only reached when the result file exists; a
|
|
283
|
+
script that never sets `result` (or sets it to `None`) therefore returns
|
|
284
|
+
Ruby `nil` silently.
|
|
285
|
+
|
|
286
|
+
## Result persistence
|
|
287
|
+
|
|
288
|
+
### save_script_result_pickle
|
|
289
|
+
|
|
290
|
+
`save_script_result_pickle` (aliased as `save_script_result`) generates the
|
|
291
|
+
snippet appended to every script. The real text is:
|
|
292
|
+
|
|
293
|
+
```python
|
|
294
|
+
# Save
|
|
295
|
+
try: result
|
|
296
|
+
except NameError: result = None
|
|
297
|
+
if result is not None:
|
|
298
|
+
import pickle
|
|
299
|
+
file = open('<result_file>', 'wb')
|
|
300
|
+
pickle.dump(result, file)
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Three consequences:
|
|
304
|
+
|
|
305
|
+
- An undefined `result` is **absorbed** (`except NameError: result = None`),
|
|
306
|
+
so a script that forgets to set `result` runs to completion and
|
|
307
|
+
`script()` returns `nil`.
|
|
308
|
+
- `result = None` writes nothing, for the same reason: the file is only
|
|
309
|
+
created when `result is not None`. It is therefore impossible to
|
|
310
|
+
distinguish "returned None" from "returned nothing".
|
|
311
|
+
- The default protocol is whatever the running Python chooses
|
|
312
|
+
(`pickle.DEFAULT_PROTOCOL`); on Python 3.13 that is protocol 4.
|
|
313
|
+
|
|
314
|
+
`save_script_result_json` emits the same `try/except NameError` and
|
|
315
|
+
`if result is not None` guard and then writes
|
|
316
|
+
`file.write(json.dumps(result))` — so with the JSON backend a missing
|
|
317
|
+
`result` also yields `nil`, and a `None` result writes nothing (not
|
|
318
|
+
`null`).
|
|
319
|
+
|
|
320
|
+
### load_result / load_pickle
|
|
321
|
+
|
|
322
|
+
`load_result` (aliased to `load_pickle`) reads the file with the
|
|
323
|
+
`python/pickle` gem. The aliases can be re-pointed to the JSON variants:
|
|
324
|
+
|
|
325
|
+
```ruby
|
|
326
|
+
class << ScoutPython
|
|
327
|
+
alias save_script_result save_script_result_json
|
|
328
|
+
alias load_result load_json
|
|
329
|
+
end
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### Pickle protocol limitations
|
|
333
|
+
|
|
334
|
+
The `python/pickle` gem (0.2.0) does not implement every opcode of the
|
|
335
|
+
default protocol. Empirically, on the installed Python 3.13:
|
|
336
|
+
|
|
337
|
+
- Integers outside `0..255` fail. `pickle.dumps(256)` uses `BININT2`
|
|
338
|
+
(opcode `M`, 0x4D) and `pickle.dumps(-1)`/`70000` use `BININT` (opcode
|
|
339
|
+
`J`, 0x4A); the gem's protocol-4 reader only handles `BININT1` (`K`,
|
|
340
|
+
0x4B), so `Python::Pickle::InvalidFormat: invalid opcode (74)` (and 77)
|
|
341
|
+
is raised for any integer that does not fit in one unsigned byte.
|
|
342
|
+
- `dict` values pickled with `NEWOBJ` (e.g. numpy scalars such as
|
|
343
|
+
`np.float64`) come back as raw `Python::Pickle::PyObject` wrappers with
|
|
344
|
+
no conversion to a Ruby number.
|
|
345
|
+
- `datetime.date` similarly yields an opaque `PyObject` describing the
|
|
346
|
+
`datetime.date` constructor rather than a Ruby `Date`.
|
|
347
|
+
|
|
348
|
+
Strings, bools, small integers, `inf`/`NaN` floats, lists, dicts, tuples
|
|
349
|
+
and bytes round-trip; bytes decode to their ASCII contents.
|
|
350
|
+
|
|
351
|
+
**Practical rule:** if the result is not a plain scalar/list/dict of basic
|
|
352
|
+
types, prefer the JSON backend, or convert to basic types inside the script
|
|
353
|
+
(`int(x)`, `x.item()`, `str(x)`).
|
|
354
|
+
|
|
355
|
+
## Serialization format summary
|
|
356
|
+
|
|
357
|
+
| Context | Direction | Mechanism |
|
|
358
|
+
|---------|-----------|-----------|
|
|
359
|
+
| `run` block | Ruby → Python | PyCall auto-conversion |
|
|
360
|
+
| `run` block | Python → Ruby | py2ruby_a, numpy2ruby, obj2hash |
|
|
361
|
+
| `script()` scalar | Ruby → Python | Literal string (ruby2python) |
|
|
362
|
+
| `script()` TSV | Ruby → Python | Temp file + scout.tsv() |
|
|
363
|
+
| `script()` result | Python → Ruby | Pickle file or JSON file |
|
|
364
|
+
| `python_task` inputs | Ruby → Python | CLI arguments |
|
|
365
|
+
| `python_task` result | Python → Ruby | stdout (JSON/array/string) |
|
|
366
|
+
|
|
367
|
+
The `python_task` row is described in
|
|
368
|
+
[PythonWorkflow Internals](PythonWorkflowInternals.md); its decoding is
|
|
369
|
+
`JSON.parse(txt)` first, then a newline split for array returns, then the
|
|
370
|
+
raw string — which is where the A2 ambiguity (a string return that is
|
|
371
|
+
itself valid JSON being decoded as a structure) lives.
|
|
372
|
+
|
|
373
|
+
## Key design decisions
|
|
374
|
+
|
|
375
|
+
1. **PyCall proxies are opaque** — Rather than trying to make PyCall proxy
|
|
376
|
+
objects behave like native Ruby objects, scout-rig provides explicit
|
|
377
|
+
converters. This is clearer and avoids surprising behavior.
|
|
378
|
+
|
|
379
|
+
2. **TSV ↔ DataFrame is the primary cross-language data type** — Scout's
|
|
380
|
+
TSV and Python's pandas DataFrame are natural equivalents. The
|
|
381
|
+
converters are bidirectional, but "lossless" needs qualification:
|
|
382
|
+
the in-process pair `tsv2df`/`df2tsv` round-trips a well-formed
|
|
383
|
+
`:list` TSV exactly (values including `;`, `,`, quotes and `":NA"`),
|
|
384
|
+
while the `script()` file path necessarily passes through pandas'
|
|
385
|
+
NA and dtype inference and therefore is not lossless for `"NA"`,
|
|
386
|
+
empty strings, or numeric-looking strings.
|
|
387
|
+
|
|
388
|
+
3. **Files as serialization boundary** — For subprocess communication,
|
|
389
|
+
data goes through files. This is the Unix philosophy: files as the
|
|
390
|
+
universal interface.
|
|
391
|
+
|
|
392
|
+
4. **Pickle by default, JSON optional** — Pickle handles all Python objects
|
|
393
|
+
on the writing side, but the `python/pickle` Ruby gem reading it back is
|
|
394
|
+
far less capable than CPython (see "Pickle protocol limitations" above);
|
|
395
|
+
integers outside `0..255` already fail. JSON is simpler and, for basic
|
|
396
|
+
types, the more reliable direction on this gem version.
|
|
397
|
+
|
|
398
|
+
5. **No auto-conversion of PyCall objects** — Users must explicitly call
|
|
399
|
+
`py2ruby_a`, `numpy2ruby`, or `obj2hash`. This prevents accidental
|
|
400
|
+
conversion overhead.
|
|
401
|
+
|
|
402
|
+
## See also
|
|
403
|
+
|
|
404
|
+
- [ScoutPython Internals](ScoutPythonInternals.md) — The execution modes.
|
|
405
|
+
- [PythonWorkflow Internals](PythonWorkflowInternals.md) — CLI-based data flow.
|
|
406
|
+
- [Passing Data to Python](../user/PassingDataToPython.md) — User-facing guide.
|
|
407
|
+
- [Scripting Python](../user/ScriptingPython.md) — User-facing guide.
|