Skip to contents

The Get started vignette reads, validates, scores and builds a theory. This article continues with the stages of developing and testing it. It appraises an amendment, derives what the theory’s causal graph commits it to, compares the theory with a rival, writes the theory and hypotheses sections of a preregistration, grades a test after the data and assembles the dossier. The examples read the theories that ship with the package through tf_example_path(), so every chunk needs only theoryforge, apart from those that draw a diagram with tf_render_diagram(), which also need the optional DiagrammeR and DiagrammeRsvg packages and are skipped without them.

Developing: appraising an amendment

A theory changes as it meets data, and the question is whether a change strengthens it. tf_appraise_amendment() compares an amended version with its prior version, the version before the new predictions were stated, and classifies the change as progressive, degenerating or neutral, by fixed rules that borrow the terms of Lakatos’s methodology of research programmes.

v1 <- tf_read(tf_example_path("panic-network.theory.yaml"))
v2 <- tf_read(tf_example_path("panic-network-2026-v2.theory.yaml"))

appraisal <- tf_appraise_amendment(v2, v1)
str(appraisal[c("verdict", "new_predictions", "corroborated_new", "dropped",
                "ad_hoc_assumptions", "content_lost", "implications_lost",
                "implications_lost_unrefuted", "signs_lost")])
List of 9
 $ verdict                    : chr "neutral"
 $ new_predictions            : chr "pred4"
 $ corroborated_new           : chr "pred4"
 $ dropped                    : chr "pred_indep"
 $ ad_hoc_assumptions         : chr(0) 
 $ content_lost               : chr(0) 
 $ implications_lost          : chr "c_arousal _||_ c_avoidance | c_perceived_threat"
 $ implications_lost_unrefuted: chr(0) 
 $ signs_lost                 : chr "effect of c_perceived_threat on c_avoidance: positive"

The first version implies that arousal and avoidance are independent given perceived threat and states that independence as pred_indep, which a test refuted. The second drops pred_indep, adds a direct path from arousal to avoidance and derives from it a new prediction that a registered test corroborates. It gives up one implied independence, the refuted one. It also gives up a sign. Both versions say that perceived threat causes arousal without saying in which direction, so in the second version the new path opens a route from threat to avoidance through arousal whose sign is not stated. The first version entails that raising perceived threat raises avoidance, and the second does not, so the amendment loses unrefuted content and is neutral. Stating that threat increases arousal in both versions would make it progressive.

The verdict is progressive when a corroborated new prediction adds content, no content is lost, no ad hoc assumption is added, no corroborated prediction is dropped and no failed prediction is weakened. It is never progressive when the causal graph of either version cannot be read, since the content of the two cannot then be compared. It is degenerating when an ad hoc assumption is added or a failed prediction is weakened and no corroborated new prediction adds content. Any other combination is neutral, theoryforge’s label for an amendment that meets neither rule. A new prediction adds no content when it derives from no proposition or only articulates what the prior version already held, and a prediction under a new id with the same statement and type is reported as renamed. An assumption added for an anomaly is ad hoc when it protects no new prediction other than that anomaly, or when some of those predictions have been tested and none is corroborated. While all of them are untested, it is pending. An assumption rewritten under its id is appraised as a new one is, and one moved unchanged to another id is not appraised. Any change of wording counts, even one that keeps the meaning, so a core assumption reworded under its id is appraised and, when it protects a prediction that failed in the prior, is read as answering it. Each appraised assumption that answers an anomaly is listed in assumptions with its change, new or revised.

The verdict holds only if what the two files declare is true, the test outcomes and the added_for and protects of each assumption above all. The appraisal reads no dates and nothing about where the data came from, so it cannot tell a prediction from an accommodation of data already seen, and deciding which version is the prior is the caller’s responsibility. Read refuted_new and corroborated_new_severity with the verdict: one corroborated new prediction among many that failed, or a pass whose own estimate lies outside the claimed region, is enough for progressive. ?tf_appraise_amendment lists the other fields of the result, and the article ‘Methodological foundations’ gives the full rule.

Testing

Testing starts from what the theory commits itself to. The testing sections read the modality-switching theory, whose causal graph is acyclic. Three of its four predictions and its one phenomenon state machine-readable claims, and its two rivals state propositions of their own. Where a feedback loop matters, the sections read the panic-network theory instead.

switching <- tf_read(tf_example_path("modality-switching.theory.yaml"))

The claim-form rubric

tf_severity() grades each prediction before any data, by the form of its claim. The base risk rises with the strength of the claim, from existence to point. A directional prediction is discounted for the correlations a field shows anyway, and a prediction that names a registered rival in diagnostic_vs gains a small bonus.

tf_severity(switching)
  prediction_id        type risk_score computed_severity
1         pred1 directional        0.4               0.3
2         pred2    interval        0.7               0.7
3         pred3       point        0.4               0.4
4         pred4    interval        0.7               0.8

The values, the discount and the bonus are the package’s conventions. The rubric reads only the declared type and the named rivals, so it ranks claims by their form and says nothing about how severely a claim has been tested, which depends on the design and the data. Post-data severity, further below, reads the data.

What the causal graph implies

