| Title: | Perform a Contract-Typed Analytical Plan Across Analytics Components |
|---|---|
| Description: | Declares an analytical plan as a directed acyclic graph of nodes, each bound to a tool that returns an 'orchestraManifest' result, and performs it in topological order. Every edge is typed by the inferential target the upstream node declares, and a mismatched handoff stops the run before the downstream node executes rather than coercing across a contract boundary. Two epistemic operators are built in: a power-aware abstention gate that refuses to pass a null verdict the design could not have resolved, and a triangulation operator that reconciles any number of independent lenses on one question. A plan serialises to 'YAML' and back, compiles to a 'targets' pipeline, and every run writes a provenance record with the integrity chain of the manifests it produced. |
| Authors: | Max Moldovan [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-9680-8474>) |
| Maintainer: | Max Moldovan <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.3.0 |
| Built: | 2026-12-04 03:18:35 UTC |
| Source: | https://github.com/max578/conductoR |
Checks a table against conditions declared before it was made, and stops
when one does not hold. conduct() runs the same check on every input a
plan declares, before the first node; a script that writes a table by
hand can call it on its own output before writing it.
check_postconditions(x, conditions, input = "input", key = NULL)check_postconditions(x, conditions, input = "input", key = NULL)
x |
A data frame. |
conditions |
A character vector of postconditions, named by their
ids, or an oap_plan, whose declared postconditions and key for the
input |
input |
The name of the input in the plan, or a label for |
key |
Columns whose combined values must be unique and never
missing, or |
Invisibly, a data frame with one row per postcondition and the
columns input, id, condition, holds and detail, when every
postcondition holds. Otherwise an error of class postcondition_failed
that lists each failure with a count of the rows that fail; the error
names no value of the table.
A postcondition is a condition in the grammar described in conduct(),
with two kinds of name. A bare column name stands for the column, so a
comparison is made row by row and the postcondition holds when it is
TRUE in every row: window_days <= 31. A name that starts with a dot
is a summary of the table: .n_rows, .n_cols, and, for a column x,
.n_missing.x, .n_distinct.x and .n_duplicated.x (counted over the
values that are not missing), .min.x and .max.x (missing values
left out) and .levels.x (its distinct values as text, so that
.levels.x %in% c("a", "b") holds when no other value occurs). A
postcondition that gives NA in any row, or names a column the table
does not have, does not hold.
Max Moldovan
tab <- data.frame(trial_id = c("t1", "t2", "t3"), window_days = c(30, 31, 62)) ok <- tryCatch( check_postconditions(tab, c(P_rows = ".n_rows == 3", P_days = "window_days <= 31"), input = "moisture", key = "trial_id"), postcondition_failed = function(e) conditionMessage(e)) cat(ok)tab <- data.frame(trial_id = c("t1", "t2", "t3"), window_days = c(30, 31, 62)) ok <- tryCatch( check_postconditions(tab, c(P_rows = ".n_rows == 3", P_days = "window_days <= 31"), input = "moisture", key = "trial_id"), postcondition_failed = function(e) conditionMessage(e)) cat(ok)
Writes a _targets.R in which each node is one targets::tar_target()
calling conduct_step(), so the plan inherits caching and skipping of
up-to-date nodes from 'targets' while every edge stays type-checked. Target
names are the node ids prefixed with n_.
compile_to_targets(plan, script_file, preamble = character(0))compile_to_targets(plan, script_file, preamble = character(0))
plan |
An oap_plan. |
script_file |
The path to write. |
preamble |
Lines of R placed at the top of the script. They must bind
|
A plan whose nodes use when, foreach or on_refusal is refused with
an error of class conductoR_unsupported, since those are applied by
conduct(). A select node compiles like any other node.
script_file, invisibly.
Max Moldovan
terminal_target(), conduct_step().
p <- oap_plan(id = "chain", nodes = list( node("a", tool = "stats::median"), node("b", tool = "stats::median", consumes = list(edge("a"))) )) f <- tempfile(fileext = ".R") compile_to_targets(p, f, preamble = c("library(conductoR)", ".score <- readRDS('plan.rds')", ".data <- list()")) cat(readLines(f), sep = "\n")p <- oap_plan(id = "chain", nodes = list( node("a", tool = "stats::median"), node("b", tool = "stats::median", consumes = list(edge("a"))) )) f <- tempfile(fileext = ".R") compile_to_targets(p, f, preamble = c("library(conductoR)", ".score <- readRDS('plan.rds')", ".data <- list()")) cat(readLines(f), sep = "\n")
Walks the plan in topological order and performs each node with
conduct_step(). Every in-edge is type-checked before its node runs, so a
mismatched handoff stops the run before the downstream tool executes. An
abstaining gate in halt-branch mode skips every node downstream of it;
the skipped nodes are recorded in the provenance, not dropped.
conduct(plan, data = list(), out_dir = NULL, verbose = TRUE, label = NULL)conduct(plan, data = list(), out_dir = NULL, verbose = TRUE, label = NULL)
plan |
An oap_plan. |
data |
The data object every tool receives. |
out_dir |
A directory to write the provenance record into, or |
verbose |
Print one line per node as it runs. |
label |
A short string stored with the run, such as |
A list with elements plan_id, plan_hash, input_hash,
label, bus (the manifest each node emitted, named by node id),
provenance (one record per node), conditions (one row per when
evaluated: node, condition, value), items (one row per foreach item:
node, item, instance, status, run_id), stopped_by (the node whose
refusal ended the run, or NA), postconditions (one row per input
postcondition checked: input, id, condition, holds, detail), n_nodes,
n_skipped, seconds and
terminal (the manifest of the last node that ran). Returned invisibly.
An abstain_gate node reads the one verdict it consumes and abstains
when any of these holds: the upstream emitter abstained; the verdict is
"no_effect" and the metric n is below params$n_min (default 25); the
verdict is "no_effect" and the power proxy
|effect_mean| / (noise_sd / sqrt(n)) is below params$z_floor (default
2); or any metric named in params$floors (a named list of minima) is
below its floor. params$mode sets what an abstention does downstream:
"flag" (default) records it and continues, "halt-branch" skips the
descendants, "reroute" tells a downstream triangulation to drop the
gated lens and reconcile the survivors.
A triangulate node reads every lens it consumes, each a manifest whose
summary metrics carry effect_present or influence_present, and at most
one gate. It emits one of seven consensus headlines:
causal_effect_corroborated (two or more lenses, all with an effect),
no_effect_corroborated (two or more, none with an effect),
single_lens_effect and single_lens_no_effect (one lens),
disagreement_flagged (mixed), and abstain (the gate abstained in flag
mode, or no lens survived a reroute).
A node with a when condition runs only when the condition is TRUE.
When it is FALSE, the node and every node downstream of it are skipped,
and the run records the condition, its value and the reason. A condition
reads results of nodes upstream: <node>.headline, <node>.abstained,
<node>.n_rows (rows of its params table) and <node>.metrics.<name>.
It may use numbers written plainly, quoted strings, TRUE, FALSE, the
comparisons ==, !=, <, <=, >, >=, %in% with c(...), the
logical operators &, |, ! (&& and || read the same) and
brackets. A function call, $, ::, backticks, an assignment and
anything else not listed here are refused when the plan is built. A
condition is never run as R code.
A select node keeps the rows of its input's params table for which
params$rule is TRUE. The rule follows the same grammar, with column
names in place of references. Rows where the rule gives NA are dropped
and counted in the metric n_na.
A compute node with foreach runs once for each item: a fixed list, or
each distinct value of a column of the params table of a node it
consumes (list(from = <node>, column = <name>)). Each instance receives
its item as node@params$item and is recorded as <id>[<item>]. More
items than foreach_max (default 50) stop the run with an error. The node
emits one manifest whose params table has one row per item, with its
status (ran, refused or skipped), and whose outputs holds the
instance manifests. With no items, nothing runs and downstream nodes
receive that record, with n_items = 0.
A refusal is a result that abstains: its summary says abstained. A
node's on_refusal sets what a refusal does: "continue" (default)
passes it on, "halt-branch" skips every node downstream of it, "stop"
ends the run; the nodes not yet performed are recorded as skipped. In a
foreach, "halt-branch" and "stop" also skip the items not yet run.
A tool that fails with an error stops the run in every case: an error is
not a refusal.
A plan may declare the tables it reads in inputs, each with the
postconditions it must meet and, optionally, a key (see plan_input()
and check_postconditions() for the grammar). Before the first node
runs, every postcondition of every input is checked against data: an
input names an element of data, or data itself under the name
"data" when data is a data frame. When one does not hold, or an input
is absent, no node runs and the run stops with an error of class
postcondition_failed that lists every failure. try_conduct() turns it
into a failed run whose record carries one line <input>.<id> postcondition_failed per failure.
Every run records input_hash, a SHA-256 of data, and plan_hash, a
SHA-256 of the plan together with the code of every tool it references
(see same_plan()). To blind an analysis, run the plan on data whose
treatment labels are hidden, freeze the plan, then run it once on the
true data. same_plan() then shows that both runs used one plan on
different data.
Max Moldovan
conduct_step(), run_provenance(), plan_to_yaml(),
same_plan().
lens_a <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "lens_a", "lens_a:demo") } lens_b <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "lens_b", "lens_b:demo") } p <- oap_plan(id = "two_lenses", nodes = list( node("a", lens_a, emits = "treatment_effects"), node("b", lens_b, emits = "treatment_effects"), node("consensus", operator = "triangulate", emits = "decisions", consumes = list(edge("a", "treatment_effects"), edge("b", "treatment_effects"))) )) run <- conduct(p, verbose = FALSE) run$terminal@summary$headline # Run a check once per site, but only when lens a found an effect. check <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "check", paste0("check:", node@params$item)) } p2 <- oap_plan(id = "per_site", nodes = list( node("a", lens_a, emits = "treatment_effects"), node("check", check, emits = "treatment_effects", consumes = list(edge("a", "treatment_effects")), when = "a.headline == \"effect\"", foreach = c("site_1", "site_2")) )) run2 <- conduct(p2, verbose = FALSE) run2$itemslens_a <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "lens_a", "lens_a:demo") } lens_b <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "lens_b", "lens_b:demo") } p <- oap_plan(id = "two_lenses", nodes = list( node("a", lens_a, emits = "treatment_effects"), node("b", lens_b, emits = "treatment_effects"), node("consensus", operator = "triangulate", emits = "decisions", consumes = list(edge("a", "treatment_effects"), edge("b", "treatment_effects"))) )) run <- conduct(p, verbose = FALSE) run$terminal@summary$headline # Run a check once per site, but only when lens a found an effect. check <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "check", paste0("check:", node@params$item)) } p2 <- oap_plan(id = "per_site", nodes = list( node("a", lens_a, emits = "treatment_effects"), node("check", check, emits = "treatment_effects", consumes = list(edge("a", "treatment_effects")), when = "a.headline == \"effect\"", foreach = c("site_1", "site_2")) )) run2 <- conduct(p2, verbose = FALSE) run2$items
Type-checks every input the node consumes, dispatches on the node's
operator and checks that the output declares the inferential target the
node promised. conduct() calls this once per node, and a pipeline
written by compile_to_targets() calls it once per target.
conduct_step(node, inputs = list(), data = list())conduct_step(node, inputs = list(), data = list())
node |
An oap_node. |
inputs |
A named list of upstream manifests, one per edge in
|
data |
The data object every tool receives as its second argument. |
The orchestraManifest::orchestra_manifest the node emitted.
An input that does not declare the contract its edge was typed with stops
the step with a message containing TYPED-EDGE VIOLATION. An input that
fails orchestraManifest::consume_manifest() stops with that guard's own
message. A tool that returns something other than a manifest, or a
manifest with a different target from node@emits, stops after the tool
has run.
when, foreach and on_refusal are applied by conduct();
conduct_step() performs the node once, as given.
Max Moldovan
lens <- node("lens", emits = "treatment_effects", tool = function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:lens") }) m <- conduct_step(lens) m@inferential_targetlens <- node("lens", emits = "treatment_effects", tool = function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:lens") }) m <- conduct_step(lens) m@inferential_target
A decision node turns a consensus and its supporting metrics into an action
recommendation. The headline "insufficient_evidence" is recorded as an
abstention.
decision_to_manifest( headline, emitter, method, metrics = list(), emitter_version = "0.0.0", run_id = NULL, consumed = list() )decision_to_manifest( headline, emitter, method, metrics = list(), emitter_version = "0.0.0", run_id = NULL, consumed = list() )
headline |
The recommended action, or |
emitter |
The name of the component or method family emitting the verdict. |
method |
A single string naming the method, conventionally
|
metrics |
A named list of scalars behind the verdict. |
emitter_version |
The emitting component's version string. |
run_id |
A run identifier, or |
consumed |
The upstream manifests the decision was derived from. Their lineage is recorded in the result. |
An orchestraManifest::orchestra_manifest with
inferential_target = "decisions".
Max Moldovan
lens <- lens_to_manifest("effect", TRUE, "ols", "ols:slope_t") d <- decision_to_manifest("apply_nitrogen", "agronomy", "agronomy:rule", metrics = list(rate_kg_ha = 90), consumed = list(lens)) d@summary$headline length(d@consumed_manifests)lens <- lens_to_manifest("effect", TRUE, "ols", "ols:slope_t") d <- decision_to_manifest("apply_nitrogen", "agronomy", "agronomy:rule", metrics = list(rate_kg_ha = 90), consumed = list(lens)) d@summary$headline length(d@consumed_manifests)
Builds the check run_return() applies to every value it would return
above dose 0. The check refuses a statistic computed on fewer than k
units, or one in which a single unit holds more than the dominance
share, when that information is present. A value that carries no unit
count is refused. Two scans follow: a value whose text holds one of the
forbidden strings is refused, and, when coord_bands is given, a
number that could be a coordinate is refused.
default_checker( k = 5, dominance = 0.6, forbidden = character(0), coord_bands = NULL )default_checker( k = 5, dominance = 0.6, forbidden = character(0), coord_bands = NULL )
k |
The smallest number of units a returned statistic may rest on. |
dominance |
The largest share of the statistic one unit may hold, between 0 and 1. |
forbidden |
Strings no returned value may contain, matched as written: the names of places and trials in the holder's table. |
coord_bands |
|
The unit count is read from the value's n_units attribute or, for a
column of a node's params table, from that table's n_units column.
The largest share of one unit is read the same way from
max_unit_share. A column passes only when every row passes;
run_return() calls the check on each row of a params field, so a
row that fails is withheld alone.
A number is coordinate-like when it lies inside one of coord_bands and
has more than two decimals. The scan applies to a value whose unit
attribute is missing, or names a coordinate (coordinate, degrees,
decimal_degrees, latitude, longitude, in any case). A value
declared in any other unit is not scanned: a rate in kg N/ha or a price
in $/ha can fall inside a band without being a place. run_return()
sets unit from the unit a request declares. There is no default band:
a band covering every latitude and longitude would refuse almost every
estimate, so the holder names the bands of the region the data come
from.
This check is a floor, not a disclosure guarantee. It does not detect a
statistic that reveals a unit through its own value, or a combination of
returns that does; differencing between rounds is checked by
run_return() against the previous round. The data holder remains
responsible for what leaves.
A function of one argument, the value, that returns
NA_character_ when the value may be returned and otherwise the
reason it may not: "no_unit_count", "too_few_units",
"dominant_unit", "forbidden_string" or "coordinate_like".
Max Moldovan
check <- default_checker(k = 5) check(structure(0.42, n_units = 12L)) check(structure(0.42, n_units = 3L)) check(0.42) scan <- default_checker(forbidden = "Roseworthy", coord_bands = list(c(-45, -10), c(110, 155))) scan(structure(138.6042, n_units = 12L)) scan(structure(138.6042, n_units = 12L, unit = "kg N/ha")) scan(structure("near Roseworthy", n_units = 12L))check <- default_checker(k = 5) check(structure(0.42, n_units = 12L)) check(structure(0.42, n_units = 3L)) check(0.42) scan <- default_checker(forbidden = "Roseworthy", coord_bands = list(c(-45, -10), c(110, 155))) scan(structure(138.6042, n_units = 12L)) scan(structure(138.6042, n_units = 12L, unit = "kg N/ha")) scan(structure("near Roseworthy", n_units = 12L))
Declare a typed edge
edge(from, contract = "any")edge(from, contract = "any")
from |
The id of the upstream node. |
contract |
The inferential target the upstream manifest must declare,
or |
A list with elements from and contract.
Max Moldovan
edge("lens", "treatment_effects")edge("lens", "treatment_effects")
A signal is declared before the run, in a table with one row per
trigger. Each trigger reads one statistic of one node, the metric
summary$metrics[[statistic]] of the manifest the node emitted, and fires
when the value compares with the threshold as its direction says.
evaluate_triggers(run, triggers)evaluate_triggers(run, triggers)
run |
A run returned by |
triggers |
A data frame with columns |
The trigger table with signal_type carrying its signal:
prefix, threshold as a number, and three added columns: value (the
statistic, or NA), fired (TRUE, FALSE, or NA when the trigger
could not be evaluated) and status ("evaluated", "node_not_run"
or "statistic_missing").
value is the statistic itself, a data value. It stays in the object
this function returns. run_record() and run_return() keep only
whether each trigger fired.
Max Moldovan
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:spread", metrics = list(spread = 1.6)) } run <- conduct(oap_plan(id = "sig", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) trig <- data.frame(trigger_id = "T_spread", node = "lens", class = "anomaly", signal_type = "lens_spread", statistic = "spread", direction = ">", threshold = 1.3, action = "return") evaluate_triggers(run, trig)[, c("trigger_id", "fired", "status")]lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:spread", metrics = list(spread = 1.6)) } run <- conduct(oap_plan(id = "sig", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) trig <- data.frame(trigger_id = "T_spread", node = "lens", class = "anomaly", signal_type = "lens_spread", statistic = "spread", direction = ">", threshold = 1.3, action = "return") evaluate_triggers(run, trig)[, c("trigger_id", "fired", "status")]
Turns a record into the message a composer reads: stop when every node
completed, was refused or was skipped by the plan's own rules with no
issue and no return trigger fired; otherwise one line <node id> <error word> per issue, then one line <trigger id> signal:<type> per
fired trigger whose action is return.
format_record(record)format_record(record)
record |
A record from |
A character vector of message lines.
Max Moldovan
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } run <- conduct(oap_plan(id = "ok", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) format_record(run_record(run))lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } run <- conduct(oap_plan(id = "ok", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) format_record(run_record(run))
Any method that answers "is there an effect?" on a shared question can take
part in a plan through this emitter: a kernel test, a classical regression
slope test, a rank correlation. The effect_present flag is what
triangulation reads; n, effect_mean and noise_sd, when supplied in
metrics, are what the abstention gate reads.
lens_to_manifest( headline, effect_present, emitter, method, metrics = list(), emitter_version = "0.0.0", run_id = NULL )lens_to_manifest( headline, effect_present, emitter, method, metrics = list(), emitter_version = "0.0.0", run_id = NULL )
headline |
The verdict label, such as |
effect_present |
Whether the method found an effect. |
emitter |
The name of the component or method family emitting the verdict. |
method |
A single string naming the method, conventionally
|
metrics |
A named list of scalars behind the verdict. |
emitter_version |
The emitting component's version string. |
run_id |
A run identifier, or |
An orchestraManifest::orchestra_manifest with
inferential_target = "treatment_effects".
Max Moldovan
decision_to_manifest(), conduct().
m <- lens_to_manifest("effect", TRUE, "ols", "ols:slope_t", metrics = list(p_value = 0.01, n = 136L)) m@summary$headline orchestraManifest::verify_manifest(m)$okm <- lens_to_manifest("effect", TRUE, "ols", "ols:slope_t", metrics = list(p_value = 0.01, n = 136L)) m@summary$headline orchestraManifest::verify_manifest(m)$ok
Builds an oap_node so a plan reads as a declaration. tool is either a
closure or a string reference; a string is stored as tool_ref and
resolved by resolve_tool() when the node runs.
node( id, tool = function(...) NULL, consumes = list(), emits = "any", operator = "compute", role = "compute", params = list(), when = "", foreach = NULL, foreach_max = 50L, on_refusal = "continue", returns = list(), triggers = list(), hypotheses = list() )node( id, tool = function(...) NULL, consumes = list(), emits = "any", operator = "compute", role = "compute", params = list(), when = "", foreach = NULL, foreach_max = 50L, on_refusal = "continue", returns = list(), triggers = list(), hypotheses = list() )
id |
A single non-empty string, unique within the plan. |
tool |
A closure |
consumes |
A list of edges, each as returned by |
emits |
The inferential target the node's output must declare, one of
|
operator |
One of |
role |
A free-text label for the component the node stands for. |
params |
A named list of operator parameters. A |
when |
A condition that must be |
foreach |
|
foreach_max |
The largest number of items a |
on_refusal |
What an abstaining result of this node does: |
returns |
As in oap_node, or a named vector of doses:
|
triggers, hypotheses
|
As in oap_node, or a data frame with one row per record. |
An oap_node.
Max Moldovan
lens <- node("lens", tool = "my_lens", emits = "treatment_effects") lens@tool_ref check <- node("check", tool = "my_check", emits = "treatment_effects", consumes = list(edge("lens", "treatment_effects")), when = "lens.metrics.p_value < 0.05", foreach = c("site_a", "site_b")) check@foreach gate <- node("gate", consumes = list(edge("lens", "treatment_effects")), emits = "decisions", operator = "abstain_gate", params = list(n_min = 25L)) gate@operatorlens <- node("lens", tool = "my_lens", emits = "treatment_effects") lens@tool_ref check <- node("check", tool = "my_check", emits = "treatment_effects", consumes = list(edge("lens", "treatment_effects")), when = "lens.metrics.p_value < 0.05", foreach = c("site_a", "site_b")) check@foreach gate <- node("gate", consumes = list(edge("lens", "treatment_effects")), emits = "decisions", operator = "abstain_gate", params = list(n_min = 25L)) gate@operator
One step of a plan, bound to a tool with the uniform signature
tool(inputs, data, node) that returns an
orchestraManifest::orchestra_manifest. The node declares which upstream
nodes it consumes, each with the contract it expects that input to carry,
and the inferential target its own output must declare.
oap_node( id = character(0), role = "compute", tool = function(...) NULL, tool_ref = "", consumes = list(), emits = "any", operator = "compute", params = list(), when = "", foreach = NULL, foreach_max = 50L, on_refusal = "continue", returns = list(), triggers = list(), hypotheses = list() )oap_node( id = character(0), role = "compute", tool = function(...) NULL, tool_ref = "", consumes = list(), emits = "any", operator = "compute", params = list(), when = "", foreach = NULL, foreach_max = 50L, on_refusal = "continue", returns = list(), triggers = list(), hypotheses = list() )
id |
A single non-empty string, unique within the plan. |
role |
A free-text label for the component the node stands for. |
tool |
The closure that performs the node, or an unused stand-in when
|
tool_ref |
A tool reference in one of the forms |
consumes |
A list of edges, each as returned by |
emits |
The inferential target the node's output must declare, one of
|
operator |
One of |
params |
A named list of operator parameters. A |
when |
A condition that must be |
foreach |
|
foreach_max |
The largest number of items a |
on_refusal |
What an abstaining result of this node does: |
returns |
The values the node may return, a list of records each
with |
triggers |
The node's declared signals, a list of records with the
columns of a trigger table (see |
hypotheses |
The hypotheses the node tests, a list of records each
with |
operator distinguishes ordinary computation from the two epistemic node
types the engine performs itself. A "compute" node calls its tool. An
"abstain_gate" node reads the one verdict it consumes and passes or
abstains, see conduct() for the policy. A "triangulate" node reconciles
every lens it consumes into one consensus.
A tool may be an in-session closure or a string reference that
resolve_tool() resolves when the node runs. The reference form is what
makes a plan portable, see plan_to_yaml().
A "select" node keeps the rows of its one input's params table that
meet params$rule, and emits them under the input's inferential target.
when, foreach, foreach_max and on_refusal are applied by
conduct(); see its sections for what each does. Node ids may not contain
dots, square brackets or white space, because conditions refer to nodes as
<node>.<field> and foreach instances are named <node>[<item>].
An oap_node object.
Max Moldovan
node() for the declarative constructor, oap_plan for the
plan.
n <- oap_node(id = "lens", emits = "treatment_effects") n@idn <- oap_node(id = "lens", emits = "treatment_effects") n@id
A plan is a list of oap_node objects with unique ids whose edges all
point at nodes within the plan. Acyclicity is checked when the plan is
ordered, see plan_order().
oap_plan(id = character(0), nodes = list(), meta = list(), inputs = list())oap_plan(id = character(0), nodes = list(), meta = list(), inputs = list())
id |
A single string naming the plan. |
nodes |
A list of oap_node objects. |
meta |
A named list of free-form metadata, such as the question the plan answers. Serialised with the plan. |
inputs |
The tables the plan reads and the postconditions each must
meet before the first node runs, a list of inputs as returned by
|
An oap_plan object.
Max Moldovan
conduct() to perform a plan, plan_to_yaml() to save one.
p <- oap_plan(id = "one_lens", nodes = list( node("lens", emits = "treatment_effects") )) plan_order(p)p <- oap_plan(id = "one_lens", nodes = list( node("lens", emits = "treatment_effects") )) plan_order(p)
A plan in language version 0.3 declares on each node what it may return
(returns), the signals it carries (triggers) and the hypotheses it
tests (hypotheses). These functions read the declarations into the
forms run_return() and evaluate_triggers() take, so a holder's runner
needs the plan file and nothing else.
plan_requests(plan) plan_returns(plan) plan_triggers(plan) plan_hypotheses(plan)plan_requests(plan) plan_returns(plan) plan_triggers(plan) plan_hypotheses(plan)
plan |
An oap_plan. |
plan_requests(): a list named by node id, each element a named
vector of the dose each requested field needs, as run_return(requests =) takes it; an empty list when nothing is requested.
plan_returns(): the same requests with what each declares besides
its dose, a data frame with one row per requested field and the
columns node, field, dose, unit, n_units_field and digits
(missing where not declared), which run_return(requests =) also
takes.
plan_triggers(): a trigger table as evaluate_triggers() takes it,
with the node column filled in. plan_hypotheses(): a data frame with
one row per hypothesis and the columns node, hypothesis_id,
statistic, direction, threshold, firing_plant and
silent_plant.
Max Moldovan
node(), run_return(), evaluate_triggers().
p <- oap_plan(id = "declared", nodes = list( node("lens", tool = "my_lens", emits = "treatment_effects", returns = c(slope = 1, "params.estimate" = 2), triggers = data.frame(trigger_id = "T_spread", class = "anomaly", signal_type = "lens_spread", statistic = "spread", direction = ">", threshold = 1.3, action = "return"), hypotheses = data.frame(hypothesis_id = "H_slope", statistic = "slope", direction = ">", threshold = 0, firing_plant = "slope of 0.3 planted", silent_plant = "flat response planted")))) plan_requests(p) plan_returns(p) plan_triggers(p) plan_hypotheses(p)p <- oap_plan(id = "declared", nodes = list( node("lens", tool = "my_lens", emits = "treatment_effects", returns = c(slope = 1, "params.estimate" = 2), triggers = data.frame(trigger_id = "T_spread", class = "anomaly", signal_type = "lens_spread", statistic = "spread", direction = ">", threshold = 1.3, action = "return"), hypotheses = data.frame(hypothesis_id = "H_slope", statistic = "slope", direction = ">", threshold = 0, firing_plant = "slope of 0.3 planted", silent_plant = "flat response planted")))) plan_requests(p) plan_returns(p) plan_triggers(p) plan_hypotheses(p)
The JSON spelling of a plan holds the same fields as the YAML spelling and
follows the schema returned by plan_schema(). A plan written as JSON,
for example as structured output from an AI model, can be read here and
saved as YAML with plan_to_yaml().
plan_from_json(path)plan_from_json(path)
path |
A file path, or a string of JSON text. |
An oap_plan. A plan with problems is an error that lists all of
them; see plan_validate().
Max Moldovan
plan_validate(), plan_from_yaml().
p <- plan_from_json('{ "id": "one_lens", "nodes": [ {"id": "lens", "tool": "my_lens", "emits": "treatment_effects"} ] }') plan_order(p)p <- plan_from_json('{ "id": "one_lens", "nodes": [ {"id": "lens", "tool": "my_lens", "emits": "treatment_effects"} ] }') plan_order(p)
Tool references are kept as strings and resolved when the plan is performed, so a plan loads without its tools present.
plan_from_yaml(path)plan_from_yaml(path)
path |
A file path, or a string of YAML text. |
The plan is checked by plan_validate() before it is built, and a plan
with problems is an error that lists all of them, including any unquoted
yes, no, on or off and any number in scientific notation.
An oap_plan.
Max Moldovan
plan_to_yaml(), plan_validate(), plan_from_json().
f <- system.file("scores", "dual_lens_gate.oap.yaml", package = "conductoR") p <- plan_from_yaml(f) plan_order(p)f <- system.file("scores", "dual_lens_gate.oap.yaml", package = "conductoR") p <- plan_from_yaml(f) plan_order(p)
The SHA-256 that conduct() records as plan_hash: the plan's nodes,
edges and parameters together with the code of every tool it references,
so editing a tool changes the hash as surely as editing the plan. A data
holder seals a plan by recording this hash before any run, and checks a
run against the seal with identical(run$plan_hash, seal).
plan_hash(plan)plan_hash(plan)
plan |
An oap_plan. |
Every tool the plan references by name must be registered, because its code enters the hash.
A string, "sha256:" followed by 64 hexadecimal digits.
Max Moldovan
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } p <- oap_plan(id = "sealed", nodes = list( node("lens", lens, emits = "treatment_effects"))) seal <- plan_hash(p) run <- conduct(p, verbose = FALSE) identical(run$plan_hash, seal)lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } p <- oap_plan(id = "sealed", nodes = list( node("lens", lens, emits = "treatment_effects"))) seal <- plan_hash(p) run <- conduct(p, verbose = FALSE) identical(run$plan_hash, seal)
An input is a table the plan's tools read, named as it is named in the
data passed to conduct(). Its postconditions are what the table must
satisfy before the first node runs; a table that fails one stops the run,
see the Input postconditions section of conduct().
plan_input(name, postconditions = character(0), key = NULL)plan_input(name, postconditions = character(0), key = NULL)
name |
The name of the table: an element of |
postconditions |
A character vector of conditions, named by their
ids (an unnamed condition is given the id |
key |
Columns whose combined values must be unique in every row and
never missing, or |
A list with name, key (when given) and postconditions, for
the inputs of an oap_plan.
Max Moldovan
check_postconditions(), conduct().
trials <- plan_input("trials", key = "trial_id", postconditions = c(P_rows = ".n_rows == 48", P_days = "window_days <= 31")) p <- oap_plan(id = "with_inputs", inputs = list(trials), nodes = list(node("fit", tool = "my_fit", emits = "parameters"))) cat(plan_to_yaml(p))trials <- plan_input("trials", key = "trial_id", postconditions = c(P_rows = ".n_rows == 48", P_days = "window_days <= 31")) p <- oap_plan(id = "with_inputs", inputs = list(trials), nodes = list(node("fit", tool = "my_fit", emits = "parameters"))) cat(plan_to_yaml(p))
Fetch a node by id
plan_node(plan, id)plan_node(plan, id)
plan |
An oap_plan. |
id |
The id of the node. |
The oap_node with that id. An unknown id is an error.
Max Moldovan
p <- oap_plan(id = "one", nodes = list(node("a"))) plan_node(p, "a")@idp <- oap_plan(id = "one", nodes = list(node("a"))) plan_node(p, "a")@id
Orders the nodes so that every node follows the nodes it consumes. A plan with a cycle is an error.
plan_order(plan)plan_order(plan)
plan |
An oap_plan. |
A character vector of node ids in execution order.
Max Moldovan
p <- oap_plan(id = "chain", nodes = list( node("b", consumes = list(edge("a"))), node("a") )) plan_order(p)p <- oap_plan(id = "chain", nodes = list( node("b", consumes = list(edge("a"))), node("a") )) plan_order(p)
The schema (JSON Schema 2020-12) describes every field a plan may hold,
its type and its allowed values. Editors can use it to check a plan as it
is written, and an AI model can use it to write a plan as structured
output. plan_validate() makes the same checks and adds those a schema
cannot express: references between nodes, cycles, the condition and
postcondition grammar, and ids unique across the plan. The schema of
language version 0.2 stays installed beside it.
plan_schema()plan_schema()
The path of the schema file, oap_plan_v0.3.schema.json.
Max Moldovan
s <- jsonlite::fromJSON(plan_schema(), simplifyVector = FALSE) names(s$properties)s <- jsonlite::fromJSON(plan_schema(), simplifyVector = FALSE) names(s$properties)
Every compute node must reference its tool by name (see node()), since
a closure cannot be written to a file. Operator nodes carry no tool.
plan_to_yaml(plan, path = NULL)plan_to_yaml(plan, path = NULL)
plan |
An oap_plan. |
path |
A file to write, or |
Every string is written in double quotes and every number in plain
decimal form, so the file reads back to the same plan. The line
plan_version: "0.3" is written when the plan uses a field added in
version 0.3: inputs on the plan, or returns, triggers or
hypotheses on a node. Otherwise plan_version: "0.2" is written only
when the plan uses a field added in version 0.2: when, foreach,
foreach_max, on_refusal or a select node.
path invisibly when a file was written, otherwise the YAML
text as a single string.
Max Moldovan
plan_from_yaml(), register_tool().
p <- oap_plan(id = "one_lens", nodes = list( node("lens", tool = "my_lens", emits = "treatment_effects"), node("gate", operator = "abstain_gate", emits = "decisions", consumes = list(edge("lens", "treatment_effects")), params = list(n_min = 25L)) )) cat(plan_to_yaml(p))p <- oap_plan(id = "one_lens", nodes = list( node("lens", tool = "my_lens", emits = "treatment_effects"), node("gate", operator = "abstain_gate", emits = "decisions", consumes = list(edge("lens", "treatment_effects")), params = list(n_min = 25L)) )) cat(plan_to_yaml(p))
Reads a plan written in YAML or JSON, or takes a plan object, and checks it against the plan language: the fields and their types, the operators and inferential targets, the condition grammar, and the references between nodes. Every problem is reported, not only the first, each with the field, the node, the rule it breaks and how to fix it. A person or an AI model can repair a plan from this table and check it again.
plan_validate(x)plan_validate(x)
x |
An oap_plan, the path of a |
In a YAML plan, an unquoted yes, no, on or off is refused: write
true or false for a logical, or quote the word for text. A number in
scientific notation (1e3) is refused with its plain form (1000). The
structure checks follow the JSON Schema returned by plan_schema().
A data frame with one row per problem and the columns field,
node (empty for a plan-level field), rule and fix. A valid plan
gives zero rows.
Max Moldovan
plan_schema(), plan_from_yaml(), plan_from_json().
f <- system.file("scores", "dual_lens_gate.oap.yaml", package = "conductoR") nrow(plan_validate(f)) plan_validate(' id: broken nodes: - id: gate operator: abstain_gate consumes: [{from: lens, contract: treatment_effects}] params: {mode: off, n_min: 1e3} ')f <- system.file("scores", "dual_lens_gate.oap.yaml", package = "conductoR") nrow(plan_validate(f)) plan_validate(' id: broken nodes: - id: gate operator: abstain_gate consumes: [{from: lens, contract: treatment_effects}] params: {mode: off, n_min: 1e3} ')
A registered tool can be referenced from a node by its name, which is what lets a plan be written to a file and performed again in another session. The registry is per session; a plan loaded from a file needs its tools registered again before it is performed.
register_tool(name, fn)register_tool(name, fn)
name |
A single string. |
fn |
A closure |
name, invisibly.
Max Moldovan
resolve_tool(), plan_to_yaml().
register_tool("always_effect", function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:constant") }) resolve_tool("always_effect")register_tool("always_effect", function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:constant") }) resolve_tool("always_effect")
Three reference forms are accepted. "<name>" is a tool registered with
register_tool(). "pkg::fn" is an exported function of an installed
package. "script:<path>::<fn>" sources an R script into a fresh
environment and returns the function it defines under that name; the
script runs with the privileges of the session, so only reference scripts
you would source yourself.
resolve_tool(ref)resolve_tool(ref)
ref |
A single string in one of the three forms. |
The function the reference names. An unknown reference is an error.
Max Moldovan
resolve_tool("stats::median")resolve_tool("stats::median")
A run's provenance as a table
run_provenance(run)run_provenance(run)
run |
The list returned by |
A data frame with one row per node in execution order and columns
node, operator, role, consumes (upstream ids joined with +),
emits, emitter, run_id, data_hash, abstained, seconds,
status (ran, refused or skipped) and reason (why a node was
skipped, the abstention reason of a node that refused, otherwise
empty). The provenance stays with the data holder; a record or a
return carries a refusal reason only when it is one of the words
listed in run_record().
When conduct() is given out_dir, it writes three files there:
run.rds (the whole run object), run_card.md (this table and the
terminal verdict) and provenance.md (a front-matter record with the chain
of node ids and payload hashes in execution order). When the run skipped
nodes, evaluated when conditions or ran foreach items, both Markdown
files list them with their reasons, values and statuses.
Max Moldovan
lens <- node("lens", emits = "treatment_effects", tool = function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:lens") }) run <- conduct(oap_plan(id = "one", nodes = list(lens)), verbose = FALSE) run_provenance(run)[, c("node", "emits", "abstained")]lens <- node("lens", emits = "treatment_effects", tool = function(inputs, data, node) { lens_to_manifest("effect", TRUE, "example", "example:lens") }) run <- conduct(oap_plan(id = "one", nodes = list(lens)), verbose = FALSE) run_provenance(run)[, c("node", "emits", "abstained")]
The record is what a run says about itself without giving away a data
value: one row per node with what it emitted and how it ended, and one
row per declared trigger with whether it fired. It is built from
run_provenance() and the manifests on the run's bus, and it keeps no
number, no headline and no free text from either.
run_record(run, triggers = NULL, checks = NULL)run_record(run, triggers = NULL, checks = NULL)
run |
A run returned by |
triggers |
A trigger table as described in |
checks |
A named list, keyed by node id, naming for each node the
metrics that are its checks; each such metric holds one |
A data frame with columns kind ("node", "trigger",
"input" for an input postcondition that stopped the run, with id
<input>.<postcondition id>, or "plan" when a run failed before any
node ran for another reason), id, emitter,
emits (for a trigger, its action), status, reason, abstained,
checks_passed and checks_failed (check names joined by ;).
A node's status is completed, refused (its result abstained),
skipped (by the plan's own rules), failed (it stopped with an
error) or not_run (the run stopped before it). Its reason holds the
issue words it reported, joined by ;, or NA.
A trigger's status is fired, silent or not_evaluated; its
emitter is the node it reads and its reason the signal type.
A node's reason is one or more of typed_edge_violation,
missing_column, type_mismatch, missing_block, too_few_units,
model_not_converged, unidentifiable_parameter,
assumption_check_failed and tool_error; the refusal words
licence_unavailable and credential_unavailable (the environment
cannot reach a licence or read a credential the tool needs); and the
shape words no_interior_minimum, no_interior_optimum and
no_response (a fitted curve has no turning point inside the observed
range, or no response at all). An input row reports
postcondition_failed: the table did not meet a postcondition the plan
declared for it, so no node ran. A completed node reports an
issue through summary$metrics$issue; a word outside this list is
recorded as tool_error. A refused node with no issue reports its
abstention reason when that reason is one of the words, and nothing
otherwise: a refusal the plan provided for is not a failure. A node that
stopped with an error reports the word try_conduct() gave it. A node
whose declared trigger statistic is missing reports tool_error.
Max Moldovan
format_record(), run_return(), evaluate_triggers().
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(issue = "model_not_converged", converged = FALSE)) } run <- conduct(oap_plan(id = "rec", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) run_record(run, checks = list(lens = "converged"))lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(issue = "model_not_converged", converged = FALSE)) } run <- conduct(oap_plan(id = "rec", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) run_record(run, checks = list(lens = "converged"))
Builds what leaves the data holder after a run: the dose-0 record and its
typed message lines, and, at dose 1 or above, the values the plan's
requests name, each passed through checker first. A value the checker
refuses, or one requested at a dose above the run's, is listed with the
reason and never returned.
run_return( run, triggers = NULL, dose = 0, requests = NULL, checker = default_checker(k = 5), series = NULL, round = NULL, checks = NULL, previous = NULL, k_diff = 10, digits = 7 )run_return( run, triggers = NULL, dose = 0, requests = NULL, checker = default_checker(k = 5), series = NULL, round = NULL, checks = NULL, previous = NULL, k_diff = 10, digits = 7 )
run |
A run returned by |
triggers |
A trigger table, as described in |
dose |
The dose of this return: 0 for the record alone, 1 or above for the record and the requested values up to that dose. |
requests |
A named list keyed by node id. Each element is a named
vector giving, for each requested field, the dose it needs, as in
|
checker |
A function of one value that returns |
series |
A short string naming the series of runs this return
belongs to, or |
round |
The round of the series, a whole number, or |
checks |
Passed to |
previous |
The earlier rounds of the series, each a return from
|
k_diff |
The smallest number of units a value changed since an
earlier round may rest on. Used only with |
digits |
The significant figures of returned numbers, unless a request declares its own. |
An object of class conductoR_return: a list with plan_id,
plan_hash, input_hash, series, round, dose, time, lines
(the typed message), record, values (one row per returned value:
node, field, dose, index, value as text), refused (one row
per requested field not returned, or per reason rows of a params
field were withheld: node, field, dose, reason, and n_rows,
the number of rows withheld for that reason, NA for a field refused
whole) and released (TRUE when a value was returned). It holds no trigger
value, no error message and nothing else from the run. Printing it
shows the text write_return() writes.
above_dose (the request needs a higher dose than the return),
node_refused (the node refused, so it returns its refusal in the record
and nothing else), not_available (the node did not run, has no such
field, or no row passes the row filter), differencing (see below), and
whatever reason the checker gives.
A params field is checked row by row: the checker sees each row with
its own unit count, a row it refuses is withheld, and the rows that pass
are returned with their row number as index. refused counts the
withheld rows by reason in n_rows and names none of them, so the
composer learns how many rows are missing and why, and not which. A
metric is checked whole. Withholding a row does not stop it being
solved from a released total and its released siblings: pass the
release through suppress_return() with the partitions it carries.
A request in the data-frame form, as plan_returns() reads it from the
plan, may declare more than its dose. unit is set as the value's unit
attribute before the checker sees it, so default_checker() scans a
rate or a price for coordinates only when it is declared as one.
n_units_field names the metric, or the params column, that holds the
unit count; when it is declared the count is read from there and nowhere
else, and a missing field is no count. Written <node>.<metric>, where
<node> is another node of the run, it names a metric of that node, as
in fidelity.n_trials; a node that did not run, or has no such metric,
gives no count. digits rounds the value's
numbers to that many significant figures, in place of digits.
A params field may carry a row filter, params.<column>[<key>=<value>],
with several values separated by commas. Only the rows whose key column
holds one of the values are returned, and the unit count is checked on
those rows alone, so rows of two kinds in one table are requested apart.
Given the earlier rounds of the series in previous, a value that passes
the checker is compared with the value returned in each of them under the
same node and field. When it changed since any of them, it is returned
only if every row rests on at least k_diff units; otherwise it is
refused as differencing, since the change between two rounds can reveal
the few units behind it. Comparing with every earlier round, not only the
last, closes the route through a round that withheld the value. A value
missing in both rounds is unchanged. A round that did not return the
field is not compared with. The rows of a params field are compared one by
one, by index: a changed row resting on fewer than k_diff units is
withheld as differencing and the other rows are returned, and a row
an earlier round did not return is not compared with that round.
Max Moldovan
run_record(), write_return(), series_report(),
plan_returns(), default_checker().
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.31, n_units = 24L), spread = structure(1.1, n_units = 3L))) } run <- conduct(oap_plan(id = "doses", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) ret <- run_return(run, dose = 1, series = "demo", round = 1, requests = list(lens = c(slope = 1, spread = 1))) ret$values ret$refusedlens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.31, n_units = 24L), spread = structure(1.1, n_units = 3L))) } run <- conduct(oap_plan(id = "doses", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) ret <- run_return(run, dose = 1, series = "demo", round = 1, requests = list(lens = c(slope = 1, spread = 1))) ret$values ret$refused
Compares the plan hashes and input hashes that conduct() records. The
plan hash covers the plan and the code of every tool it references, so
two runs with equal plan hashes ran the same analysis. Use it after a
blinded analysis: the blinded run and the unblinded run should share a
plan hash and differ in input hash.
same_plan(run_a, run_b)same_plan(run_a, run_b)
run_a, run_b
|
Two runs returned by |
A list with same_plan and same_input (logical), and the four
hashes and two labels compared.
Max Moldovan
lens <- function(inputs, data, node) { lens_to_manifest(if (mean(data$d) > 0) "effect" else "no_effect", mean(data$d) > 0, "demo", "demo:mean") } p <- oap_plan(id = "blind_demo", nodes = list( node("lens", lens, emits = "treatment_effects"))) d <- c(0.3, 0.1, 0.2, 0.4) flip <- c(1, -1, -1, 1) blinded <- conduct(p, data = list(d = d * flip), verbose = FALSE, label = "blinded") unblinded <- conduct(p, data = list(d = d), verbose = FALSE, label = "unblinded") same_plan(blinded, unblinded)$same_planlens <- function(inputs, data, node) { lens_to_manifest(if (mean(data$d) > 0) "effect" else "no_effect", mean(data$d) > 0, "demo", "demo:mean") } p <- oap_plan(id = "blind_demo", nodes = list( node("lens", lens, emits = "treatment_effects"))) d <- c(0.3, 0.1, 0.2, 0.4) flip <- c(1, -1, -1, 1) blinded <- conduct(p, data = list(d = d * flip), verbose = FALSE, label = "blinded") unblinded <- conduct(p, data = list(d = d), verbose = FALSE, label = "unblinded") same_plan(blinded, unblinded)$same_plan
Lists every round of one analysis from the returns written into its
series folder by write_return(): <series>/round_<k>/return.txt. A
round folder that holds no return is listed with its fields missing, so a
run that returned nothing still shows.
series_report(dir, budget = NULL)series_report(dir, budget = NULL)
dir |
The series folder. |
budget |
The number of returns above dose 0 the data holder allows
for the series, or |
A data frame of class conductoR_series with one row per round:
round, plan_hash, dose, n_lines and lines (the message, lines
joined by |), n_values (values returned), released and time.
The attributes n_above_dose_0, budget and within_budget carry the
count against the budget, which printing shows below the table.
Max Moldovan
write_return(), run_return(), same_plan().
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.31, n_units = 24L))) } run <- conduct(oap_plan(id = "s", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) dir <- file.path(tempdir(), "demo_rounds") write_return(run_return(run, series = "demo", round = 1), dir) write_return(run_return(run, dose = 1, series = "demo", round = 2, requests = list(lens = c(slope = 1))), dir) series_report(dir, budget = 3)lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.31, n_units = 24L))) } run <- conduct(oap_plan(id = "s", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) dir <- file.path(tempdir(), "demo_rounds") write_return(run_return(run, series = "demo", round = 1), dir) write_return(run_return(run, dose = 1, series = "demo", round = 2, requests = list(lens = c(slope = 1))), dir) series_report(dir, budget = 3)
Applies the rules that look across cells to the cells a release would
return, after each cell has passed its own checks in run_return(): a
withheld value must not follow from the released ones. Six rules run
until none changes a cell: by-design duplicates, identical cells,
complementary withholding over declared partitions, zero-width
intervals, derivation closure over declared links, and a route search
over identities, two-term arithmetic and count-weighted means. Every
rule fails closed: it withholds on doubt, and what it cannot break it
lists.
suppress_return( cells, partitions = NULL, links = NULL, groups = NULL, seen = NULL, bounds = NULL, primary = NULL, k = 5, k_obs = 5, dominance = 0.6, route_limit = 200 )suppress_return( cells, partitions = NULL, links = NULL, groups = NULL, seen = NULL, bounds = NULL, primary = NULL, k = 5, k_obs = 5, dominance = 0.6, route_limit = 200 )
cells |
The cells of the release, as described below. |
partitions |
|
links |
|
groups |
|
seen |
|
bounds |
|
primary |
|
k |
The fewest units a complement may rest on. |
k_obs |
The fewest observations a complement may rest on, when the node carries observation counts. |
dominance |
The largest share of a complement's observations one unit may hold, between 0 and 1. |
route_limit |
The most candidates the route search examines for one withheld value, a whole number of at least 1. |
This is a floor, not a disclosure guarantee. It finds the routes it is
told to look for, from the structure the holder declares; a route
through a link nobody declared, or through values outside cells, is
not found. The data holder remains responsible for what leaves.
A list: cells (the input with status as the rules leave it,
and rule and detail for each cell a rule changed), changes (the
changed cells: node, payload, field, unit, status, rule,
detail), unbreakable (node, payload, field, unit, route:
withheld values that still follow from pinned values) and limit
(node, payload, field, unit, n_candidates: withheld values
the route search did not search). rule is one of complement,
derivation, identical_cell, zero_width, duplicate, route and
route_limit.
cells holds one row per value of the release, with the columns node,
field, unit (the row of the node's table the value sits in; "" for
a metric), value (numeric; a missing value is never a route) and
status ("released" or "withheld", as the per-cell checks left it).
Optional columns: payload ("params" when absent, "metrics" for a
metric), and the counts of the unit's row, n_units (the units the
value rests on: trials, in a trial series), n_obs (its observations:
plots) and max_unit_share (the largest share of the observations one unit
holds). Counts are the same on every row of one node and unit, and are
treated as public.
partitions declares which rows are sub-cells of which: one row per
sub-cell, with the columns parent and child, and optionally
partition (an id, since one parent may be split by state and again by
year; default the parent), units_additive and
obs_additive (whether the sub-cells' unit and observation counts add
up to a part of the parent's; default TRUE) and node (the node it
applies to; missing for every node). Sub-cells of the rates of one set
of trials hold the same trials, so their units do not add while their
observations do.
For a released parent field, the complement is the parent minus its
released sub-cells. It breaches when it is exactly one withheld sub-cell,
rests on fewer than k units, or, when the node carries observation
counts, fewer than k_obs observations or a possible share above
dominance for the parent's largest unit. When units do not add, the
complement's units are bounded below by its largest sub-cell. A breach
withholds one more released sub-cell: a sub-cell that is no parent
first, then the fewest units, then by name. With none left to withhold,
the parent is withheld. A missing count is a breach.
A parent whose additive partition has exactly one sub-cell with units is
the same data as that sub-cell: a field withheld in either is withheld in
both (identical_cell).
links declares arithmetic between fields: one row per member, with the
columns link (an id), type ("sum", "difference", "ratio" or
"identity"), node, field and unit, and optionally payload. A
unit written "<u>" is free: the link holds at every unit of the cells.
An identity has two members, a difference and a ratio three, a sum at
least three. When every member of a link but one is released and that
one is withheld, every released member is withheld (derivation).
A withheld value whose released bounds at the same node and unit equal
each other and the value has both bounds withheld (zero_width). The
bounds of a field f are f_lo and f_hi, unless bounds names
others (columns field, lo, hi).
groups declares values that are one value by design (columns group,
node, field, unit, optionally payload). A group with a member in
seen, the cells an earlier return released, and a member released now
is released on every row and pinned: it is never withheld, since it has
already left. Any other group withheld on some rows is withheld on every
row (duplicate).
The route search looks, for every withheld value, among the released
values at its unit, at the units whose row is identical to its row in
its node, at the top parents of the partitions and among the metrics: a
value equal to one of them, or, for a value that is not a whole number,
to a sum, difference, product or ratio of two; and a withheld parent
equal to the unit- or observation-weighted mean of its released
sub-cells, or a withheld sub-cell solved from its released parent and
siblings (relative tolerance 1e-9). A smallest set of released values
that breaks every route is withheld, chosen greedily (most routes per
cost; cost 100 for a primary field, else 1; ties to a sub-cell that is
no parent, then by name), and the search repeats, since a newly
withheld value can have routes of its own (route). A withheld value
with more than route_limit candidates is not searched: every candidate
is withheld (route_limit) and the value is logged in limit. A route
made only of pinned values cannot be broken: it is listed in
unbreakable, and so is a complement or link that only a pinned value
could break.
Max Moldovan
run_return(), default_checker().
# A parent of 20 units over three sub-cells; c rests on too few units cells <- data.frame(node = "fit", field = "estimate", unit = c("all", "a", "b", "c"), value = c(1.11, 1.37, 0.92, 1.04), status = c("released", "released", "released", "withheld"), n_units = c(20, 8, 7, 5)) parts <- data.frame(parent = "all", child = c("a", "b", "c")) res <- suppress_return(cells, partitions = parts) res$changes # yield = biomass - straw at every unit cells <- data.frame(node = "fit", field = c("yield", "straw", "biomass"), unit = "site_1", value = c(2.13, 3.07, 5.2), status = c("withheld", "released", "released")) links <- data.frame(link = "biomass", type = "sum", node = "fit", field = c("yield", "straw", "biomass"), unit = "<u>") suppress_return(cells, links = links)$changes# A parent of 20 units over three sub-cells; c rests on too few units cells <- data.frame(node = "fit", field = "estimate", unit = c("all", "a", "b", "c"), value = c(1.11, 1.37, 0.92, 1.04), status = c("released", "released", "released", "withheld"), n_units = c(20, 8, 7, 5)) parts <- data.frame(parent = "all", child = c("a", "b", "c")) res <- suppress_return(cells, partitions = parts) res$changes # yield = biomass - straw at every unit cells <- data.frame(node = "fit", field = c("yield", "straw", "biomass"), unit = "site_1", value = c(2.13, 3.07, 5.2), status = c("withheld", "released", "released")) links <- data.frame(link = "biomass", type = "sum", node = "fit", field = c("yield", "straw", "biomass"), unit = "<u>") suppress_return(cells, links = links)$changes
The target that holds a plan's terminal result
terminal_target(plan)terminal_target(plan)
plan |
An oap_plan. |
The name of the target, as a string, that
compile_to_targets() maps the last node in topological order to.
Max Moldovan
p <- oap_plan(id = "chain", nodes = list( node("b", consumes = list(edge("a"))), node("a") )) terminal_target(p)p <- oap_plan(id = "chain", nodes = list( node("b", consumes = list(edge("a"))), node("a") )) terminal_target(p)
Checks a report before it is released. A composer that never saw a
number writes each one as a reference to a value of the release,
{{<node>:<field>}}, and trace_report() enters the value. Any number
written out in the text is matched against the release's values at the
digits shown. A reference to a value the release does not hold, or a
number that matches no value and was not declared in allow, blocks the
release: the result then carries no text, only the trace saying why.
trace_report(report, ret, allow = NULL, run = NULL)trace_report(report, ret, allow = NULL, run = NULL)
report |
The report: its text, as one string or a vector of lines, or the path of a text file. |
ret |
The release the report draws on: a return from |
allow |
Numbers the report may show that are not results of the
run, for example the confidence level of an interval. Each is listed in
the trace as |
run |
The run the release was built from, or |
An object of class conductoR_trace: a list with text (the
report with every reference replaced by its value, or NA when the
release is blocked), trace (one row per reference and per number
written out, see below), released (TRUE when every number traced),
plan_hash and input_hash (those of the release).
A reference names a row of the release's values: {{fit:slope}} for
the value of a metric, {{fit:params.estimate:3}} for the third row of a
params field. The index may be left out only when the field returned a
single value. The value is entered as the release holds it, at the
significant figures the plan declared. A number the report needs in
another form, for example a difference, is added to the plan as a node.
Columns item, line (of the report), kind (reference or
literal), shown (the text in the report), status, reason,
node, field, index, value (the text entered or matched),
n_matches (values a literal number matched), emitter and
emitter_version.
status is filled (a reference resolved), matched (a number written
out equals at least one value of the release at the digits shown; the
first is named), declared (the number is in allow), unresolved (a
reference the release does not hold; reason is the reason the value
was refused, not_in_return or index_needed) or untraced (a number
that matches no value; reason is no_match). Either of the last two
blocks the release.
A run of digits, with an optional sign, decimal part, exponent and
thousands separators, that is not part of a word: H1, v0.3 and
round_2 are not numbers, while the 95 of 95% and both years of
2008-2017 are. A number equals a value at the digits shown when the
value, rounded to the number of decimals written, is that number.
Max Moldovan
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.3127, n_units = 24L))) } run <- conduct(oap_plan(id = "traced", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) ret <- run_return(run, dose = 1, requests = list(lens = c(slope = 1))) # a reference is filled in; 95 is declared, 0.31 matches the slope tr <- trace_report(c("The slope was {{lens:slope}} t/ha per 10 units", "(0.31 rounded, 95% interval in the appendix)."), ret, allow = c(10, 95)) tr$text tr$trace[, c("shown", "status", "node", "field")] # a number that matches nothing blocks the release trace_report("The slope was 0.42.", ret)$releasedlens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens", metrics = list(slope = structure(0.3127, n_units = 24L))) } run <- conduct(oap_plan(id = "traced", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) ret <- run_return(run, dose = 1, requests = list(lens = c(slope = 1))) # a reference is filled in; 95 is declared, 0.31 matches the slope tr <- trace_report(c("The slope was {{lens:slope}} t/ha per 10 units", "(0.31 rounded, 95% interval in the appendix)."), ret, allow = c(10, 95)) tr$text tr$trace[, c("shown", "status", "node", "field")] # a number that matches nothing blocks the release trace_report("The slope was 0.42.", ret)$released
Calls conduct() with the same arguments. When the run completes, the
result is the run itself. When a node stops with an error, the result is
a failed run: the nodes performed before the error, with their manifests,
the node that failed and the typed error word for the failure. The
failed run is accepted by run_record() and run_return(), so a run that
stops still returns a typed message to the composer.
try_conduct(plan, data = list(), ...)try_conduct(plan, data = list(), ...)
plan |
An oap_plan. |
data |
The data object every tool receives. |
... |
Further arguments to |
The error word is the condition's class when that class is one of the
words listed in run_record(); else the word before a colon that starts
the error message (stop("missing_block: site S3 has no plots")); else
typed_edge_violation for a contract failure at an edge; else
tool_error. The error message itself is kept in failed$message for
the data holder and never enters a record or a return.
The run returned by conduct(), or a failed run: a list with
plan_id, plan_hash, input_hash, label, bus and provenance
(the nodes performed before the error), not_run (the ids of the
nodes not reached) and failed, a list with node (the id of the node
that failed, or "plan" when the error came before any node ran),
error_type, message and postconditions (the <input>.<id> of
each input postcondition that failed, when that stopped the run).
Max Moldovan
broken <- function(inputs, data, node) { stop("missing_column: the table has no column 'yield'") } p <- oap_plan(id = "fails", nodes = list( node("fit", broken, emits = "parameters"))) run <- try_conduct(p, verbose = FALSE) run$failed$error_type format_record(run_record(run))broken <- function(inputs, data, node) { stop("missing_column: the table has no column 'yield'") } p <- oap_plan(id = "fails", nodes = list( node("fit", broken, emits = "parameters"))) run <- try_conduct(p, verbose = FALSE) run$failed$error_type format_record(run_record(run))
Writes the text of a return: a header with the plan id, plan_hash,
input_hash, series, round, dose, whether a value was released and the
time the return was built, then the sections [message], [record],
[values] and [refused], the last three as CSV.
write_return(ret, path)write_return(ret, path)
ret |
A return from |
path |
A series folder, or a file path ending in |
The path of the file written, invisibly.
The rounds of one analysis share a folder, one sub-folder per round:
<series>/round_<k>/return.txt. Give path as the series folder and the
file goes to the sub-folder of the return's round; give a path ending in
.txt to write that file instead. series_report() reads a series
folder back. A return already written is never replaced: writing to an
existing file is an error.
Max Moldovan
run_return(), series_report().
lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } run <- conduct(oap_plan(id = "w", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) dir <- file.path(tempdir(), "demo_series") f <- write_return(run_return(run, series = "demo", round = 1), dir) readLines(f)[1:9] series_report(dir)lens <- function(inputs, data, node) { lens_to_manifest("effect", TRUE, "demo", "demo:lens") } run <- conduct(oap_plan(id = "w", nodes = list( node("lens", lens, emits = "treatment_effects"))), verbose = FALSE) dir <- file.path(tempdir(), "demo_series") f <- write_return(run_return(run, series = "demo", round = 1), dir) readLines(f)[1:9] series_report(dir)