Package 'conductoR'

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

Help Index


Check a table against its postconditions

Description

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.

Usage

check_postconditions(x, conditions, input = "input", key = NULL)

Arguments

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 are checked.

input

The name of the input in the plan, or a label for x in the messages when conditions is a vector.

key

Columns whose combined values must be unique and never missing, or NULL. Ignored when conditions is a plan, which carries its own.

Value

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.

The grammar

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.

Author(s)

Max Moldovan

See Also

plan_input(), conduct().

Examples

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)

Compile a plan to a targets script

Description

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_.

Usage

compile_to_targets(plan, script_file, preamble = character(0))

Arguments

plan

An oap_plan.

script_file

The path to write.

preamble

Lines of R placed at the top of the script. They must bind .score to the plan and .data to the data object, and make any registered tools available in the process that runs the pipeline.

Details

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.

Value

script_file, invisibly.

Author(s)

Max Moldovan

See Also

terminal_target(), conduct_step().

Examples

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")

Perform a plan

Description

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.

Usage

conduct(plan, data = list(), out_dir = NULL, verbose = TRUE, label = NULL)

Arguments

plan

An oap_plan.

data

The data object every tool receives.

out_dir

A directory to write the provenance record into, or NULL to write nothing. See run_provenance() for the files.

verbose

Print one line per node as it runs.

label

A short string stored with the run, such as "blinded" or "unblinded", or NULL.

Value

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.

The abstention gate

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.

Triangulation

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).

Conditions

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.

Running a node once per item

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.

Refusals

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.

Input postconditions

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.

Blinded runs

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.

Author(s)

Max Moldovan

See Also

conduct_step(), run_provenance(), plan_to_yaml(), same_plan().

Examples

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$items

Perform one node

Description

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.

Usage

conduct_step(node, inputs = list(), data = list())

Arguments

node

An oap_node.

inputs

A named list of upstream manifests, one per edge in node@consumes, named by the upstream node id.

data

The data object every tool receives as its second argument.

Value

The orchestraManifest::orchestra_manifest the node emitted.

Errors

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.

Author(s)

Max Moldovan

See Also

conduct().

Examples

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_target

Lift a decision into a decisions manifest

Description

A decision node turns a consensus and its supporting metrics into an action recommendation. The headline "insufficient_evidence" is recorded as an abstention.

Usage

decision_to_manifest(
  headline,
  emitter,
  method,
  metrics = list(),
  emitter_version = "0.0.0",
  run_id = NULL,
  consumed = list()
)

Arguments

headline

The recommended action, or "insufficient_evidence".

emitter

The name of the component or method family emitting the verdict.

method

A single string naming the method, conventionally "component:method".

metrics

A named list of scalars behind the verdict.

emitter_version

The emitting component's version string.

run_id

A run identifier, or NULL to derive one from the verdict.

consumed

The upstream manifests the decision was derived from. Their lineage is recorded in the result.

Value

An orchestraManifest::orchestra_manifest with inferential_target = "decisions".

Author(s)

Max Moldovan

See Also

lens_to_manifest().

Examples

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)

A floor on what a returned statistic may rest on

Description

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.

Usage

default_checker(
  k = 5,
  dominance = 0.6,
  forbidden = character(0),
  coord_bands = NULL
)

Arguments

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

NULL for no coordinate scan, or a list of bands, each a numeric vector of a lower and an upper bound. list(c(-45, -10), c(110, 155)) covers the latitudes and longitudes of south-eastern Australia.

Details

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.

Value

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".

Author(s)

Max Moldovan

See Also

run_return().

Examples

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

Description

Declare a typed edge

Usage

edge(from, contract = "any")

Arguments

from

The id of the upstream node.

contract

The inferential target the upstream manifest must declare, or "any" to accept every target.

Value

A list with elements from and contract.

Author(s)

Max Moldovan

See Also

node().

Examples