A theory’s propositions together form a graph, and the graph implies conditional independencies that the theory does not state. tf_implications() derives them. Each directed relation is an arrow, and an association is a bidirected edge, covariance the theory leaves unexplained. The graph is read as complete: every pair of constructs in it that no proposition joins is read as having no direct effect on each other and no unexplained association. Every such pair yields one statement when some set of other constructs separates it, usually the parents of both. The statements are consequences of the graph as encoded, so they are the theory’s commitments only if its authors meant those omissions. When every relation is directed, these statements are the basis set, from which every other independence the graph implies follows when the distribution has the composition property, as a multivariate normal one does.

statements <- function(implied) {
  writeLines(vapply(implied$implications, function(i) i$statement, character(1)))
}
statements(tf_implications(switching))
c_sensorimotor_experience _||_ c_switch_cost | c_modality_activation
c_sensorimotor_experience _||_ c_conceptual_access | c_modality_activation, c_lexical_familiarity
c_sensorimotor_experience _||_ c_lexical_familiarity
c_modality_activation _||_ c_lexical_familiarity | c_sensorimotor_experience
c_switch_cost _||_ c_conceptual_access | c_modality_activation, c_lexical_familiarity
c_switch_cost _||_ c_lexical_familiarity | c_modality_activation

Switch cost and conceptual access are the two children of a fork at modality activation, so the theory says that their correlation is due to that shared cause and vanishes once it is held fixed. Sensorimotor experience and lexical familiarity meet only at the collider at conceptual access, so the theory says they are unrelated with nothing held fixed. The first statement is not among the theory’s predictions, whereas the second is stated as pred4. Evidence against either would count against the theory as encoded, including the omissions the statement rests on.

The basis set conditions on the parents of both constructs, which can be more than a single test needs. given = "minimal" prunes each conditioning set until none of its members can be dropped.

statements(tf_implications(switching, given = "minimal"))
c_sensorimotor_experience _||_ c_switch_cost | c_modality_activation
c_sensorimotor_experience _||_ c_conceptual_access | c_modality_activation
c_sensorimotor_experience _||_ c_lexical_familiarity
c_modality_activation _||_ c_lexical_familiarity
c_switch_cost _||_ c_conceptual_access | c_modality_activation
c_switch_cost _||_ c_lexical_familiarity

A minimal set holds fewer constructs, and that matters because the constructs are measured with error. Error in a conditioning construct leaves part of the dependence that holding it fixed should remove, so a conditional statement tested on observed scores is rejected too often, and more often the larger the sample (Westfall & Yarkoni, 2016). Take a chain whose two paths have standardised coefficients of .5, with the middle construct measured at a reliability of .8. The chunk below computes the partial correlation of the two ends given the observed middle and the rate at which a test at the 5 per cent level rejects the true statement.

r_observed <- 0.5 * sqrt(0.8)            # each end with the observed middle
partial <- (0.5 * 0.5 - r_observed^2) / (1 - r_observed^2)
n <- c(200, 500, 1000)
z <- atanh(partial) * sqrt(n - 4)
data.frame(n = n, partial = round(partial, 4),
           rejected = round(pnorm(z - 1.96) + pnorm(-z - 1.96), 2))
     n partial rejected
1  200  0.0625     0.14
2  500  0.0625     0.29
3 1000  0.0625     0.51

The minimal statements suit tests of single pairs. They are no longer a basis set, so their tests are not to be combined into one test of the model, as the tests of a basis set can be. A conditional statement is better tested in a latent-variable model, which takes the measurement error into account, and each statement can be tested in such a model separately (Thoemmes et al., 2018).

A graph with a feedback loop is refused by default. The panic-network theory has a loop between arousal and perceived threat.

Error:
! implications requires an acyclic causal graph; cycle found: c_arousal -> c_perceived_threat -> c_arousal; set cycles to 'sigma' to derive sigma-separation statements
looped <- tf_implications(v1, cycles = "sigma")
lapply(looped$feedback, unlist)
[[1]]
[1] "c_arousal"          "c_perceived_threat"
statements(looped)
c_arousal _||_ c_avoidance | c_perceived_threat

The d-separation criterion, which dagitty applies to any graph, is guaranteed to hold in a model with feedback only in special cases, a linear model among them. Sigma-separation holds whenever each feedback loop settles into a unique equilibrium (Bongers et al., 2021), and cycles = "sigma" applies it. A theory that posits alternative stable states, such as a calm state and a panic state that each sustain themselves, violates that assumption, and its statements are then not guaranteed.

What the causal graph entails

A prediction or a phenomenon can state its claim in machine-readable form, as the effect of one construct on another or the association between two, with a sign.

str(switching$predictions[[1]]$claim)
List of 4
 $ kind: chr "effect"
 $ x   : chr "c_modality_activation"
 $ y   : chr "c_switch_cost"
 $ sign: chr "positive"

tf_entailments() reads each claim against the graph. The signs of the routes between the two constructs decide whether the graph entails the claim, contradicts it or leaves it undetermined, and via names the propositions the verdict rests on. For an effect claim that no feedback loop reaches, adjustment gives a smallest set of constructs whose adjustment would identify the effect in observational data, or a minimal set when more than 12 constructs are candidates. Here it is the empty set. For other claims, it is NA. identified reports identification by adjustment alone, so an effect without such a set may still be identified by other means, such as the front-door criterion, and a set for a cause or an outcome marked latent assumes a measure of it.

