Skip to content
Run your own R or Python

Run your own R or Python

A Script runs R or Python code at a chosen point in a Sequence. Use one to prepare input data before a Run, or to analyze collected output after one. Experimenter runs a bare .py or .R file with the Python or Rscript you set in the Settings window. It installs no library.

Where a Script runs

  • As a Sequence stage. A Script is one member of a Sequence outline, beside the Stages that name a Run or a Group. It runs when execution reaches its position.
  • Between the Runs of a Group. Name the Runs of the Group one by one as stages, and put the Script stage between two of them. The Group on its own tab never holds a Script.
  • As a dataset-axis bookend. A top-level datasets: axis entry carries before: and after: Script lists. A before Script runs once before that dataset’s lane starts, an after Script once after the lane finishes. The groups: dataset groups of a Sequence have no bookend. Every stages: member already runs once per group. A Script as the first or last stages: entry does the same job at the same cadence.

The Order panes of the Run, Optimization and Sensitivity tabs hold no Script. Experimenter refuses to open a file with a Script in a runs: entry, in a group: list or in the runs: list of an Optimization. The message names the Script. Move it into a stage on the Sequence tab, or remove it.

Editing a Script in the GUI

On the Sequence tab, Add > Add script adds a Script stage. Select a Script stage to open its own Settings pane. The pane has a Script identity row naming the selection (the File/Run/Group idiom), then Name (shown in the outline and the Monitor), File (a .py or .R path, or a full command, with a … browse button), Timeout, and Continue on error. During a run the pane accepts no edits. See The run lock.

Add > Add script puts the Script below the selected stage and its nested stages, at the same level. With no single stage selected, it goes last at level 0.

The env-var contract

A Script starts in the folder that holds the Experiment file. Experimenter passes context only through environment variables. Every variable below is always set. A missing value is the empty string, never an unset key.

VariableValueEmpty when
EXPERIMENTER_OUTPUT_DIRThe Outputs folder for the Script scope.Never.
EXPERIMENTER_MODEL_DIRThe nearest model or run-copy folder. Among independent Runs, the scope folder. Inside a chained group, the shared copy. In a Sequence, the Script’s own level decides, the same outline rule a Run/Optimization member follows. Nested one level under an enclosing stage, it points at a copy of that stage’s folder. At level 0, it points at the Template.At a dataset-axis bookend (no run copy exists there).
EXPERIMENTER_DATASETThe current dataset name.Outside a dataset sweep.
EXPERIMENTER_CONFIGThe Experiment file that owns the Script’s position.Never.
EXPERIMENTER_SEQUENCEThe enclosing sequence name.Outside a Sequence.
EXPERIMENTER_GROUPThe enclosing group name.Outside a group.
EXPERIMENTER_POSITIONThe item index in its order, or before / after for a dataset-axis bookend.Never.
EXPERIMENTER_VERSIONThe Experimenter version. Compare it against the version the script targets, and warn on a mismatch.Never.
EXPERIMENTER_COMPARISON_RUNThe saved-run name that holds the observed data this scope compares against. Resolved from the full Calibration membership, chained or not.Outside a Calibration scope, or when the Runs bind more than one distinct name.
EXPERIMENTER_TIME_COLUMNThe model’s time_units (for example Year), or Time when the model declares none. In a long file it is the header of the time column. A wide file has no such column, and the name labels the step axis. Read a long column by this name, not by position. The name changes with the model, and a new context column can shift what looks like “the first other column” (see Outputs).Never.
EXPERIMENTER_OUTPUT_NAMEThe collated file’s own basename inside EXPERIMENTER_OUTPUT_DIR: the Output File Name preference, or a Sequence’s own Output File. Default Output.csv. Read this name and never hardcode one: the preference can change it.Never.
EXPERIMENTER_OUTPUT_LAYOUTwide or long: the layout the launch writes the collated file in. In wide, each row is one Run and variable and each time step is a column. In long, each row is one time step, variable and Run. Branch on this value and never guess from the header. The launch fixes it, so a change in Settings during the launch does not reach a running Script.Never.

Command resolution

  • A bare script path (exactly one token ending .py, .R, or .r) gets an inferred interpreter. That is the Python or Rscript from Settings, Environment. With a blank setting it is python3 or Rscript from your login shell.
  • Anything else runs verbatim: an explicit interpreter, a venv path (script: ".venv/bin/python prep.py"), or extra arguments.

The bundled scripts library

The app carries a pinned snapshot of the approved public scripts/ library. When a Script’s File is a bare name with no directory of its own (Calibration_Fit.R, not Scripts/Calibration_Fit.R or an absolute path), Experimenter first looks for that name beside the Experiment file. If no copy exists there, it uses the bundled snapshot. A name that matches no approved script stays as typed. Either outcome logs one line to the Log panel and the Monitor: which copy ran, and its full path. Two bundled scripts can share a name in different per-language folders. Experimenter then picks the first by sorted path and the log line notes the ambiguity.

