## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 5
)
library(umx)
# Never auto-open browser plots during package check
umx_set_auto_plot(FALSE)

## ----load-data----------------------------------------------------------------
# Load the classic Holzinger Swineford 1939 data (x1:x9)
data("HS.ability.data")

# Define the manifest (observed) variables
manifests = c("visual","cubes","flags","paragrap","sentence","wordm","addition","counting","straight")
# Quick look at the correlations
umx_cor(HS.ability.data[, manifests])

## ----build-model, results = "hide", message = FALSE---------------------------
m1 = umxRAM("Holzinger_one_factor", data = HS.ability.data,
  # Factor loadings (G predicts each x)
  umxPath("g", to = manifests),
  # Residual means and variances for the observed variables
  umxPath(v.m. = manifests),
  # Fix the latent factor variance to 1 (for identification)
  umxPath(v1m0 = "g")
)

## ----summary-basic------------------------------------------------------------
umxSummary(m1)

## ----summary-std--------------------------------------------------------------
umxSummary(m1, std = TRUE)

## ----lavaan-string, results = "hide", message = FALSE-------------------------
m2 = umxRAM(paste("g =~", paste(manifests, collapse = " + ")),
  data = HS.ability.data)

## ----lavaan-summary-----------------------------------------------------------
umxSummary(m2, std = TRUE)

## ----plot-png, fig.cap = "Standardized one-factor Holzinger model (PNG)", message = FALSE----
# Prefer a stored PNG under vignettes/figures/ (no browser). Regenerate if missing.
figDir = "figures"
dir.create(figDir, showWarnings = FALSE)
gvPath = file.path(figDir, "holzinger_one_factor.gv")
pngPath = file.path(figDir, "holzinger_one_factor.png")
if (!file.exists(pngPath)) {
	# digraph only; capture.output silences plot()'s cat() of the graph
	dot = NULL
	utils::capture.output({
		dot <<- plot(m1, std = TRUE, means = FALSE, file = NA)
	})
	cat(dot, file = gvPath)
	# 1) Graphviz CLI
	dotBin = Sys.which("dot")
	if (nzchar(dotBin)) {
		system2(dotBin, c("-Tpng", "-o", pngPath, gvPath), stdout = FALSE, stderr = FALSE)
	}
	# 2) DiagrammeR → SVG → PNG (Suggests: DiagrammeRsvg, rsvg)
	if (!file.exists(pngPath) &&
		requireNamespace("DiagrammeR", quietly = TRUE) &&
		requireNamespace("DiagrammeRsvg", quietly = TRUE) &&
		requireNamespace("rsvg", quietly = TRUE)) {
		svgTxt = DiagrammeRsvg::export_svg(DiagrammeR::grViz(dot))
		rsvg::rsvg_png(charToRaw(svgTxt), pngPath)
	}
}
if (file.exists(pngPath)) {
	knitr::include_graphics(pngPath)
} else {
	message(
		"PNG plot unavailable (install graphviz `dot`, or DiagrammeR + DiagrammeRsvg + rsvg). ",
		"Ship/regenerate ", pngPath, " under vignettes/figures/."
	)
}

## ----uncertainty, message = FALSE---------------------------------------------
umxSummary(m1, std = TRUE, uncertainty = "MLR", refModels = FALSE)