entailed <- tf_entailments(switching)
listed <- function(x) if (identical(x, NA)) NA_character_ else paste(unlist(x), collapse = ", ")
data.frame(
  id = vapply(entailed$claims, function(c) c$id, character(1)),
  kind = vapply(entailed$claims, function(c) c$kind, character(1)),
  sign = vapply(entailed$claims, function(c) c$sign, character(1)),
  verdict = vapply(entailed$claims, function(c) c$verdict, character(1)),
  via = vapply(entailed$claims, function(c) listed(c$via), character(1)),
  adjustment = vapply(entailed$claims, function(c) listed(c$adjustment), character(1))
)
     id        kind     sign  verdict    via adjustment
1 pred1      effect positive entailed     p2           
2 pred3      effect positive entailed     p3           
3 pred4 association     zero entailed              <NA>
4   ph1 association positive entailed p1, p3       <NA>

The derived signs hold when the graph is the causal structure, with no common cause of two constructs left out unless an association stands for it, and when each directed relation acts in its stated direction whatever the other inputs, as in a linear model or a uniformly monotone one. A verdict whose faithfulness is TRUE also assumes that effects do not cancel exactly, along a route of unknown sign or between routes of opposite signs, and the preregistration and the dossier end its line with unless effects cancel exactly. Under cycles = "sigma", the sign of an effect further assumes that the system with the intervened construct held fixed settles, which the stability of the system as observed does not ensure. The function shows what the propositions commit the theory to and does not show whether a claim holds in data. The checklist’s derivation-chain item counts a prediction whose claim the graph contradicts or leaves open as not derived from the propositions it cites.

Equivalent models

Graphs that imply the same conditional independencies are Markov equivalent, and no test of conditional independence can tell them apart (Andersson et al., 1997). In structural equation modelling, this is the problem of equivalent models (MacCallum et al., 1993). tf_equivalent_models() marks each directed edge as compelled, pointing the same way in every equivalent graph, or reversible.

equivalent <- tf_equivalent_models(switching)
str(equivalent$v_structures)
List of 1
 $ :List of 3
  ..$ a       : chr "c_modality_activation"
  ..$ collider: chr "c_conceptual_access"
  ..$ b       : chr "c_lexical_familiarity"
data.frame(
  proposition = vapply(equivalent$edges, function(e) listed(e$propositions), character(1)),
  from = vapply(equivalent$edges, function(e) e$from, character(1)),
  to = vapply(equivalent$edges, function(e) e$to, character(1)),
  status = vapply(equivalent$edges, function(e) e$status, character(1))
)
  proposition                      from                    to     status
1          p1 c_sensorimotor_experience c_modality_activation reversible
2          p2     c_modality_activation         c_switch_cost reversible
3          p3     c_modality_activation   c_conceptual_access  compelled
4          p4     c_lexical_familiarity   c_conceptual_access  compelled

The collider at conceptual access compels the two edges into it. The other two edges are reversible, so no test of conditional independence can tell whether sensorimotor experience drives modality activation or the reverse. Telling the direction apart needs an intervention, a temporal order or distributional assumptions such as non-Gaussian errors. The function does not know which constructs a study manipulates, so an edge out of a construct that an experiment sets is listed as reversible all the same. The rule covers acyclic graphs of directed relations, so for a theory with a feedback loop or an association the record says why it was not computed.

[1] "feedback_loop"

Comparing the theory with a rival

A registered alternative can state its own propositions over the theory’s constructs, under alternatives[].propositions. In grounding by interaction, perceptual activation follows access to the concept instead of feeding it.

rival <- switching$alternatives[[1]]
do.call(rbind, lapply(rival$propositions, as.data.frame))
  id                      from                    to  relation
1 g1 c_sensorimotor_experience c_modality_activation increases
2 g2       c_conceptual_access c_modality_activation increases
3 g3     c_modality_activation         c_switch_cost increases
4 g4     c_lexical_familiarity   c_conceptual_access increases

tf_discriminate() sets the two graphs side by side. It lists the claims of the theory on which the two graphs give opposite verdicts, the independencies one graph implies and the other does not, and the effects and associations whose sign differs between them. Each of these is a result that could tell the two accounts apart.

compared <- tf_discriminate(switching, "alt_grounding_by_interaction")
compared$markov_equivalent
[1] FALSE
unlist(compared$counts)
discriminating_claims        independencies      decisive_effects 
                    2                     4                     6 
decisive_associations 
                    3 
do.call(rbind, lapply(compared$claims, as.data.frame))
      source    id   theory        rival discriminates
1 prediction pred1 entailed     entailed         FALSE
2 prediction pred3 entailed contradicted          TRUE
3 prediction pred4 entailed     entailed         FALSE
4 phenomenon   ph1 entailed contradicted          TRUE
writeLines(vapply(compared$independencies,
                  function(i) paste(i$implied_by, i$statement), character(1)))
theory c_sensorimotor_experience _||_ c_conceptual_access | c_modality_activation, c_lexical_familiarity
rival c_sensorimotor_experience _||_ c_conceptual_access | c_lexical_familiarity
theory c_modality_activation _||_ c_lexical_familiarity | c_sensorimotor_experience
rival c_modality_activation _||_ c_lexical_familiarity | c_sensorimotor_experience, c_conceptual_access

