--- title: "Building, checking and diagramming a theory" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Building, checking and diagramming a theory} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse = FALSE, comment = "") # Console colour carries no meaning on a rendered page. pkgdown turns it on for # its own build, and the escape sequences then reach the reader as literal text, # so colour is switched off here for a plain vignette render and a site build # alike. The fixed width keeps printed output inside the documentation column. options(cli.num_colors = 1, cli.hyperlink = FALSE, crayon.enabled = FALSE, width = 80) # Both optional packages are needed to turn the DOT source into an inline # SVG, so the rendering chunks below are skipped when either is absent. has_diagram <- requireNamespace("DiagrammeR", quietly = TRUE) && requireNamespace("DiagrammeRsvg", quietly = TRUE) ``` `theoryforge` treats a scientific theory as a versioned, machine-checkable object. This vignette shows how to build a theory, check its rigour and diagram it. The [package overview](https://pablobernabeu.github.io/theoryforge/r/) describes the R/Python parity guarantee. ```{r setup} library(theoryforge) ``` ## Building a theory A theory is built incrementally with the BUILDING-mode verbs. Each verb appends to the theory, records a provenance entry and returns the theory, so the steps compose with the native pipe. ```{r build} theory <- tf_theory("panic-network", "A network theory of panic") |> tf_add_construct("c_arousal", "Physiological arousal", "Bodily activation in response to a stressor.", measurement = "heart rate variability", boundary_conditions = "awake adults") |> tf_add_construct("c_threat", "Perceived threat", "Appraised danger of bodily sensations.", measurement = "self-report appraisal scale", boundary_conditions = "awake adults") |> tf_add_proposition( "p1", "c_arousal", "c_threat", "causes", mechanism = "Activation raises the salience of threat cues." ) |> tf_add_prediction("h1", "Arousal raises threat appraisal by a fixed amount.", "point", derives_from = "p1") isTRUE(tf_validate(theory)) # structural checks: required fields and enums # also ids, cross-references and the rest of the schema isTRUE(tf_validate(theory, full = TRUE)) ``` `tf_validate()` returns `TRUE` invisibly on success and otherwise stops with a message listing every problem. The calls above wrap it in `isTRUE()` to show the result. With `full = TRUE`, it additionally checks referential integrity: that ids are unique and that every cross-reference points to a declared id. It then checks the rest of the schema, such as the evidence directions, a logical `passed` on each test outcome and the type of every other field. It does not require any optional dependency. A failed validation shows what the full pass adds. A prediction pointing at a proposition that was never declared still passes the structural checks, since every required field is present and well formed. Only `full = TRUE` reports the problem. ```{r validate-failure, error = TRUE} broken <- theory broken$predictions[[1]]$derives_from <- "p_missing" tf_validate(broken, full = TRUE) ``` BUILDING mode has three further verbs. `tf_add_alternative()` registers a rival account, which a prediction can name in its `diagnostic_vs` to declare that it discriminates between the two. `tf_add_assumption()` records an auxiliary assumption, and `tf_set_formal_model()` attaches a formal-model reference. Because each verb returns a modified copy, assigning the result to a new object leaves the original theory untouched. ```{r build-more} extended <- theory |> tf_add_alternative("alt_cognitive", "Cognitive model of panic", key_constructs = "catastrophic misinterpretation") |> tf_add_assumption("a1", "Arousal is measured at rest.", protects = "h1") |> tf_set_formal_model("sem", spec_ref = "panic-sem.lavaan") ``` The provenance entries are stored in the theory object and make up the record of how it was built. Each entry records the step, the action and its detail. ```{r provenance-entries} do.call(rbind, lapply(extended$provenance, as.data.frame)) ``` A theory can be written to and read back from disk. The format follows the file extension, `.json` for JSON and otherwise YAML. ```{r io} path <- tempfile(fileext = ".yaml") tf_write(theory, path) roundtrip <- tf_read(path) identical(roundtrip$id, theory$id) ``` ## Checking rigour `tf_check()` runs the 12-item rigour checklist defined in the copy of `rigor_checklist.yaml` included in the package. ```{r check} report <- tf_check(theory) report$aggregate_score # weighted score, 0-100, rounded to 1 dp report$gate # "pass", "blocked", or "advisory" (draft maturity) report$n_blockers_failed # count of failed blocker items # Per-item detail (checklist order preserved): report$items[[1]]$id # "falsifiability" report$items[[1]]$status # "pass" / "warn" / "fail" report$items[[1]]$score # numeric in [0, 1] ``` An item with nothing to assess, such as the redundancy screen of a theory with a single construct, has the status `"n/a"` and a `NULL` score. It is left out of the aggregate score, which is the weighted mean of the applicable items. `report$coverage` gives the applicable items' share of the checklist's weight. `tf_report()` renders the report as valid, pretty-printed JSON or as an HTML fragment. The JSON string is shown here verbatim. ```{r report-json} cat(tf_report(theory, format = "json")) ``` The HTML fragment can be inserted directly into a page, where it renders as a table. ```{r report-html, results = "asis"} cat(tf_report(theory, format = "html")) ``` ### Screening for redundant constructs The lexical redundancy screen reports the Jaccard similarity and the overlap coefficient of every pair of construct definitions, sorted by descending similarity. A pair is flagged for review when the definitions are near duplicates or one is contained in the other. ```{r redundancy} tf_redundancy_check(theory) ``` The lexical screen is deterministic but shallow. When a semantic comparison is wanted, `tf_embedding_redundancy()` takes any embedder that maps a definition to a numeric vector and reports the cosine similarity of each construct pair. It needs no optional dependency, since the embedder is supplied by the caller. Here, a toy bag-of-words embedder stands in for a language model. ```{r embedding-redundancy} vocab <- c("bodily", "activation", "appraised", "danger", "salience") embedder <- function(def) { words <- strsplit(tolower(def), "[^a-z]+")[[1]] vapply(vocab, function(w) sum(words == w), numeric(1)) } tf_embedding_redundancy(theory, embedder) ``` ## Diagramming `tf_diagram()` emits deterministic intermediate representations for several diagram types. The digraphs are Graphviz DOT, and the causal DAG uses dagitty syntax. ```{r diagram} cat(tf_diagram(theory, type = "nomological_net")) cat(tf_diagram(theory, type = "causal_dag")) ``` The DOT strings render with any Graphviz tool. In R, `tf_render_diagram()` returns them as a DiagrammeR widget for the viewer and for R Markdown, or as a standalone SVG string with `as = "svg"`. The packages it uses are optional and listed in Suggests, so the rest of the package works without them. The figure below is drawn from the nomological-net DOT printed above. ```{r diagram-render, results = "asis", eval = has_diagram} cat( '
', tf_render_diagram(theory, "nomological_net", as = "svg"), '
', sep = "" ) ``` The causal DAG is the one view that `tf_render_diagram()` does not render, since it is written in dagitty syntax. Paste it into a dagitty tool such as [dagitty.net](https://dagitty.net) instead. Within R, `tf_implications()` checks the causal DAG for acyclicity and returns the conditional independencies it entails, which the article 'Developing and testing a theory' works through. ## Simulation `tf_simulate()` treats each construct as a state variable and integrates the signed proposition network as a linear dynamical system. The trajectory is deterministic. ```{r simulate} sim <- tf_simulate(theory, steps = 5) unlist(sim$states) unlist(sim$trajectory[[1]]) # the common initial state unlist(sim$trajectory[[6]]) # after five Euler steps ``` The two states separate immediately. Arousal, which receives no incoming coupling, decays under the damping term. Perceived threat is pushed up by the positive coupling from arousal before the decay eventually takes over. The default `method = "euler"` takes fixed explicit steps, which stay close to the solution only while `dt` is small against the network's rates. The function warns when the Euler trajectory departs from the exact solution by more than 5 per cent. `method = "exact"` propagates the system with its matrix exponential, so each row is the solution at its time for any `dt`. It will become the default in the next minor release. ```{r simulate-exact} exact <- tf_simulate(theory, steps = 5, method = "exact") unlist(exact$trajectory[[6]]) # the exact solution at time 0.5 ```