---
title: "8. GIMME"
output:
  rmarkdown::html_vignette:
    toc: true
bibliography: references.bib
link-citations: true
vignette: >
  %\VignetteIndexEntry{8. GIMME}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE,
  fig.width = 7, fig.height = 5.5
)
library(idiographic)
data(esm_srl)
has_cograph <- requireNamespace("cograph", quietly = TRUE)
```

Group iterative multiple model estimation (GIMME) sits at the boundary of
idiographic and group inference. It estimates a person-specific unified
structural equation model for each individual — one structural model per
person, fitted to that person's own ordered series — while searching for
paths that recur in a sufficient proportion of individuals and promoting
those to a shared group level. The estimand is
therefore double: every subject receives an idiographic dynamic model, and
the group model records which pieces of structure the sample holds in
common. Like the other lag-one models in this package, it presumes weakly
stationary series, linear lag-one dynamics, and correctly ordered,
approximately equally spaced occasions within each person.

Two kinds of within-person path enter the search. A temporal path
`from -> to` is a directed lag-one path within a person's series: the value
of `from` at occasion $t-1$ predicts the value of `to` at occasion $t$,
holding the other lagged variables constant. A contemporaneous path is a
directed within-occasion path: `from` predicts `to` at the same occasion,
over and above what the lagged variables explain. Unlike the graphical VAR,
whose contemporaneous layer is an undirected partial-correlation network,
GIMME places directed SEM paths within an occasion as well as across
occasions. The weight displayed on a GIMME edge is the proportion of
subjects whose individual model carries that path — path prevalence — not a
regression coefficient; a weight of 1 states that every subject has the
path and by itself says nothing about the size or sign of the effect. The
per-person coefficients live in the individual models and are reported
separately.

This placement distinguishes GIMME from its neighbours. Multilevel VAR
(`fit_mlvar()`) pools all subjects into a single fixed-effect average
temporal matrix and treats person-level departures as random effects around
it; GIMME instead keeps one structural model per person and asks which
paths replicate. Unified SEM (`fit_usem()`) fits the same person-specific
model class for a single subject, with no group search; GIMME is the
multi-subject extension that adds the replication rule. The method is
appropriate when theory expects both shared pathways and person-specific
deviations, and when the question is which is which.

# Data and preprocessing

The estimator expects long format: one row per person-occasion, an id
column, an ordering column, and numeric time-varying indicators. The
supplied anonymized `esm_srl` data hold momentary self-regulated-learning
indicators for 41 students; `name` identifies the student and `occasion` orders
measurements within student. Five indicators enter the model: `efficacy`,
`value`, `planning`, `monitoring`, and `effort`. To keep the vignette fast
without hand-picking people for their fitted networks, the example uses the
four students with the most complete five-indicator occasions, breaking ties
alphabetically.

```{r vars-audit}
vars <- c("efficacy", "value", "planning", "monitoring", "effort")
complete_n <- tapply(complete.cases(esm_srl[vars]), esm_srl$name, sum)
selection <- data.frame(subject = names(complete_n),
                        complete = as.integer(complete_n))
selection <- selection[order(-selection$complete, selection$subject), ]
selected_ids <- head(selection$subject, 4)
head(selection, 4)
preprocess(esm_srl[esm_srl$name %in% selected_ids, ],
           vars = vars, id = "name")
```

The transparent rule selects Hana, Iker, Jamal, and Omar, each with 79
complete five-indicator occasions. The audit is shown rather
than silently assuming stationarity; these supplied series contain trend or
shift flags, so the fit is a method demonstration and its paths should not be
treated as confirmatory substantive findings.

# Fitting the model

The estimator takes the data, the variable set, the id column, and the time
column; `time = "occasion"` orders occasions within each student. `ar = TRUE`
places an autoregressive path on every variable in every subject's model
from the outset, which anchors the search. `groupcutoff = 0.75` and
`subcutoff = 0.75` require a path to improve fit in at least 75 percent of
the relevant subjects — here, three of the four — before it is promoted by
the corresponding rule.

```{r fit}
students <- esm_srl[esm_srl$name %in% selected_ids, ]
gimme_fit <- fit_gimme(
  students, vars = vars, id = "name", time = "occasion",
  ar = TRUE, groupcutoff = 0.75, subcutoff = 0.75, seed = 1
)
gimme_fit
```

No cross-variable path reaches the 75 percent group threshold. The five
autoregressive paths are fixed by `ar = TRUE` and carried by all four
students; all selected cross-variable paths are individual-level. This is a
result of the stated rule and cutoffs, not a claim that the population has no
shared dynamics. The fitted temporal and contemporaneous prevalence matrices
range from 0.25 (one student) to 0.75 (three students) off the diagonal.

# Reading the output

The `summary()` method reports one row per network layer, counting
cross-variable edges only.

```{r summary}
summary(gimme_fit)
```

The temporal layer holds six cross-variable edges at density 0.30 and mean
prevalence 0.250; the contemporaneous layer holds 11 directed edges at density
0.55 and mean prevalence 0.409. The `edges()` accessor lists every retained path with its layer,
prevalence, and level.

```{r edges}
edges(gimme_fit)
```

The first five temporal rows are the fixed autoregressive self paths at
prevalence 1. Every cross-variable row is individual-level. The most prevalent
contemporaneous path is planning to efficacy, present in three of the four
students; the most prevalent cross-lagged paths occur in one of the four
students.

```{r coefs-nodes}
head(coefs(gimme_fit))
nodes(gimme_fit)
```

`coefs()` supplies the person-specific estimates that the prevalence display
abstracts away: one row per subject, layer, and path. The displayed rows begin
with Jamal and show why prevalence and coefficient magnitude are separate
quantities. The `nodes()` table sums prevalence over incident edges. Planning is
the most connected contemporaneous node (strength 2.25), while value is
most connected temporally (strength 1.00); the `self` column separately records
autoregressive prevalence 1 for every variable.

```{r matrices}
matrices(gimme_fit)
```

`matrices()` returns the count and sample-average coefficient matrices
behind these tables, with outcomes on the rows and predictors on the
columns. The temporal count matrix has 4 on its diagonal and at most 1 in an
off-diagonal cell; the contemporaneous count matrix reaches 3. The average
coefficient matrices put magnitude beside recurrence; for example, the
planning-to-efficacy contemporaneous path appears in three students and averages
0.302 across all four. A path can therefore be common and weak, so
prevalence and magnitude have to be read together, and neither should be
mistaken for a standardized effect size.

# Visualizing the network

Plotting the fit draws the mixed network in the convention of the `gimme`
package: a single panel over the five nodes in which dashed edges are
lag-one temporal paths, solid edges are contemporaneous paths, black edges
belong to the group model, grey edges are individual-level, and edge width
scales with the weight. Under the default `weight = "prop"` the width is
path prevalence.

```{r plot-prop, eval=has_cograph}
plot(gimme_fit, weight = "prop")
```

The dashed black self-loops constitute the fixed group structure; the grey
arrows are individual-level paths, drawn in proportion to how many students
carry them.

```{r plot-coef, eval=has_cograph}
plot(gimme_fit, weight = "coef")
```

Reweighting by `weight = "coef"` keeps the same graph but scales width by the
sample-average coefficient, so the display answers how large rather than how
common. This view must still be read beside the count matrix because an average
over all eight students can be small even when the fitted coefficients among
the students carrying a path are sizeable.

# References