The rival can also be a theory of its own, whose constructs are matched to the theory’s by id. The comparison reads only the propositions each account states and does not say which account the data favour. The checklist’s diagnosticity item reads the same verdicts: a prediction that names a rival in diagnostic_vs counts only when the rival’s own graph does not give its claim the same verdict.

Preregistration

tf_preregister() writes the theory and hypotheses sections of a preregistration as Markdown. Its header gives the theory’s version and content hash and the status of the checklist’s derivation chain, read with the document’s cycles, and, when the causal graph has a feedback loop, a line that says whether the document refuses the loop or reads it by sigma-separation. A line in italics then says what the document holds and what must be added before registration. The hypotheses section opens with the assumptions that the verdicts on the claims rest on. Each hypothesis is listed with its type, its derivation, its claim and what the graph says of it, the adjustment an observational test would need, the auxiliary assumptions that protect it, the rivals it is declared to discriminate and its test record. The hypotheses section of the modality-switching theory reads as follows.

prereg <- tf_preregister(switching)
start <- regexpr("## Hypotheses", prereg, fixed = TRUE)
end <- regexpr("## Sampling plan", prereg, fixed = TRUE)
cat(substr(prereg, start, end - 1))
## Hypotheses
_The verdicts on the claims assume that the graph of the propositions is the causal structure, with no omitted common cause of two of its constructs, that each directed relation acts in its stated direction whatever the other inputs (as in a linear model or a uniformly monotone one), that effects do not cancel exactly where a verdict says 'unless effects cancel exactly' (faithfulness) and, for feedback loops read by sigma-separation, that each loop settles to a unique equilibrium, also once the intervened construct is held fixed._

1. [directional] In property verification with word frequency, word length and property typicality matched across conditions, responses are slower when the property belongs to a different modality from the preceding trial than when it belongs to the same one. (pred1; derives from: p1, p2)
   - Claim: the effect of c_modality_activation on c_switch_cost is positive; entailed by the causal graph through p2
   - Adjustment for an observational test: none needed
   - Auxiliary assumptions: aux1 (core)
   - Test record: untested
2. [interval] In that design the switch cost lies between 20 and 60 ms, averaged over items and participants. (pred2; derives from: p1, p2)
   - Region the claim allows: [20, 60]
   - Auxiliary assumptions: aux1 (core)
   - Test record: already tested: passed
3. [point] Concurrent dynamic visual noise removes the advantage of visual properties over auditory properties in semantic categorisation, leaving a difference of zero under load in the same participants who show the advantage without it. (pred3; derives from: p3)
   - Claim: the effect of c_modality_activation on c_conceptual_access is positive; entailed by the causal graph through p3
   - Adjustment for an observational test: none needed
   - Auxiliary assumptions: aux1 (core)
   - Rivals it is declared to discriminate: alt_grounding_by_interaction (its propositions contradict the claim)
   - Test record: untested
4. [interval] Across a corpus of concrete nouns matched for length, modality-specific perceptual strength and lexical familiarity correlate no more strongly than 0.10 in absolute value. (pred4; derives from: p1, p4)
   - Region the claim allows: [-0.1, 0.1]
   - Claim: c_sensorimotor_experience and c_lexical_familiarity are independent; entailed by the causal graph
   - Auxiliary assumptions: aux2 (core)
   - Rivals it is declared to discriminate: alt_symbol_interdependency (its propositions contradict the claim)
   - Test record: untested

A sampling plan section, the implied conditional independencies, with a line that says they rest on the omissions of the graph, and a severity line for each prediction follow. A registry also needs the study design, the analysis plan and the inference criteria, which a theory file does not hold, and a template such as PRP-QUANT sets them out (Bosnjak et al., 2022). Passing a path also writes the document to disk, with LF line endings.

Post-data severity

A prediction with bounds states the region of a quantity its claim allows, and a test outcome can record the estimate the test observed and its standard error. tf_post_data_severity() computes, for each such outcome, how severely the claim passed. For a claim with one bound, it is the post-data severity of Mayo and Spanos (2006): the probability that the test would have given a result less in accord with the claim, had the quantity been at the bound. For a claim with two bounds, it takes the smaller of the two one-sided values, the package’s own extension, which equals 1 minus the p value of the z-based two one-sided tests of equivalence (Lakens, 2017).

The theory’s interval prediction for the switch cost records one outcome, with illustrative values. A second outcome is added below, as a replication whose estimate falls above the region.

replicated <- tf_add_test_outcome(
  switching, "pred2", TRUE, estimate = 63, se = 6,
  observed = "Illustrative values: switch cost 63 ms (SE 6 ms)."
)
tf_post_data_severity(replicated)
  prediction_id outcome lower upper estimate se severity
1         pred2       0    20    60       41  6    0.999
2         pred2       1    20    60       63  6    0.309

The dossier writes each value beside its outcome in its test record. It writes a value that rounds to 1 as > 0.999 and one that rounds to 0 as < 0.001, since a test cannot give certainty, and it marks an outcome recorded as passed whose estimate lies outside the region and one recorded as failed whose estimate lies inside it.

dossier <- tf_dossier(replicated)
start <- regexpr("## Test record", dossier, fixed = TRUE)
end <- regexpr("## Evidence", dossier, fixed = TRUE)
cat(substr(dossier, start, end - 1))
## Test record

