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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +31 -13
  3. data/README.md +27 -4
  4. data/Rakefile +1 -0
  5. data/VERSION +1 -1
  6. data/doc/Improvements.md +396 -0
  7. data/doc/StartHere.md +95 -0
  8. data/doc/developer/Architecture.md +232 -0
  9. data/doc/developer/DataConversionInternals.md +407 -0
  10. data/doc/developer/DesignPrinciples.md +254 -0
  11. data/doc/developer/PythonTaskRunnerInternals.md +371 -0
  12. data/doc/developer/PythonWorkflowInternals.md +539 -0
  13. data/doc/developer/ScoutPythonInternals.md +504 -0
  14. data/doc/user/Cookbook.md +337 -0
  15. data/doc/user/DefiningPythonTasks.md +708 -0
  16. data/doc/user/DrivingWorkflowsFromPython.md +418 -0
  17. data/doc/user/IteratingPythonData.md +142 -0
  18. data/doc/user/PassingDataToPython.md +223 -0
  19. data/doc/user/PythonEnvironments.md +197 -0
  20. data/doc/user/RunningPythonFromRuby.md +267 -0
  21. data/doc/user/ScriptingPython.md +281 -0
  22. data/doc/user/TestingAndPackaging.md +487 -0
  23. data/lib/scout/python/script.rb +11 -2
  24. data/lib/scout/workflow/python/inputs.rb +33 -23
  25. data/lib/scout/workflow/python/task.rb +219 -22
  26. data/lib/scout/workflow/python.rb +236 -9
  27. data/lib/scout-rig/testing/availability.rb +608 -0
  28. data/python/README.md +51 -0
  29. data/python/scout/__init__.py +2 -0
  30. data/python/scout/runner.py +193 -29
  31. data/python/scout/task_errors.py +6 -0
  32. data/research/00_scope_and_themes.md +131 -0
  33. data/research/data-conversion-and-scripting-analysis.md +209 -0
  34. data/research/design-philosophy-analysis.md +246 -0
  35. data/research/python-helper-package-analysis.md +272 -0
  36. data/research/pythonworkflow-analysis.md +199 -0
  37. data/research/scoutpython-bridge-analysis.md +185 -0
  38. data/research/synthesis-report.md +109 -0
  39. data/research/testing-availability-baseline.md +1625 -0
  40. data/research/testing-availability-final-report.md +500 -0
  41. data/research/validation-report.md +149 -0
  42. data/scout-rig.gemspec +35 -5
  43. data/test/scout/python/test_util.rb +13 -0
  44. data/test/scout/test_python.rb +10 -0
  45. data/test/scout/workflow/python/test_task.rb +1119 -1
  46. data/test/scout-rig/testing/test_availability.rb +495 -0
  47. data/test/scout-rig/testing/test_test_support.rb +166 -0
  48. data/test/test_helper.rb +96 -19
  49. metadata +47 -4
  50. data/doc/Python.md +0 -482
  51. data/doc/PythonWorkflow.md +0 -163