On a Script row, Bundled scripts… opens a filterable list of the bundled scripts. Pick one to set its bare name as the File. Edit copies the bundled script beside the Experiment file and opens the copy. The copy runs in place of the bundled script. Edit never overwrites a file that is already there.

The Calibration Fit chain

Calibration_Fit reads only Wide_To_Long.csv, so the Script stages after a calibration run these steps in this order:

  1. Wide_To_Long converts the collated file to a long table and writes Wide_To_Long.csv, or Wide_To_Long_<dataset>.csv when EXPERIMENTER_DATASET has a value.

  2. Calibration_Fit reads that file and writes Calibration_Fit.csv, or Calibration_Fit_<dataset>.csv when EXPERIMENTER_DATASET has a value.

  3. Collect_Datasets --stem Calibration_Fit is optional. It puts the per-dataset files into one file.

Each script reads its input by name. Without a Wide_To_Long file in the folder, Calibration_Fit stops and names the missing file.

Experimenter resolves a bare interpreter against the login-shell PATH plus common install locations (Homebrew, the R framework). A Script therefore finds Rscript or a Homebrew python3 even when Experimenter starts from the Finder. Experimenter bundles no interpreter.

Choose the Python and Rscript

Set the interpreter once and every bare .py and .R step uses it. You change no PATH and no Experiment.

  1. Choose Experimenter ▸ Settings… and select the Environment tab.
  2. In Python for Script steps, type the path of a Python or use Browse, such as <conda>/envs/<name>/bin/python or <venv>/bin/python.
  3. In Rscript for Script steps, do the same for Rscript.
  4. Read the line under each field. It names the program that runs and its version.

A blank field uses python3 or Rscript from your login shell. A step that names its own interpreter, such as .venv/bin/python prep.py, ignores the setting.

The Environment tab of the Settings window, with sample values. The group Next Batch records lists each component with its version and source.

The Environment tab also lists Next Batch records. Each row gives a component, its version and its source, the values that the next Batch writes into batch.json. A source is one of preferences:<path>, login-shell, bundled or system. Use Show latest Batch record… to open the record of the latest Batch of the open Experiment, read-only. The tab shows state and nothing else. A change since the previous Batch goes to the Log as a drift warning.

The record holds the Python or Rscript that ran each Script step, not the Python of the app. For a Python file it also lists the version of each package that the file imports. See what each job writes.

An environment for the bundled scripts

The bundled scripts import these libraries:

LanguageLibraries
Pythonpandas, numpy, matplotlib
Rjsonlite, ggplot2

A script needs only the libraries it imports. A few write an Excel workbook when openpyxl, openxlsx or writexl exists, and skip it otherwise. The README of each script lists what it needs.

The Settings window checks them for you. Open the Environment tab and read Script packages, under the two interpreter fields. It names each bundled script that imports a package your Python or Rscript lacks. Hold the pointer over the line to read all of them. The check runs when the tab opens and when you change an interpreter field.

Choose Create venv and install to fix the Python packages. It makes the venv script-venv in the settings folder and installs the missing packages there. Then it checks again. When every package is present, it puts the venv Python in Python for Script steps. The button does nothing for R. For R, run the install.packages line in R. A source checkout has no bundled scripts, and the line says so.

To make an environment by hand for the Python libraries:

python3 -m venv ~/experimenter-env
~/experimenter-env/bin/python -m pip install pandas numpy matplotlib

Then enter ~/experimenter-env/bin/python in Python for Script steps. For conda, run conda create -n experimenter pandas numpy matplotlib and enter the Python of that environment. For R, run install.packages(c("jsonlite", "ggplot2")) in R.

When a step fails because its interpreter lacks a library, the Log shows one line. It names the library and the command that installs it. It also points to Settings, Environment, where Script packages installs it.

Timeout and failure

  • Each Script has its own timeout, in seconds, default 300. Experimenter kills a Script that runs longer and marks it failed.
  • A failed Script (non-zero exit or timeout) skips the stages nested under it. Experimenter records each one as skipped. A nested Run never starts on data a failed prep Script did not produce. The siblings of the Script keep running (Sequence tab). A failed before Script of a dataset stops that lane before it starts.
  • Set continue_on_error: true to run past a failure. Use it on an analysis Script whose own failure should not discard finished Runs.
  • A Script’s combined stdout and stderr stream to the Monitor log, tagged with the Script name. On a failure, the log carries the last lines of that output.