- pred2: passed; observed: Illustrative values, not a reported result: switch cost 41 ms (SE 6 ms).; post-data severity 0.999 for [20, 60]
- pred2: passed; observed: Illustrative values: switch cost 63 ms (SE 6 ms).; post-data severity 0.309 for [20, 60]; recorded as passed, with the estimate outside that region

The computation uses a normal approximation and treats the standard error as known, so it overstates the severity of an estimate inside the region when the standard error comes from a small sample. The standard error must describe the sampling distribution of the estimate at the bound. The value is nominal, so it does not account for selection, such as a subgroup chosen after seeing the data, and it does not check the statistical adequacy of the model behind the estimate. A high value does not show that the claim is true, and the checklist does not read it.

The dossier

tf_dossier() assembles one Markdown document for a reviewer or an editor. Its header gives the content hash, the checklist version, the checklist score with its range and the gate, and, when the causal graph has a feedback loop, how the dossier reads it. A paragraph in italics then says what the score describes, what the gate checks and what the dossier is: the test outcomes, evidence, registrations and declared severities are as the author recorded them, and the dossier checks none of them beyond the inconsistencies it flags, so it is not an independent audit. Sections on the checklist, where the two items that decide the gate are marked (blocker), the severities, the test record, the evidence, the claims and the causal graph, the equivalent models for observational data, the rivals and the provenance follow, and the preregistration closes it. The same theory file gives the same dossier for the same cycles, so it can be committed or attached to a submission. Its header and sections read as follows.

dossier <- tf_dossier(switching)
lines <- strsplit(dossier, "\n", fixed = TRUE)[[1]]
writeLines(lines[seq_len(grep("^## Checklist", lines) - 1)])
# theoryforge dossier: Modality switching in grounded conceptual processing

- Theory ID: modality-switching-2026
- Content hash: sha256:c8109f9b8b7ca5df9c28ea0b42d799a4e9e608cad9cb0641e6030f9cd7bbb630
- Maturity: developing
- Checklist version: 3.1
- Checklist score: 87.1 (83.5 to 89.2 with equal weights or one weight halved or doubled)
- Checklist coverage: 0.92
- Gate: pass
- Blockers failed: 0

_Generated by theoryforge from the file with the content hash above. The checklist score describes how completely the file states what checklist 3.1 asks for. Most items read whether a field is filled in or how a prediction is labelled, and stated claims are checked against the causal graph. Test outcomes are read only by the parsimony item, the weights are conventions, and no study has established what difference between two scores is meaningful. The score does not show that the theory is true or well reasoned. The gate reports whether either blocking item failed: at least one prediction is typed point, interval or directional, and every prediction cites declared propositions whose graph entails any claim it states, with no stated phenomenon contradicted. Under the default reading of feedback loops, a claim that names a construct on a loop or downstream of one is not read and blocks nothing. The labels are the author's and are not checked against the statements. Test outcomes, evidence, registrations and declared severities are as the author recorded them. The dossier flags a recorded pass whose estimate lies outside its claimed region, a recorded failure whose estimate lies inside it and a declared severity more than 0.2 above the rubric, and checks nothing else that the author entered. It is not an independent audit._
grep("^## ", lines, value = TRUE)
[1] "## Checklist"                               
[2] "## Severity (pre-data rubric of claim form)"
[3] "## Test record"                             
[4] "## Evidence"                                
[5] "## Claims and the causal graph"             
[6] "## Equivalent models (observational data)"  
[7] "## Rivals"                                  
[8] "## Provenance"                              
[9] "## Preregistration"                         

Compiling a measurement model

tf_compile_sem() writes lavaan model syntax for lavaan::sem() and does not need lavaan installed. Constructs with indicators become latent variables with =~, directed propositions labelled paths with ~ and associations covariances with ~~. Comments say whether the paths are identified, or what identifying them would need, and list the sign each increases or decreases proposition states, and the effect each claim is about is defined with :=, so that lavaan estimates the quantity the claim concerns.

cat(tf_compile_sem(switching))
# lavaan model generated by theoryforge for modality-switching-2026
# Written for lavaan::sem(); indicator names are the sanitised measurement entries and must match columns of the data.
# Measurement model
c_sensorimotor_experience =~ modality_specific_perceptual_strength_ratings + sensory_experience_ratings + self_reported_frequency_of_first_hand_encounters
c_modality_activation =~ bold_response_in_modality_specific_sensory_cortex + interference_from_a_concurrent_load_in_the_same_modality
c_switch_cost =~ switch_minus_repeat_response_time_difference + switch_minus_repeat_error_rate_difference
c_conceptual_access =~ semantic_categorisation_latency + lexical_decision_latency + accuracy_on_either_task
c_lexical_familiarity =~ subjective_familiarity_ratings + corpus_frequency_of_the_word_form + age_of_acquisition
# Structural model
c_modality_activation ~ b_c_sensorimotor_experience_c_modality_activation*c_sensorimotor_experience
c_switch_cost ~ b_c_modality_activation_c_switch_cost*c_modality_activation
c_conceptual_access ~ b_c_modality_activation_c_conceptual_access*c_modality_activation
c_conceptual_access ~ b_c_lexical_familiarity_c_conceptual_access*c_lexical_familiarity
# Identification: the paths among the constructs form no loop, and no two constructs are joined by both a path and a covariance (a bow). The path coefficients are therefore generically identified if the measurement model identifies the constructs (Brito & Pearl, 2002). Whether it does has to be checked separately.
# Signs the theory states, which the fit does not impose
# b_c_sensorimotor_experience_c_modality_activation > 0 (p1, increases)
# b_c_modality_activation_c_switch_cost > 0 (p2, increases)
# b_c_modality_activation_c_conceptual_access > 0 (p3, increases)
# b_c_lexical_familiarity_c_conceptual_access > 0 (p4, increases)
# Effects the claims are about, each the sum over the directed paths from cause to outcome of the product of the labels along the path
# pred1 claims that the effect of c_modality_activation on c_switch_cost is positive.
effect_c_modality_activation_c_switch_cost := b_c_modality_activation_c_switch_cost
# pred3 claims that the effect of c_modality_activation on c_conceptual_access is positive.
effect_c_modality_activation_c_conceptual_access := b_c_modality_activation_c_conceptual_access
# Covariances the theory fixes at zero (lavaan::sem() frees them by default; delete this block to restore its defaults)
c_sensorimotor_experience ~~ 0*c_lexical_familiarity
c_switch_cost ~~ 0*c_conceptual_access