edge("lens", "treatment_effects")

Evaluate the declared signals of a run

Description

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.

Usage

evaluate_triggers(run, triggers)

Arguments

run

A run returned by conduct() or try_conduct().

triggers

A data frame with columns trigger_id, node, class ("anomaly" or "candidate"), signal_type (a lower-case word, written with or without the prefix ⁠signal:⁠), statistic, direction (>, >=, <, <= or ==), threshold, action ("return", "branch" or "release") and, optionally, rehearsal_plant (what was planted in rehearsal to show the trigger fires). Columns may be character, as read from a CSV file.

Value

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").

What stays with the data holder

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.

Author(s)

Max Moldovan

See Also

run_record(), run_return().

Examples

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")]

The typed message lines of a record

Description

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.

Usage

format_record(record)

Arguments

record

A record from run_record().

Value

A character vector of message lines.

Author(s)

Max Moldovan

See Also

run_record(), run_return().

Examples

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))

Lift a binary verdict into a treatment-effects manifest

Description

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.

Usage

lens_to_manifest(
  headline,
  effect_present,
  emitter,
  method,
  metrics = list(),
  emitter_version = "0.0.0",
  run_id = NULL
)

Arguments

headline

The verdict label, such as "effect" or "no_effect".

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 "component:method".

metrics

A named list of scalars behind the verdict.

emitter_version

The emitting component's version string.

run_id

A run identifier, or NULL to derive one from the verdict.

Value

An orchestraManifest::orchestra_manifest with inferential_target = "treatment_effects".

Author(s)

Max Moldovan

See Also

decision_to_manifest(), conduct().

Examples

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)$ok

Declare a node

Description

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.

Usage

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()
)

Arguments

id

A single non-empty string, unique within the plan.

tool

A closure ⁠function(inputs, data, node)⁠ returning an orchestraManifest::orchestra_manifest, or a string reference in one of the forms resolve_tool() accepts.

consumes

A list of edges, each as returned by edge().

emits

The inferential target the node's output must declare, one of orchestraManifest::inferential_targets() or "any".

operator

One of "compute", "abstain_gate", "triangulate" or "select".

role

A free-text label for the component the node stands for.

params

A named list of operator parameters. A "select" node needs rule, a row condition written in the grammar described in conduct().

when

A condition that must be TRUE for the node to run, or "" to always run it. See the Conditions section of conduct().

foreach

NULL to run the node once; a list of items to run it once per item; or ⁠list(from = <node id>, column = <name>)⁠ to take the items from a column of the params table of a node this node consumes.

foreach_max

The largest number of items a foreach may run. More items stop the run with an error.

on_refusal

What an abstaining result of this node does: "continue" passes it on, "halt-branch" skips every node downstream, "stop" ends the run.

returns

As in oap_node, or a named vector of doses: c(slope = 1, "params.estimate" = 2).

triggers, hypotheses

As in oap_node, or a data frame with one row per record.

Value

An oap_node.

Author(s)

Max Moldovan

See Also

edge(), oap_plan.

Examples

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@operator

A node of an analytical plan

Description

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.

Usage

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()
)

Arguments

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 is set.

tool_ref

A tool reference in one of the forms resolve_tool() accepts, or "" for an in-session closure.

consumes

A list of edges, each as returned by edge().

emits

The inferential target the node's output must declare, one of orchestraManifest::inferential_targets() or "any".

operator

One of "compute", "abstain_gate", "triangulate" or "select".

params

A named list of operator parameters. A "select" node needs rule, a row condition written in the grammar described in conduct().

when

A condition that must be TRUE for the node to run, or "" to always run it. See the Conditions section of conduct().

foreach

NULL to run the node once; a list of items to run it once per item; or ⁠list(from = <node id>, column = <name>)⁠ to take the items from a column of the params table of a node this node consumes.

foreach_max

The largest number of items a foreach may run. More items stop the run with an error.