@@ -0,0 +1,223 @@
1
+ # Passing Data to Python
2
+
3
+ This document explains how to convert Ruby data structures to Python and
4
+ back, so you can pass data between the two languages efficiently.
5
+
6
+ ## Audience
7
+
8
+ This page is intended for:
9
+
10
+ - ✓ Workflow authors passing data between Ruby and Python
11
+ - ✓ Agent developers building cross-language tools
12
+ - ✗ Framework contributors (see [Data Conversion Internals](../developer/DataConversionInternals.md))
13
+
14
+ ## When to use this
15
+
16
+ Use the data conversion helpers when you need to:
17
+
18
+ - Pass a Ruby TSV to Python as a pandas DataFrame.
19
+ - Get a Python numpy array back as a Ruby array.
20
+ - Convert Python dicts/lists to Ruby hashes/arrays.
21
+ - Read Python computation results into Ruby data structures.
22
+
23
+ ## Core concepts
24
+
25
+ ScoutPython provides two categories of converters:
26
+
27
+ 1. **In-process converters** — Used inside `run` blocks where PyCall keeps
28
+ Ruby and Python objects alive in the same process. Fast, no serialization.
29
+
30
+ 2. **Serialization for `script()`** — Used when passing Ruby variables into
31
+ a Python subprocess via `script()`. Slower (involves file I/O) but works
32
+ across process boundaries.
33
+
34
+ ## TSV ↔ pandas DataFrame
35
+
36
+ ### TSV to DataFrame
37
+
38
+ ```ruby
39
+ tsv = TSV.setup([], key_field: "Gene", fields: %w(LogFoldChange PValue), type: :list)
40
+ tsv["BRCA1"] = [2.5, 0.001]
41
+ tsv["TP53"] = [-1.8, 0.003]
42
+
43
+ df = ScoutPython.tsv2df(tsv)
44
+ ```
45
+
46
+ The resulting DataFrame has:
47
+ - Index: the TSV keys (`BRCA1`, `TP53`)
48
+ - Columns: the TSV fields (`LogFoldChange`, `PValue`)
49
+ - Column name: the key field (`Gene`) — `tsv2df` sets `df.columns.name`,
50
+ **not** `df.index.name`, which stays `nil`. Keep this in mind if you build
51
+ DataFrames both ways: `scout.tsv()` (the file loader used by `script()`)
52
+ does the opposite and sets `df.index.name` only.
53
+
54
+ Also note the values are passed through **unchanged**: a TSV column of
55
+ strings becomes a pandas `object` dtype column holding those exact strings
56
+ (`"1.5"` stays `"1.5"`), because the values travel as Python objects through
57
+ PyCall rather than being parsed by `read_table`. Type inference only happens
58
+ when a TSV goes through a file, i.e. in `script()` variables — see below.
59
+
60
+ ### DataFrame to TSV
61
+
62
+ ```ruby
63
+ new_tsv = ScoutPython.df2tsv(df)
64
+ # new_tsv is a Ruby TSV with type :list by default
65
+ ```
66
+
67
+ The round-trip is lossless **for well-formed `:list` TSVs of string values**:
68
+ `df2tsv(tsv2df(tsv)) == tsv`. Verified round-tripping includes values that
69
+ contain `;`, `,` and `"` (the dump path escapes them), and the Ruby `:NA`
70
+ sentinel string (which stays the literal string `":NA"`).
71
+
72
+ Things that do **not** survive, verified by probe:
73
+
74
+ - **`tsv.key_field` is taken from `df.columns.name`, not the index name.**
75
+ Round-tripping a DataFrame that was loaded by `scout.tsv()` (whose
76
+ `columns.name` is unset) yields `key_field == ""`.
77
+ - **Type is forced to `:list`** (the default); the original TSV type is not
78
+ remembered, and a `:flat`/`:single` TSV comes back as `:list` with nested
79
+ single-element arrays.
80
+ - **Ragged rows** (a row with more values than the header has fields) raise
81
+ `ValueError: Length mismatch` when loaded through `scout.tsv()` in
82
+ `script()`, while the Ruby TSV tolerates them — the two loaders are
83
+ asymmetric.
84
+ - **Numbers keep their TSV string form in-process** (`"1.5"` stays `"1.5"`);
85
+ going through a file in `script()` converts the column to `float64`.
86
+
87
+ ## Numpy arrays to Ruby arrays
88
+
89
+ ```ruby
90
+ result = ScoutPython.run :numpy, as: :np do
91
+ na = np.array([[1, 2, 3], [4, 5, 6]])
92
+ ScoutPython.numpy2ruby(na)
93
+ end
94
+ # result is a nested Ruby Array: [[1, 2, 3], [4, 5, 6]]
95
+ ```
96
+
97
+ `numpy2ruby` calls `.tolist()` on the numpy array (Python-side conversion),
98
+ then converts the result with `list2ruby`, which recurses into nested
99
+ `PyCall::List` objects.
100
+
101
+ Dtype behaviour, verified by probe:
102
+
103
+ | numpy dtype | Result in Ruby |
104
+ |-------------|----------------|
105
+ | `int64` (2-D) | nested Ruby `Array` of `Integer`: `[[1, 2], [3, 4]]` |
106
+ | `float64` with `NaN` | `Float`, with `NaN` as `Float::NAN` |
107
+ | `str` / `object` (strings) | `Array` of `String` |
108
+ | `object` (mixed `1`, `"a"`) | **all strings**: `["1", "a"]` — PyCall stringifies mixed objects |
109
+ | `bool` | `[true, false]` |
110
+ | `datetime64[D]` | **opaque objects**: Ruby `Object` whose `to_s` is `datetime.date(2020, 1, 1)`; call `.to_s`/`strftime` on the Python side first |
111
+
112
+ Note `numpy2ruby` requires numpy to be importable in the running session
113
+ (`ScoutPython.run(:numpy, as: :np)` above takes care of that); without it
114
+ `.tolist` is undefined.
115
+
116
+ ## Python lists to Ruby arrays
117
+
118
+ ```ruby
119
+ result = ScoutPython.run do
120
+ pyimport :json
121
+ pylist = json.loads('[1, 2, 3]')
122
+ ScoutPython.py2ruby_a(pylist)
123
+ end
124
+ # result is a Ruby Array: [1, 2, 3]
125
+ ```
126
+
127
+ For nested lists, use `list2ruby`, which recurses into `PyCall::List`
128
+ members:
129
+
130
+ ```ruby
131
+ nested = ScoutPython.run do
132
+ pyimport :json
133
+ ScoutPython.list2ruby(json.loads('[[1, 2], [3, 4]]'))
134
+ end
135
+ # nested is [[1, 2], [3, 4]] — genuinely nested Ruby Arrays
136
+ ```
137
+
138
+ By contrast `py2ruby_a` (and its `ScoutPython.to_a` alias) is **flat**: with
139
+ `[[1, 2], [3, 4]]` it returns a Ruby `Array` whose elements are still
140
+ PyCall list objects. They compare equal to the corresponding Ruby arrays
141
+ (`r.first == [1, 2]` is true) but are not `Array`s — use `list2ruby` when
142
+ you need real nested arrays.
143
+
144
+ ## Python dicts to Ruby hashes
145
+
146
+ ```ruby
147
+ result = ScoutPython.run do
148
+ pyimport :json
149
+ d = json.loads('{"a": 1, "b": 2}')
150
+ ScoutPython.obj2hash(d)
151
+ end
152
+ # result is {"a" => 1, "b" => 2}
153
+ ```
154
+
155
+ `obj2hash` works with any Python object that has `.keys` and `[]` access
156
+ (dicts, DataFrames, etc.).
157
+
158
+ `obj2hash` and `dict2hash` differ in one important way:
159
+
160
+ - **`dict2hash` reads values with `obj.get(k)`** and returns **eagerly
161
+ converted** values (`{"x" => 1, "y" => 2}`). Use it for real dicts.
162
+ On a DataFrame `get` resolves to something else entirely and you get the
163
+ Series back anyway (`{"x" => <Series proxy>}`), so it is not a way to
164
+ obtain converted DataFrame columns.
165
+ - **`obj2hash` reads values with `obj[k]`**, which on a DataFrame yields the
166
+ **column as a live proxy** (a pandas `Series`), not a converted value.
167
+ Convert it yourself (`ScoutPython.list2ruby(h["x"].tolist)`) or use
168
+ `df2tsv` when you want native Ruby data out of a DataFrame.
169
+
170
+ Both build plain Ruby `Hash`es with the keys converted to Ruby strings.
171
+
172
+ ## Passing data via `script()`
173
+
174
+ When using `script()` to run Python in a subprocess, variables are
175
+ serialized differently — see [Scripting Python](ScriptingPython.md) for
176
+ details. The key difference is:
177
+
178
+ - **In-process (`run`):** PyCall maintains object identity. Use `tsv2df`,
179
+ `py2ruby_a`, `numpy2ruby`.
180
+ - **Subprocess (`script`):** Data goes through files. TSVs become temp
181
+ files loaded via `scout.tsv()`. Results are pickled or JSON-encoded.
182
+
183
+ ## Common mistakes
184
+
185
+ ### Using `py2ruby_a` on non-list objects
186
+
187
+ `py2ruby_a` expects a list-like Python object. For dicts, use `obj2hash`
188
+ or `dict2hash`.
189
+
190
+ ### Not importing numpy before `numpy2ruby`
191
+
192
+ `numpy2ruby` calls `.tolist()` on the numpy object. The numpy array must
193
+ already exist in the Python environment. This happens naturally inside a
194
+ `run` block.
195
+
196
+ ### Forgetting that script() TSV variables become DataFrames
197
+
198
+ When you pass a TSV to `script()`, the Python variable is a pandas
199
+ DataFrame, not a file path:
200
+
201
+ ```ruby
202
+ # df is a pandas DataFrame in Python, not a file path
203
+ ScoutPython.script <<~PY, df: tsv
204
+ result = df.shape # DataFrame attribute
205
+ PY
206
+ ```
207
+
208
+ ### Assuming the file path preserves your types
209
+
210
+ Because `script()` TSV variables go through `scout.tsv()`
211
+ (`pandas.read_table`), pandas applies its own NA and type inference:
212
+ `NA`, `""`, `nan`, `None` all become `NaN` and a numeric-looking column
213
+ becomes `float64`. The Ruby `:NA` sentinel is protected by its leading
214
+ colon (`":NA"` survives as the literal string `":NA"`), but a plain `"NA"`
215
+ does **not** survive. If you need exact string round-tripping, keep the data
216
+ in-process (`tsv2df`) or quote/escape it yourself.
217
+
218
+ ## See also
219
+
220
+ - [Scripting Python](ScriptingPython.md) — The subprocess scripting facility.
221
+ - [Running Python from Ruby](RunningPythonFromRuby.md) — Execution modes.
222
+ - [Annotating Data](https://github.com/mikisvaz/scout-essentials/blob/main/doc/user/AnnotatingData.md)
223
+ in scout-essentials — The TSV data structure.
@@ -0,0 +1,197 @@
1
+ # Python Environments
2
+
3
+ This document explains how Python environments relate to scout-rig, who is
4
+ responsible for setting them up, and why embedding Python inside a Ruby
5
+ process makes native-library compatibility a real concern.
6
+
7
+ ## Audience
8
+
9
+ This page is intended for:
10
+
11
+ - ✓ Anyone installing or deploying a project that uses scout-rig
12
+ - ✓ Workflow authors who hit import errors or native-library conflicts
13
+ - ✓ System administrators packaging Scout for a cluster or container
14
+ - ✗ Framework contributors looking for PyCall internals (see
15
+ [ScoutPython Internals](../developer/ScoutPythonInternals.md))
16
+
17
+ ## When to use this
18
+
19
+ Read this page when:
20
+
21
+ - You are choosing or building the Python environment a Scout process will
22
+ use.
23
+ - A Python package fails to import inside Ruby but works from a plain
24
+ `python` shell.
25
+ - You are combining several workflows with different Python requirements
26
+ into one project.
27
+ - You need to mix an environment manager (conda, micromamba, a virtualenv
28
+ shipping its own native libraries) with a long-lived Scout process.
29
+
30
+ ## Core concepts
31
+
32
+ ### Scout does not manage Python environments
33
+
34
+ Scout-rig has no environment manager and no dependency resolver. It expects
35
+ an interpreter, its standard library and all required packages (at minimum
36
+ `numpy` and `pandas`, plus `requests` for the remote workflow client) to
37
+ already be installed and reachable, and it hands that interpreter over to
38
+ PyCall. Selection of *which* interpreter is supplied through the normal
39
+ PyCall configuration — notably the `PYTHON` environment variable, which
40
+ `PyCall.init` reads by default — plus `PATH` resolution when `PYTHON` is
41
+ unset.
42
+
43
+ Concretely, PyCall resolves the interpreter by interrogating the `python`
44
+ found on `PATH` (or `ENV['PYTHON']`), locates the matching `libpython`
45
+ shared library and `dlopen`s it into the running Ruby process. Two
46
+ consequences follow:
47
+
48
+ - The environment must be correct *before* Scout starts. Scout does not
49
+ install, activate or repair environments.
50
+ - Whatever environment is selected, its native libraries become libraries
51
+ *of the Ruby process itself*.Concretely, PyCall resolves the interpreter by interrogating the `python`
52
+ found on `PATH` (or `ENV['PYTHON']`), locates the matching `libpython`
53
+ shared library and `dlopen`s it into the running Ruby process. Two
54
+ consequences follow:
55
+
56
+ - The environment must be correct *before* Scout starts. Scout does not
57
+ install, activate or repair environments.
58
+ - Whatever environment is selected, its native libraries become libraries
59
+ *of the Ruby process itself*.
60
+
61
+ The subprocess route (`script()`, `run_file`, `python_task`) does not follow
62
+ this selection at all: it spawns the literal command `python` from `PATH` and
63
+ never reads `ENV['PYTHON']`. The two selections can therefore disagree, and
64
+ `PyCall.init` additionally exports `PYTHONHOME` for the interpreter it
65
+ embedded, which can break unrelated subprocess pythons. The test-only
66
+ availability helpers can report the disagreement —
67
+ `ScoutRig::Testing::Availability.python_routes_divergence_reason` returns
68
+ `nil` when both routes resolve to the same interpreter and a sentence naming
69
+ both resolutions otherwise; see
70
+ [Testing and Packaging](TestingAndPackaging.md). The remedy is the same
71
+ `bin`-first-on-`PATH` recipe described there.
72
+
73
+ ### Embedded Python shares the Ruby process's native library namespace
74
+
75
+ In-process Python (the `ScoutPython.run*` family) is not a subprocess. When
76
+ `ScoutPython.init_scout` calls `PyCall.init`, `libpython` is mapped into the
77
+ Ruby process, and from then on every native extension that Python loads
78
+ (`_ssl`, `_multiarray_umath`, `_ctypes`, ...) is `dlopen`ed into the same
79
+ process. Python and Ruby therefore negotiate one shared set of native
80
+ dependencies.
81
+
82
+ That is usually invisible, but it matters when the selected environment
83
+ supplies its own copies of libraries the Ruby process already has — a very
84
+ common situation with conda/micromamba environments or virtualenvs that
85
+ bundle OpenSSL, `libffi`, `zlib`, `libxml2`, BLAS/LAPACK and friends. Ruby
86
+ has already loaded, say, the system `libssl`; if the embedded Python then
87
+ wants the environment's `libssl` built against a different OpenSSL major
88
+ version, you can get duplicate symbols, subtly wrong behaviour, or a crash
89
+ deep inside `import ssl`, `import numpy` or `import pandas` — none of which
90
+ fail when the same environment is used from a plain `python` process,
91
+ because that process never loads the Ruby side of the conflict.
92
+
93
+ These failures are hard to diagnose precisely because they disappear when
94
+ the Python code is tested standalone.
95
+
96
+ ### ScoutPython manages `sys.path` only — never native libraries
97
+
98
+ `lib/scout/python/paths.rb` is deliberately narrow. It maintains
99
+ `ScoutPython.paths` (seeded at load time from `Scout.python.find_all`, i.e.
100
+ the repository's own `python/` directory) and `process_paths` appends those
101
+ directories to Python's `sys.path`. That is all it does. It never sets
102
+ `LD_LIBRARY_PATH`, `PYTHONHOME`, `PYTHONPATH` or any other loader
103
+ variable, and it never `dlopen`s anything; native library resolution is
104
+ entirely up to the dynamic linker and to PyCall's own libpython discovery.
105
+
106
+ ### Subprocess execution is a different world
107
+
108
+ `ScoutPython.script`, `ScoutPython.run_file`, and Python-backed workflow
109
+ tasks defined with `python_task` do **not** embed anything: each one runs a
110
+ separate `env PYTHONPATH=... python` process. They inherit the environment
111
+ of the Scout process, so the same environment-selection guidance applies,
112
+ but native-library conflicts with Ruby cannot happen there because Ruby and
113
+ Python never share a process.
114
+
115
+ ## Typical usage
116
+
117
+ ### One environment per project
118
+
119
+ Use a single Python environment per Ruby project, containing everything
120
+ that project and all its workflows need. If two workflows need different
121
+ things, build one environment with the union of both requirement sets
122
+ rather than trying to load several environments into one process. Mixing
123
+ environments inside one embedded interpreter is not a supported
124
+ configuration: once `libpython` and its dependencies are loaded, they cannot
125
+ be swapped for a different environment in the same process.
126
+
127
+ For projects whose native dependencies are genuinely irreconcilable, the
128
+ general alternative is process isolation — run the conflicting Python code
129
+ in a separate process. Scout-rig's subprocess-based facilities
130
+ (`ScoutPython.script`, `ScoutPython.run_file`, and `python_task` task
131
+ execution) are already exactly that, so they double as the practical escape
132
+ hatch.
133
+
134
+ ### Establish native library paths before the process starts
135
+
136
+ Native library search paths are resolved by the dynamic loader when a
137
+ library is first mapped, and `libpython` is mapped during the first
138
+ `ScoutPython` call. Setting or changing `LD_LIBRARY_PATH` from inside Ruby
139
+ afterwards is generally too late: the loader consults it at load time, not
140
+ per call, and the conflicting library may already be resident.
141
+
142
+ For a conda or micromamba environment, activate it and export its library
143
+ directory before launching scout-ai:
144
+
145
+ ```bash
146
+ micromamba activate python3
147
+ export LD_LIBRARY_PATH="$CONDA_PREFIX/lib:$LD_LIBRARY_PATH"
148
+ scout-ai workflow task MyWorkflow my_python_task
149
+ ```
150
+
151
+ Environment activation scripts are the automated alternative: placing the
152
+ `export` in the environment's activation hook (for conda/micromamba,
153
+ `etc/conda/activate.d/*.sh`) means every activation sets the loader path
154
+ for you, so no manual step is needed before launching the Ruby process.
155
+
156
+ Note that `PYTHON` (which selects the interpreter PyCall embeds) and
157
+ `LD_LIBRARY_PATH` (which selects where the loader looks for shared
158
+ libraries) are complementary: the first picks *which* Python, the second
159
+ picks *which native copies* satisfy the Python and Ruby sides. Configure
160
+ both before the process starts.
161
+
162
+ ## Common mistakes
163
+
164
+ ### Assuming Scout will activate an environment
165
+
166
+ Scout-rig never activates anything. Whatever `python`/`PYTHON` resolves to
167
+ at the moment Scout first touches PyCall is the environment you get, and
168
+ activation state is only inherited if it was already applied to the
169
+ launching shell (or service unit, container entrypoint, etc.).
170
+
171
+ ### Fixing a native conflict by editing `LD_LIBRARY_PATH` at runtime
172
+
173
+ Changing `ENV['LD_LIBRARY_PATH']` from Ruby after the process has started
174
+ does not change how the loader resolves later `dlopen`s of already-resident
175
+ dependencies, and the first Python import may already have pulled the
176
+ conflicting library in. Fix it in the launching environment instead.
177
+
178
+ ### Testing the environment standalone and concluding it is safe
179
+
180
+ `python -c "import numpy"` succeeding proves the environment is internally
181
+ consistent, not that it is consistent *with the Ruby process it will be
182
+ embedded into*. Reproduce problems through scout-rig itself.
183
+
184
+ ### Reading `ScoutPython.paths` as environment configuration
185
+
186
+ `ScoutPython.add_path`/`add_paths` only extend `sys.path` for Python module
187
+ imports. They cannot add native libraries, and cannot repair a
188
+ `libssl`/BLAS version conflict.
189
+
190
+ ## See also
191
+
192
+ - [Running Python from Ruby](RunningPythonFromRuby.md) — The in-process
193
+ execution modes this page talks around.
194
+ - [ScoutPython Internals](../developer/ScoutPythonInternals.md) — What
195
+ `PyCall.init` actually does inside the Ruby process.
196
+ - [Scripting Python](ScriptingPython.md) — The subprocess route, which
197
+ sidesteps native-library sharing entirely.
@@ -0,0 +1,267 @@
1
+ # Running Python from Ruby
2
+
3
+ This document explains how to execute Python code from Ruby using
4
+ scout-rig. It covers the different execution modes, importing Python
5
+ modules, and choosing the right approach for your use case.
6
+
7
+ ## Audience
8
+
9
+ This page is intended for:
10
+
11
+ - ✓ Workflow authors who need to call Python from Ruby
12
+ - ✓ Agent developers building cross-language tools
13
+ - ✗ Framework contributors (see [ScoutPython Internals](../developer/ScoutPythonInternals.md))
14
+
15
+ ## When to use this
16
+
17
+ Use ScoutPython when you need to:
18
+
19
+ - Call Python libraries (numpy, pandas, PyTorch, etc.) from Ruby code.
20
+ - Run a quick Python snippet and get a result back.
21
+ - Integrate Python-based computation into a Scout workflow.
22
+ - Process data with Python tools that have no Ruby equivalent.
23
+
24
+ ## Core concepts
25
+
26
+ ScoutPython is a thin layer over the [pycall](https://github.com/mrkn/pycall.rb)
27
+ gem. It adds import helpers, execution modes with different isolation levels,
28
+ and data conversion utilities. You never interact with PyCall directly.
29
+
30
+ ### Execution modes
31
+
32
+ Different situations call for different levels of isolation and overhead.
33
+ ScoutPython provides a progression of execution modes:
34
+
35
+ | Mode | Overhead | Isolation | When to use |
36
+ |------|----------|-----------|-------------|
37
+ | `run` | Medium | Synchronized | General-purpose default |
38
+ | `run_simple` | Low | Synchronized | Already initialized, need speed |
39
+ | `run_direct` | Lowest | None | Quick one-liners, no synchronization |
40
+ | `run_threaded` | High | Dedicated thread | Background work — but see the threading caveats in *Common mistakes* before choosing it |
41
+ | `run_log` | Medium | Synchronized | When you need to capture Python output |
42
+
43
+ ### Imports
44
+
45
+ All execution modes accept an optional import directive before the block:
46
+
47
+ ```ruby
48
+ # Import a module
49
+ ScoutPython.run :numpy do
50
+ numpy.array([1, 2, 3])
51
+ end
52
+
53
+ # Import with an alias
54
+ ScoutPython.run :numpy, as: :np do
55
+ np.array([1, 2, 3])
56
+ end
57
+
58
+ # Import a specific name from a module
59
+ ScoutPython.run "tensorflow.keras.models", import: :Sequential do
60
+ self::Sequential
61
+ end
62
+
63
+ # No import — use pyimport/pyfrom inside the block
64
+ ScoutPython.run do
65
+ pyimport :sys
66
+ sys.version
67
+ end
68
+ ```
69
+
70
+ ## Typical usage
71
+
72
+ ### The default: `run`
73
+
74
+ ```ruby
75
+ # Compute a numpy array sum
76
+ result = ScoutPython.run :numpy, as: :np do
77
+ a = np.array([1, 2, 3, 4, 5])
78
+ a.sum()
79
+ end
80
+ puts result # => 15
81
+ ```
82
+
83
+ `run` initializes PyCall if needed, synchronizes access (important for
84
+ thread safety), runs your block, and triggers garbage collection afterward.
85
+
86
+ ### Quick one-liners: `run_direct`
87
+
88
+ ```ruby
89
+ # Fastest mode — no synchronization, no GC
90
+ result = ScoutPython.run_direct :numpy do
91
+ numpy.array([1, 2, 3])
92
+ end
93
+ ```
94
+
95
+ Use `run_direct` when you're sure no other thread is accessing Python and
96
+ you want minimal overhead.
97
+
98
+ ### Background work: `run_threaded`
99
+
100
+ ```ruby
101
+ # Execute Python in a dedicated background thread
102
+ result = ScoutPython.run_threaded :numpy, as: :np do
103
+ np.array([1, 2, 3])
104
+ end
105
+
106
+ # When done with all threaded work, clean up
107
+ ScoutPython.stop_thread
108
+ ```
109
+
110
+ Threaded execution runs in a dedicated thread with its own queue. All
111
+ threaded calls are serialized through this queue. Call `stop_thread` when
112
+ you're done to clean up resources.
113
+
114
+ ### Capturing output: `run_log`
115
+
116
+ ```ruby
117
+ # Capture Python stdout/stderr and route to Scout Log
118
+ ScoutPython.run_log :sys do
119
+ print("Hello from Python")
120
+ end
121
+ ```
122
+
123
+ Use `run_log` when you want Python's output routed to Scout's logging
124
+ system instead of going to the terminal directly.
125
+
126
+ ## Importing modules
127
+
128
+ ### Inside a block
129
+
130
+ Inside any execution block, you have access to PyCall's import methods:
131
+
132
+ ```ruby
133
+ ScoutPython.run do
134
+ pyimport :json # import json
135
+ pyfrom :os.path, import: :join # from os.path import join
136
+ pyimport :numpy, as: :np # import numpy as np
137
+
138
+ np.array([1, 2, 3])
139
+ end
140
+ ```
141
+
142
+ ### Import helpers
143
+
144
+ ScoutPython provides convenience methods for common import patterns:
145
+
146
+ ```ruby
147
+ # Get a bound Ruby method for a Python function
148
+ random = ScoutPython.import_method :random, :randint
149
+ random.call(1, 10)
150
+
151
+ # Call a Python function directly
152
+ ScoutPython.call_method :random, :seed, 42
153
+
154
+ # Import a module object
155
+ sys = ScoutPython.get_module :sys
156
+
157
+ # Get a class
158
+ Linear = ScoutPython.get_class "torch.nn", "Linear"
159
+
160
+ # Instantiate a class with keyword arguments
161
+ layer = ScoutPython.class_new_obj "torch.nn", "Linear", in_features: 10, out_features: 5
162
+
163
+ # Execute a Python expression
164
+ ScoutPython.exec "x = 42"
165
+ ```
166
+
167
+ ### Binding scopes
168
+
169
+ Imports inside `run` blocks leak into the `ScoutPython` module namespace.
170
+ To isolate imports, use a binding scope:
171
+
172
+ ```ruby
173
+ ScoutPython.binding_run do
174
+ pyimport :torch
175
+ pyfrom :torch, import: ["nn"]
176
+ # torch is available here
177
+ end
178
+ # torch is NOT available outside this block
179
+ ```
180
+
181
+ Each `binding_run` creates a fresh scope. This is useful when importing
182
+ large frameworks (like PyTorch) that you don't want polluting the global
183
+ namespace.
184
+
185
+ Two details worth knowing:
186
+
187
+ - `binding_run` accepts an optional first argument but ignores it; a fresh
188
+ binding is always created. Passing an existing `Binding` will not reuse
189
+ it.
190
+ - To reuse a scope across several calls, create the binding yourself with
191
+ `ScoutPython.new_binding` and run blocks on it with `instance_exec`;
192
+ imports made on that instance persist between calls:
193
+
194
+ ```ruby
195
+ b = ScoutPython.new_binding
196
+ b.instance_exec { pyimport :math }
197
+ b.instance_exec { math.sqrt(16) } # => 4.0 — math is still available
198
+ ```
199
+
200
+ ## Common mistakes
201
+
202
+ ### Using `run_direct` in a multi-threaded context
203
+
204
+ `run_direct` skips synchronization. If another thread is accessing Python
205
+ at the same time, you may get a GIL-related crash. Use `run` or `run_simple`
206
+ in multi-threaded code.
207
+
208
+ ### Mixing `run_threaded` with the other modes
209
+
210
+ Once `run_threaded` has run, PyCall effectively belongs to the background
211
+ thread, and calling any of the main-thread modes afterwards — including
212
+ `run` and `run_simple` — crashes the process with a segmentation fault. The
213
+ same happens in the other direction (`run` first, then `run_threaded`), and
214
+ even when a second Ruby thread simply calls `run`. Pick one mode family per
215
+ process: either the main-thread modes, or `run_threaded`, never both. See
216
+ [ScoutPython Internals](../developer/ScoutPythonInternals.md) for details.
217
+
218
+ ### Expecting `run_threaded` to survive an exception
219
+
220
+ If the block raises, the exception is logged and re-raised inside the
221
+ background thread, which kills it. The Ruby thread waiting for the result
222
+ then blocks forever. A failing `run_threaded` block is not recoverable in
223
+ the current implementation: treat it as fatal for the process, or wrap your
224
+ Python code so exceptions are returned as values instead.
225
+
226
+ ### Forgetting to call `stop_thread`
227
+
228
+ If you use `run_threaded`, the background thread stays alive. Call
229
+ `ScoutPython.stop_thread` when you're done.
230
+
231
+ Caveat, verified at HEAD: `stop_thread` does not currently guarantee a
232
+ clean exit. After threaded use the process either hangs in the shutdown
233
+ path or segfaults on the next PyCall call, whether or not `stop_thread` was
234
+ called. If you can, prefer the main-thread modes (`run`) or the subprocess
235
+ helpers ([Scripting Python](ScriptingPython.md)) for long-lived processes;
236
+ see [ScoutPython Internals](../developer/ScoutPythonInternals.md).
237
+
238
+ ### Importing heavy modules inside hot loops
239
+
240
+ Each `pyimport` call has overhead. Import modules once, outside loops:
241
+
242
+ ```ruby
243
+ # Bad — reimports every iteration
244
+ 100.times do
245
+ ScoutPython.run_direct :numpy do
246
+ numpy.array([1, 2, 3]).sum()
247
+ end
248
+ end
249
+
250
+ # Better — import once
251
+ ScoutPython.run :numpy do
252
+ 100.times { numpy.array([1, 2, 3]).sum() }
253
+ end
254
+ ```
255
+
256
+ ## See also
257
+
258
+ - [Passing Data to Python](PassingDataToPython.md) — How to convert Ruby
259
+ data structures to Python.
260
+ - [Scripting Python](ScriptingPython.md) — Running full Python scripts with
261
+ variable injection.
262
+ - [Python Environments](PythonEnvironments.md) — How the Python environment
263
+ is selected, and why embedded Python shares native libraries with Ruby.
264
+ - [ScoutPython Internals](../developer/ScoutPythonInternals.md) — How the
265
+ execution modes are implemented.
266
+ - [Running Commands](https://github.com/mikisvaz/scout-essentials/blob/main/doc/user/RunningCommands.md)
267
+ in scout-essentials — The CMD module that ScoutPython builds on.