The comment after the structural model says that its paths form no loop and that no pair of constructs is joined by both a path and a covariance, so the path coefficients are generically identified if the measurement model identifies the constructs (Brito & Pearl, 2002). The last block fixes at zero the covariance of the two exogenous constructs and the residual covariance of the two terminal ones, which two of the implied independencies require. lavaan::sem() frees them by default, so a fit with its defaults could not refute either statement, and deleting the block restores the defaults. The indicator names are the measurement entries made safe for lavaan and must match columns of the data. A construct with a single indicator is treated as measured without error. A feedback loop makes the model non-recursive, and such a model may not be identified (Bollen, 1989), so the syntax flags each loop in a comment and is a starting point for a fit.

Rendering and depositing

tf_render_report() writes the dossier as a Quarto source document, ready to render to HTML or PDF. A theory file may come from someone else, so the header tells Quarto to run no code, compile no OJS and load no MathJax, the theory’s text is escaped so that Quarto reads it as text, and a theory whose text Quarto would decode as a shortcode is refused. With Quarto 1.11, reports of hostile theory files rendered this way to html, revealjs and dashboard, and opened in a browser that loaded their scripts and clicked their links, ran none of the code, shortcodes or scripts the files held. The escaping holds for Quarto and Pandoc alone: writers of other markup languages, such as hugo-md, docusaurus-md, org or mediawiki, write the text back for programs that can run it, so render such a file to html, revealjs, dashboard, pdf, typst, docx, odt, pptx or epub. Quarto also runs the scripts and filters that _quarto.yml, _metadata.yml, _brand.yml and _extensions name in the report’s folder or any folder above it, so write the report into a folder of your own. With render = FALSE, the default, it writes the .qmd without calling Quarto, and it returns the path of the file it wrote.

report_path <- tf_render_report(switching, tempfile(fileext = ".qmd"))
file.exists(report_path)
[1] TRUE

tf_osf_push() deposits the dossier on an Open Science Framework node, as <id>.dossier.md. It defaults to dry_run = TRUE, which assembles the request and returns it without sending anything, so the planned deposit can be inspected offline and without a token.

str(tf_osf_push(switching, node = "ab12c"))
List of 3
 $ dry_run: logi TRUE
 $ request:List of 4
  ..$ method       : chr "PUT"
  ..$ url          : chr "https://files.osf.io/v1/resources/ab12c/providers/osfstorage/?kind=file&name=modality-switching-2026.dossier.md"
  ..$ filename     : chr "modality-switching-2026.dossier.md"
  ..$ content_bytes: int 15068
 $ note   : chr "set dry_run=FALSE with a valid token and node to perform the upload"

A live deposit needs dry_run = FALSE, a personal access token, the node id and the curl package. OSF refuses a second file with the same name, which tf_osf_push() reports as an error with HTTP 409. Pass a filename that names the version, or overwrite = TRUE to send the dossier to the existing file as a new OSF version.

tf_osf_push(switching, node = "ab12c", token = Sys.getenv("OSF_PAT"),
            dry_run = FALSE)

Visualising the theory

tf_diagram() returns ten views of a theory. Seven are graphs written in Graphviz DOT, or for the causal_dag view in DAGitty’s syntax, and three are SVG images. The Get started vignette shows the nomological network and the causal graph. The views below draw the panic-network theory, which records test outcomes and scope conditions, and each is drawn with tf_render_diagram(). The workflow view traces the theory from its constructs through its propositions and predictions to the recorded test outcomes.

cat('<div class="tf-figure tf-diagram">',
    tf_render_diagram(v1, "workflow", as = "svg"), '</div>', sep = "")
workflow cluster_build building cluster_relate propositions cluster_predict predictions cluster_test testing c_arousal Physiologicalarousal prop_p1 p1increases c_arousal->prop_p1 c_perceived_threat Perceived threat prop_p2 p2increases c_perceived_threat->prop_p2 prop_p3 p3causes c_perceived_threat->prop_p3 c_avoidance Avoidancebehaviour prop_p1->c_perceived_threat pred_pred1 pred1point prop_p1->pred_pred1 pred_pred_indep pred_indepinterval prop_p1->pred_pred_indep prop_p2->c_avoidance pred_pred2 pred2interval prop_p2->pred_pred2 pred_pred3 pred3directional prop_p2->pred_pred3 prop_p2->pred_pred_indep prop_p3->c_arousal prop_p3->pred_pred1 prop_p3->pred_pred_indep outcome_pred1 pred1passed pred_pred1->outcome_pred1 outcome_pred_indep pred_indepfailed pred_pred_indep->outcome_pred_indep