on_refusal

What an abstaining result of this node does: "continue" passes it on, "halt-branch" skips every node downstream, "stop" ends the run.

returns

The values the node may return, a list of records each with field (a metric, or ⁠params.<column>⁠) and dose (a whole number of at least 1), and optionally unit and n_units_field. Read by plan_requests().

triggers

The node's declared signals, a list of records with the columns of a trigger table (see evaluate_triggers()) other than node. Read by plan_triggers().

hypotheses

The hypotheses the node tests, a list of records each with hypothesis_id, statistic, direction, threshold, firing_plant and silent_plant (what rehearsal planted to show the rule fires and stays silent). Read by plan_hypotheses().

Details

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>]⁠.

Value

An oap_node object.

Author(s)

Max Moldovan

See Also

node() for the declarative constructor, oap_plan for the plan.

Examples

n <- oap_node(id = "lens", emits = "treatment_effects")
n@id

An analytical plan

Description

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().

Usage

oap_plan(id = character(0), nodes = list(), meta = list(), inputs = list())

Arguments

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 plan_input(). See the Input postconditions section of conduct().

Value

An oap_plan object.

Author(s)

Max Moldovan

See Also

conduct() to perform a plan, plan_to_yaml() to save one.

Examples

p <- oap_plan(id = "one_lens", nodes = list(
  node("lens", emits = "treatment_effects")
))
plan_order(p)

The values, triggers and hypotheses a plan declares

Description

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.

Usage

plan_requests(plan)

plan_returns(plan)

plan_triggers(plan)

plan_hypotheses(plan)

Arguments

plan

An oap_plan.

Value

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.

Author(s)

Max Moldovan

See Also

node(), run_return(), evaluate_triggers().

Examples

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)

Read a plan from JSON

Description

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().

Usage

plan_from_json(path)

Arguments

path

A file path, or a string of JSON text.

Value

An oap_plan. A plan with problems is an error that lists all of them; see plan_validate().

Author(s)

Max Moldovan

See Also

plan_validate(), plan_from_yaml().

Examples

p <- plan_from_json('{
  "id": "one_lens",
  "nodes": [
    {"id": "lens", "tool": "my_lens", "emits": "treatment_effects"}
  ]
}')
plan_order(p)

Read a plan from YAML

Description

Tool references are kept as strings and resolved when the plan is performed, so a plan loads without its tools present.

Usage

plan_from_yaml(path)

Arguments

path

A file path, or a string of YAML text.

Details

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.

Value

An oap_plan.

Author(s)

Max Moldovan

See Also

plan_to_yaml(), plan_validate(), plan_from_json().

Examples

f <- system.file("scores", "dual_lens_gate.oap.yaml", package = "conductoR")
p <- plan_from_yaml(f)
plan_order(p)

The hash of a plan

Description

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).

Usage

plan_hash(plan)

Arguments

plan

An oap_plan.

Details

Every tool the plan references by name must be registered, because its code enters the hash.

Value

A string, "sha256:" followed by 64 hexadecimal digits.

Author(s)

Max Moldovan

See Also

same_plan(), conduct().

Examples

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)

Declare an input of a plan

Description

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().

Usage

plan_input(name, postconditions = character(0), key = NULL)

Arguments

name

The name of the table: an element of data when data is a list, or "data" for data itself when it is a data frame.

postconditions

A character vector of conditions, named by their ids (an unnamed condition is given the id ⁠P<n>⁠), written in the grammar described in check_postconditions().

key

Columns whose combined values must be unique in every row and never missing, or NULL.

Value

A list with name, key (when given) and postconditions, for the inputs of an oap_plan.

Author(s)

Max Moldovan

See Also

check_postconditions(), conduct().

Examples

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

Description

Fetch a node by id

Usage

plan_node(plan, id)

Arguments

plan

An oap_plan.

id

The id of the node.

Value

The oap_node with that id. An unknown id is an error.