Ordering

  • After a stage, inside a Sequence’s stages: list: the Script sees the result of every stage run so far in that lane. Experimenter collates the file immediately before the Script starts. The Script then reads a current file at $EXPERIMENTER_OUTPUT_DIR/$EXPERIMENTER_OUTPUT_NAME.
  • In a dataset lane: EXPERIMENTER_OUTPUT_DIR is the lane folder, and the file in it holds that lane’s dataset value only. This holds in the long and the wide layout. It applies to a Sequence-stage Script, a Script in a stage sub-experiment, and a Script between two calibration stages. Only the top file spans every dataset, and no Script in a lane gets it.
  • At a dataset-axis bookend: no guarantee. Experimenter collates the enclosing scope once, after the whole sweep. A bookend Script can find the collated file absent or stale. Read from EXPERIMENTER_MODEL_DIR instead.
  • Cleanup never removes a file a Script is still positioned to read. Both cleanup forms run only after every Script in scope has finished. The forms are the default top-only prune and Retention set to Outputs only. Outputs only deletes every other file in the output folder, the files that Scripts wrote there included. A Script that must keep a result writes it outside the output folder.
  • Nested in a Sequence outline: a Script placed one level under an enclosing stage receives a copy of that stage’s folder and may change it in place before its own children read it. This adjusts carried-forward state, and it is also a hazard. Use a read-only Script here, unless you intend to change the folder. A Script at level 0 runs against the Template regardless of what came before it. A Script never advances the lane’s history by producing a folder of its own. Only an item nested under the Script inherits its edited copy.

YAML shape

A Script is a mapping with a script: key and a name:. It sits in a stages: list of a Sequence. timeout and continue_on_error are optional. Here the Sequence names the two Runs of the Group all one by one, so a Script can run between them:

model: Model.stmx
runs:
  baseline: {}
  policy-shift: {}
  all:
    group: [baseline, policy-shift]
sequences:
  main:
    stages:
      - {name: fetch-inputs, script: prep.py}
      - {stage: baseline}
      - {name: compare, script: compare.py}
      - {stage: policy-shift}
      - {name: report, script: "Rscript analyze.R", continue_on_error: true}

Run it with experimenter run --section sequence:main <experiment>, or launch the Sequence in the GUI.

A top-level dataset-axis entry uses the same shape under before: or after::

datasets:
  - name: japan
    base: datasets/japan
    after: [{name: summarize, script: analyze.R, continue_on_error: true}]

A Sequence’s groups: dataset groups take no before: or after:. Put the Script in stages: instead, first or last:

sequences:
  main:
    stages:
      - {name: prep, script: prep.py}
      - {stage: simulate}
      - {name: summarize, script: analyze.R, continue_on_error: true}
    groups:
      - name: japan
        base: datasets/japan

A Script inside a Sequence’s stages: list takes the same level: key a Run or Optimization member does. Nested one level under an enclosing stage, it receives a copy of that stage’s folder. Its own edits reach whatever is nested one level under it in turn. In the example, adjust-seed sits under the calibrate stage, and the simulate stage sits one level deeper, under adjust-seed:

sequences:
  main:
    stages:
      - {stage: calibrate}
      - {name: adjust-seed, script: adjust.py, level: 1}
      - {stage: simulate, level: 2}

Example: an analysis Script

analyze.R runs after the Runs, so the collated file holds their collected rows. Build the path from EXPERIMENTER_OUTPUT_NAME, never a hardcoded name such as Output.csv or the legacy output.csv. The Output File Name preference, or a Sequence’s own Output File, can name it anything.

A Script that reads Output.csv must handle both layouts. Read the layout from EXPERIMENTER_OUTPUT_LAYOUT. When it is unset, as in a Script you run by hand, a value column means long. Anything else means wide. For wide, melt the file to the long shape first. Read every column as text and set check.names = FALSE, or R renames the step header 1990 to X1990:

#!/usr/bin/env Rscript
csv_path <- file.path(
  Sys.getenv("EXPERIMENTER_OUTPUT_DIR"), Sys.getenv("EXPERIMENTER_OUTPUT_NAME")
)
raw <- read.csv(csv_path, colClasses = "character", check.names = FALSE)

# Layout: the declared value, else a guess from the header for a by-hand run.
layout <- Sys.getenv("EXPERIMENTER_OUTPUT_LAYOUT")
if (layout == "") layout <- if ("value" %in% names(raw)) "long" else "wide"
if (!layout %in% c("wide", "long")) stop("unknown output layout: ", layout)

if (layout == "wide") {
  # Melt: one long block per step column, dropping empty cells.
  time_col <- Sys.getenv("EXPERIMENTER_TIME_COLUMN", unset = "Time")
  context <- c(
    "sequence", "dataset", "level", "group", "source", "source_kind", "engine",
    "started_at", "batch_id", "record_hash", "sample"
  )
  ids <- c(intersect(context, names(raw)), "variable")
  blocks <- lapply(setdiff(names(raw), ids), function(step) {
    keep <- raw[[step]] != ""
    block <- raw[keep, ids, drop = FALSE]
    block[[time_col]] <- rep(step, sum(keep))
    block$value <- raw[[step]][keep]
    block
  })
  results <- do.call(rbind, blocks)
} else {
  results <- raw
}
results$value <- as.numeric(results$value)

by_source <- aggregate(value ~ source + source_kind + variable, data = results, FUN = mean)
write.csv(by_source, file.path(dirname(csv_path), "summary.csv"), row.names = FALSE)

A prep Script is the same pattern in reverse: it runs before the Runs, with no collated file yet. It puts input files in its working directory (the configuration folder) for the Runs to read.