The context view places the theory among its scope conditions and the rivals it is meant to outpredict.

cat('<div class="tf-figure tf-diagram">',
    tf_render_diagram(v1, "context", as = "svg"), '</div>', sep = "")
context theory Network theory ofpanic disorder c_arousal Physiologicalarousal theory->c_arousal c_perceived_threat Perceived threat theory->c_perceived_threat c_avoidance Avoidancebehaviour theory->c_avoidance alt_cognitive Cognitive model ofpanic theory->alt_cognitive contrasts with alt_biological Biological modelof panic theory->alt_biological contrasts with scope1 adults scope1->theory holds within scope2 non-clinicalbaseline scope2->theory holds within scope3 no beta-blockermedication scope3->theory holds within scope4 waking hours scope4->theory holds within scope5 community sample scope5->theory holds within

The pipeline view links each prediction to its test outcomes, one node for each, so a failed replication appears beside the pass it followed. The provenance view draws the provenance log.

cat('<div class="tf-figure tf-diagram">',
    tf_render_diagram(v1, "pipeline", as = "svg"), '</div>', sep = "")
pipeline pred1 pred1point pred2 pred2interval result_pred1 passed pred1->result_pred1 pred3 pred3directional pred_indep pred_indepinterval result_pred_indep failed pred_indep->result_pred_indep

The venn, rigour and severity views are returned as SVG. The venn view draws the boundary conditions of the first three constructs as overlapping sets, the rigour view the checklist as a grid of statuses and the severity view one bar per prediction.

cat('<div class="tf-figure">', tf_diagram(v1, "rigour"), '</div>', sep = "")
Checklist 3.1checklist score 88.0, gate passfalsifiabilitypassprecisionpassrisk_severitypassparsimonyn/anon_redundancypassconstruct_claritypassscopepasslogical_whypasscausal_testabilitypassdiagnosticitypassformalisationpassderivation_chainwarn

The development_roadmap view turns the checklist into a worklist. It keeps the items that fail or warn and orders them as the work should be done: the items that block the gate first, heaviest first, then the advisory ones. The weak theory of the Get started vignette gives the full list, one numbered node for each item.