Author(s)

Max Moldovan

Examples

p <- oap_plan(id = "one", nodes = list(node("a")))
plan_node(p, "a")@id

Topological order of a plan

Description

Orders the nodes so that every node follows the nodes it consumes. A plan with a cycle is an error.

Usage

plan_order(plan)

Arguments

plan

An oap_plan.

Value

A character vector of node ids in execution order.

Author(s)

Max Moldovan

Examples

p <- oap_plan(id = "chain", nodes = list(
  node("b", consumes = list(edge("a"))),
  node("a")
))
plan_order(p)

The JSON Schema of the plan language

Description

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.

Usage

plan_schema()

Value

The path of the schema file, oap_plan_v0.3.schema.json.

Author(s)

Max Moldovan

See Also

plan_validate().

Examples

s <- jsonlite::fromJSON(plan_schema(), simplifyVector = FALSE)
names(s$properties)

Write a plan as YAML

Description

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.

Usage

plan_to_yaml(plan, path = NULL)

Arguments

plan

An oap_plan.

path

A file to write, or NULL to return the YAML text.

Details

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.

Value

path invisibly when a file was written, otherwise the YAML text as a single string.

Author(s)

Max Moldovan

See Also

plan_from_yaml(), register_tool().

Examples

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))

Check a plan and list every problem

Description

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.

Usage

plan_validate(x)

Arguments

x

An oap_plan, the path of a .yaml, .yml or .json plan file, or the plan's text. Text that starts with an opening brace is read as JSON. A plan object is checked as the plan it would write; a compute node that carries an inline function is checked as if it named a tool.

Details

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().

Value

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.

Author(s)

Max Moldovan

See Also

plan_schema(), plan_from_yaml(), plan_from_json().

Examples

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}
')

Register a tool by name

Description

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.

Usage

register_tool(name, fn)

Arguments

name

A single string.

fn

A closure ⁠function(inputs, data, node)⁠ returning an orchestraManifest::orchestra_manifest.

Value

name, invisibly.

Author(s)

Max Moldovan

See Also

resolve_tool(), plan_to_yaml().

Examples

register_tool("always_effect", function(inputs, data, node) {
  lens_to_manifest("effect", TRUE, "example", "example:constant")
})
resolve_tool("always_effect")

Resolve a tool reference

Description

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.

Usage

resolve_tool(ref)

Arguments

ref

A single string in one of the three forms.

Value

The function the reference names. An unknown reference is an error.

Author(s)

Max Moldovan

See Also

register_tool().

Examples

resolve_tool("stats::median")

A run's provenance as a table

Description

A run's provenance as a table

Usage

run_provenance(run)

Arguments

run

The list returned by conduct().

Value

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().

Files

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.

Author(s)

Max Moldovan

See Also

conduct().

Examples

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 dose-0 record of a run

Description

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.

Usage

run_record(run, triggers = NULL, checks = NULL)

Arguments

run

A run returned by conduct() or try_conduct().

triggers

A trigger table as described in evaluate_triggers(), evaluated or not, or NULL.

checks

A named list, keyed by node id, naming for each node the metrics that are its checks; each such metric holds one TRUE (passed) or FALSE. A node may also declare its own checks as a named logical vector in summary$metrics$checks. NULL for none.

Value

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.

The error words

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.

Author(s)

Max Moldovan

See Also

format_record(), run_return(), evaluate_triggers().

Examples

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"))

The message a run returns to the composer

Description

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.

Usage

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
)

Arguments

run

A run returned by conduct() or try_conduct().

triggers

A trigger table, as described in evaluate_triggers(), or NULL.

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 list(quorum = c(width_ratio = 1, "params.estimate" = 2)). A field is a metric of the node's summary$metrics, written bare or as ⁠metrics.<name>⁠, or a column of its params table, written ⁠params.<column>⁠. Or a data frame with the columns node, field and dose, and optionally unit, n_units_field and digits, as plan_returns() gives it.

checker

A function of one value that returns NA_character_ when the value may be returned, else the reason it may not. See default_checker().

series

A short string naming the series of runs this return belongs to, or NULL.

round

The round of the series, a whole number, or NULL.

checks

Passed to run_record().

previous

The earlier rounds of the series, each a return from run_return() or the path of one written by write_return(): one of them, a list of them, or a character vector of paths. NULL for no differencing.

k_diff

The smallest number of units a value changed since an earlier round may rest on. Used only with previous.

digits

The significant figures of returned numbers, unless a request declares its own.

Value

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.

Reasons a value is not returned

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.

Rows of a params field

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.

Declared fields

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.

Differencing across rounds

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.

Author(s)

Max Moldovan

See Also

run_record(), write_return(), series_report(), plan_returns(), default_checker().

Examples

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$refused

Check that two runs used the same plan

Description

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.

Usage

same_plan(run_a, run_b)

Arguments

run_a, run_b

Two runs returned by conduct().

Value

A list with same_plan and same_input (logical), and the four hashes and two labels compared.

Author(s)

Max Moldovan

See Also

conduct().

Examples

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_plan

Report the rounds of a series

Description

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.

Usage

series_report(dir, budget = NULL)

Arguments

dir

The series folder.

budget

The number of returns above dose 0 the data holder allows for the series, or NULL for no budget. The budget is the holder's number; the report only counts against it.

Value

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.

Author(s)

Max Moldovan

See Also

write_return(), run_return(), same_plan().

Examples

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)

Secondary suppression of a release

Description

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.

Usage

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
)

Arguments

cells

The cells of the release, as described below.

partitions

NULL, or the declared partitions, as described below.

links

NULL, or the declared links, as described below.

groups

NULL, or the by-design duplicates.

seen

NULL, or the cells an earlier return released (columns node, field, unit, optionally payload).

bounds

NULL, or a table of the bounds of fields whose bounds are not named ⁠<field>_lo⁠ and ⁠<field>_hi⁠.

primary

NULL, or the fields kept longest by the route search (columns node, field).

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.

Details

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.

Value

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

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

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

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).

Bounds, duplicates and the route search

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.

Author(s)

Max Moldovan

See Also

run_return(), default_checker().

Examples

# 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

Description

The target that holds a plan's terminal result

Usage

terminal_target(plan)

Arguments

plan

An oap_plan.

Value

The name of the target, as a string, that compile_to_targets() maps the last node in topological order to.

Author(s)

Max Moldovan

See Also

compile_to_targets().

Examples

p <- oap_plan(id = "chain", nodes = list(
  node("b", consumes = list(edge("a"))),
  node("a")
))
terminal_target(p)

Trace every number in a report to the release it came from

Description

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.

Usage

trace_report(report, ret, allow = NULL, run = NULL)

Arguments

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 run_return() or the path of one written by write_return().

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 declared. A numeric or character vector, or NULL.

run

The run the release was built from, or NULL. When given, the version of the tool behind each traced value is added to the trace.

Value

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).

References

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.

The trace

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.

What counts as a number

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.

Author(s)

Max Moldovan

See Also

run_return(), write_return().

Examples

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)$released

Perform a plan and keep a record when it fails

Description

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.

Usage

try_conduct(plan, data = list(), ...)

Arguments

plan

An oap_plan.

data

The data object every tool receives.

...

Further arguments to conduct().

Details

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.

Value

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).

Author(s)

Max Moldovan

See Also

run_record(), run_return().

Examples

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))

Write a return to a file

Description

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.

Usage

write_return(ret, path)

Arguments

ret

A return from run_return().

path

A series folder, or a file path ending in .txt.

Value

The path of the file written, invisibly.

A series of runs

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.

Author(s)

Max Moldovan

See Also

run_return(), series_report().

Examples

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)