weak <- tf_read(tf_example_path("weak-theory.theory.yaml"))
cat(tf_diagram(weak, "development_roadmap"))
digraph development_roadmap {
  graph [rankdir=TB, bgcolor="transparent", fontname="Helvetica", fontsize=11, pad="0.2", nodesep="0.3", ranksep="0.45"];
  node [fontname="Helvetica", fontsize=11, shape=box, style="rounded,filled", color="#33567A", fillcolor="#F2F6F9", fontcolor="#12283A", penwidth=1.1, margin="0.16,0.1"];
  edge [fontname="Helvetica", fontsize=10, color="#7B909F", fontcolor="#0F6E6E", arrowsize=0.7];
  "roadmap" [shape=ellipse, label="An underspecified\nmotivation theory\nchecklist 3.1\nchecklist score 2.2, gate blocked", fillcolor="#12283A", color="#12283A", fontcolor="#FFFFFF"];
  "falsifiability" [label="1. falsifiability\nAt least one\nprediction is typed\npoint, interval or\ndirectional; the label\nis the author's\nblocks the gate", fillcolor="#F9E5E4", color="#B2453C"];
  "derivation_chain" [label="2. derivation_chain\nEvery prediction cites\ndeclared propositions,\nthe causal graph\nentails any claim it\nstates and contradicts\nno phenomenon's claim\n(a claim left unread\nbecause of a feedback\nloop warns)\nblocks the gate", fillcolor="#F9E5E4", color="#B2453C"];
  "precision" [label="3. precision\nShare of predictions\ntyped point or\ninterval with a finite\nlower and upper bound,\nat or above threshold;\nthe width of the\nregion is not read\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "risk_severity" [label="4. risk_severity\nMean prediction\nriskiness (declared\nseverity, else the\nclaim-form rubric) at\nor above threshold\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "non_redundancy" [label="5. non_redundancy\nEvery construct is\ndefined, and no two\nhave near-duplicate or\ncontained definitions\nor one label, and no\nconstruct's measures\nare all listed for\nanother (lexical\nscreen)\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "construct_clarity" [label="6. construct_clarity\nEvery construct has\ndefinition +\nmeasurement + boundary\nconditions\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "logical_why" [label="7. logical_why\nEvery proposition's\nmechanism field is\nfilled in; its text is\nnot judged\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "scope" [label="8. scope\nBoundary conditions\nexplicitly stated\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "causal_testability" [label="9. causal_testability\nAt least one\nproposition states a\ncausal relation\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "diagnosticity" [label="10. diagnosticity\nAt least one\nprediction names a\nregistered alternative\nit discriminates from\n(declared, and not\nshown false where the\nclaim and the rival's\npropositions are\nstated)\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "formalisation" [label="11. formalisation\nA formal model of a\nrecognised type (ode,\nabm, network, sem) is\ndeclared\nadvisory", fillcolor="#FBF1DC", color="#9C6B14"];
  "roadmap" -> "falsifiability";
  "falsifiability" -> "derivation_chain";
  "derivation_chain" -> "precision";
  { rank=same; "precision" -> "risk_severity" -> "non_redundancy" [style=invis]; }
  "precision" -> "construct_clarity" [style=invis];
  { rank=same; "construct_clarity" -> "logical_why" -> "scope" [style=invis]; }
  "construct_clarity" -> "causal_testability" [style=invis];
  { rank=same; "causal_testability" -> "diagnosticity" -> "formalisation" [style=invis]; }
}

?tf_diagram documents each view.

Simulation

tf_simulate() treats each construct as a state variable and propagates the signed network of propositions as a linear dynamical system. increases couples positively and decreases negatively. causes and mediates state no sign, so they are coupled positively by an assumption the record lists under assumed_positive, and moderates and associates are not coupled. A theory states no parameter values, so the trajectory is that of one linear model consistent with the signs the propositions state, with one gain k for every coupling and a decay at the rate damping for every state. Each row is the solution of the system at its time, computed with the matrix exponential, whatever the step size.

The example closes a loop in which avoidance lowers arousal. The run covers 20 time units in steps of 0.5 and prints the state every two time units.

regulation <- tf_theory("regulation-demo", "Arousal regulated by avoidance") |>
  tf_add_construct("arousal", "Physiological arousal", "bodily activation") |>
  tf_add_construct("threat", "Perceived threat", "appraised danger") |>
  tf_add_construct("avoidance", "Avoidance behaviour", "protective withdrawal") |>
  tf_add_proposition("p1", "arousal", "threat", "increases") |>
  tf_add_proposition("p2", "threat", "avoidance", "increases") |>
  tf_add_proposition("p3", "avoidance", "arousal", "decreases")

sim <- tf_simulate(regulation, steps = 40, dt = 0.5)
every_two <- seq(1, 41, by = 4)
trajectory <- do.call(rbind, lapply(sim$trajectory[every_two], unlist))
colnames(trajectory) <- unlist(sim$states)
data.frame(time = (every_two - 1) * sim$dt, trajectory)
   time   arousal    threat avoidance
1     0  1.000000  1.000000  1.000000
2     2 -1.230162 -0.230671  1.049278
3     4 -0.265490 -1.265417 -0.997448
4     6  1.332317  0.620111 -0.712082
5     8 -0.161493  1.065450  1.226949
6    10 -1.280417 -0.962283  0.318135
7    12  0.572654 -0.756450 -1.329104
8    14  1.096531  1.205189  0.108658
9    16 -0.924764  0.369449  1.294213
10   18 -0.799577 -1.323824 -0.524246
11   20  1.181519  0.055648 -1.125870

Arousal falls first, pushed down by avoidance. Threat and avoidance rise briefly and then follow it down, each later than the one before, and arousal later climbs back above its starting value. The three constructs keep cycling, and at the default gain of 1 and damping of 0.5 the swings neither grow nor fade.

Whether a feedback loop grows or settles is set by the gain against the damping, neither of which the theory states. The loop of arousal and perceived threat in the panic-network theory, closed by a causes proposition coupled positively by assumption, grows at the defaults, a gain of 1 and a damping of 0.5, holds its level at a damping of 1 and settles above it. Time is in units of 1/k, and the window that steps and dt choose decides what is seen. The last construct of a chain of five, which decays in the long run, shows only a rise in the default window of one time unit.

ends <- lapply(c(0.5, 1, 1.5), function(damping) {
  sim <- tf_simulate(v1, steps = 30, damping = damping)
  stats::setNames(sim$trajectory[[31]], unlist(sim$states))
})
data.frame(damping = c(0.5, 1, 1.5), do.call(rbind, ends))
  damping c_arousal c_perceived_threat c_avoidance
1     0.5  4.481689           4.481689    4.481689
2     1.0  1.000000           1.000000    1.000000
3     1.5  0.223130           0.223130    0.223130
chain <- tf_theory("chain", "A chain of five constructs")
for (i in 0:4) chain <- tf_add_construct(chain, paste0("c", i), paste0("C", i), "A state.")
for (i in 0:3) {
  chain <- tf_add_proposition(chain, paste0("p", i), paste0("c", i), paste0("c", i + 1),
                              "increases")
}
window <- function(steps) {
  last <- vapply(tf_simulate(chain, steps = steps)$trajectory, `[[`, numeric(1), 5L)
  c(time = steps * 0.1, end = last[[length(last)]], peak = max(last))
}
rbind(window(10), window(400))
     time      end     peak
[1,]    1 1.642687 1.642687
[2,]   40 0.000244 5.768572

A linear system has one equilibrium, or a continuum of them, and never two separate ones, so it cannot show the alternative stable states that some theories posit. method = "euler" takes fixed explicit steps, which stay close to the solution only while dt is small against the network’s rates. On the regulation loop above, they inflate the oscillation, and tf_simulate() warns when an Euler trajectory departs from the exact one by more than 5 per cent of the larger of the exact value and the largest absolute starting value. init sets the starting values, one number for every construct or a named list such as list(arousal = 1), which starts the constructs it leaves out at 0 and so traces the response to an impulse. No data enter the trajectory, and it does not show what the propositions imply beyond the signs it was built from.