---
title: "Network Meta-analysis with MARS"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Network Meta-analysis with MARS}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse=TRUE,comment="#>")
library(mars)
```

## Select the statistical model

All three interfaces fit basic treatment effects jointly under coherence.
Coherence defines relationships between treatment contrasts; multivariate and
multilevel specify their covariance. Transitivity concerns the comparability of
studies' effect modifiers and requires substantive assessment.

| Interface | Intended analysis | Heterogeneity |
|---|---|---|
| `coherent` | Standard NMA | `none` or `common` |
| `multivariate` | Correlated basic treatment effects, outcomes or times | `none`, `common`, or `unstructured` |
| `multilevel` | Treatment variation across additional study-level groups | `none` or common signed contrast variance per level |

`network_meta()` defaults to standard common-effect NMA. Select
`heterogeneity="common"` explicitly for random-effects NMA. `wls` is a
zero-heterogeneity GLS interface. No option pools unconstrained comparisons and
then projects them onto coherence after heterogeneity estimation.

## Contrast data, reference and covariance

Each effect is `treatment_2` minus `treatment_1`. For odds/risk ratios supply
logarithmic effects and their sampling variances. Sampling dependence must be
specified separately from random-effects heterogeneity.

This example combines three-arm trials and two-arm trials. The shared control
induces sampling covariance .015 between the two contrasts in each three-arm trial.

```{r contrast-data}
d <- data.frame(id=paste0("i",1:18), study=rep(1:12,c(rep(2,6),rep(1,6))),
  a="A",b=c(rep(c("B","C"),6),rep(c("B","C"),3)),
  effect=c(.2,.5,.3,.7,.1,.6,.4,.8,.2,.4,.3,.6,.1,.5,.4,.8,.2,.6),variance=.04)
S <- diag(d$variance); dimnames(S)<-list(d$id,d$id)
for(ii in split(seq_len(nrow(d)),d$study)) if(length(ii)==2) S[ii,ii]<-matrix(c(.04,.015,.015,.04),2)
fit <- network_meta(d,"study","a","b","effect","variance",reference="A",
  observation_id="id",sampling_covariance=S,heterogeneity="common")
fit
network_league_table(fit)
```

The reference need not occur in every study. Changing the reference changes basic
effect coordinates, not equivalent pairwise contrasts. If omitted, the first
sorted treatment is used.

The network overview counts studies, within-study pairwise comparisons,
treatments and designs (unique study treatment sets). A three-arm study
contributes three pairwise comparisons even when represented by two basis rows.
Unique study treatment pairs and actual modeled contrast rows are reported
separately; repeated outcomes/times do not duplicate study-pair counts.

The residual-variation section reports overall, within-design and between-design
Q using sampling covariance alone. Overall and within-design Q-based I-squared
are printed as percentages. Overall variation includes both heterogeneity and
incoherence. The two I-squared values are not additive and do not partition
multilevel/multivariate variance components. Between-design I-squared is not
reported; zero residual df has unavailable I-squared. The random-effects Higgins
test remains a separate diagnostic.

Printed models and summaries default to treatment-minus-reference contrasts,
within every mean stratum. To display the full set of pairwise results, use:

```{r display-comparisons, eval=FALSE}
summary(fit, comparisons="all")
print(fit, comparisons="all")
summary(fit, digits=3)
print(summary(fit, digits=3), digits=5)
```

`digits` controls significant digits and defaults to `getOption("digits")`.
A summary remembers the requested precision, and an explicit print setting
overrides it. Counts and df stay integers, small p-values are not printed as
zero, and stored numerical precision is unchanged.

This is a display choice. All pairs remain in `fit$effects` and league tables;
diagnostic hypothesis sets and multiplicity-adjustment families are unchanged.
For example, displaying nine Placebo contrasts from a ten-treatment network
retains adjustment over all 45 fitted pairs when that is the selected family.

```{r reference}
reference_B <- network_meta(d,"study","a","b","effect","variance",reference="B",
  observation_id="id",sampling_covariance=S,heterogeneity="common")
stopifnot(isTRUE(all.equal(fit$effects$total,reference_B$effects$total,tolerance=1e-7)))
```

Multiple rows within a study require covariance, or an explicit
`assume_independent=TRUE` assumption. Independence is not inferred from a missing
matrix. Supplied named matrices or named study blocks are aligned by observation ID;
subset effects and covariance together. Singular sampling covariance is rejected:
supply a scientifically valid independent contrast basis instead of redundant pairs.

## Multiple treatment comparisons

Use `adjust="holm"` or `adjust="bonferroni"` to control family-wise error for
the total network treatment-effect tests. The default, `adjust="none"`, leaves
p-values unadjusted. These options use R's `stats` package and add no dependency.

```{r multiplicity}
adjusted <- network_meta(d,"study","a","b","effect","variance",reference="A",
  observation_id="id",sampling_covariance=S,heterogeneity="common",adjust="holm")
adjusted$effects[,c("treatment_1","treatment_2","total","total_se",
  "total_p_value","total_p_adjusted")]
adjusted$adjustment
```

The family contains every unique treatment pair reported in `effects`, including
indirectly estimated comparisons. For this three-treatment example there are
three hypotheses. When separate effects are reported by outcome or time, all
pair-by-stratum hypotheses are adjusted together. This family is independent of
the reference treatment. Moderator-adjusted comparisons are evaluated at
covariate zero, as are the reported total effects.

Raw two-sided p-values use the model's normal reference distribution, or the
study-based t distribution for CR1 inference. Holm accommodates dependence among
comparisons and is generally preferable to Bonferroni for adjusted p-values.
Error control depends on the validity of the underlying tests and model.
Nonestimable tests retain NA p-values and remain counted in the family size.

Estimates, standard errors, fitted heterogeneity, league tables and confidence
intervals are unchanged. Existing confidence intervals are **pointwise**, not
simultaneous: an interval can exclude zero while its adjusted p-value exceeds
0.05. Moderator-coefficient tests and assumption-checking diagnostics are outside
this adjustment family.

## Construct contrasts from arms

For one measurement per treatment, `network_arm_data()` constructs baseline
contrasts and their covariance for MD, SMD, logOR, logRR or RD. Study baselines and
the network reference are separate choices.

```{r arms}
arms <- data.frame(study=rep(1:4,each=3),treatment=rep(c("A","B","C"),4),
  mean=c(0,.3,.6,0,.2,.5,0,.4,.7,0,.3,.5),sd=1,n=60)
a <- network_arm_data(arms,"study","treatment",mean="mean",sd="sd")
arm_fit <- network_meta(a$data,"study_id","treatment_1","treatment_2","effect","variance",
  observation_id="observation_id",sampling_covariance=a$sampling_covariance)
arm_fit$effects[,c("treatment_1","treatment_2","total","total_se")]
```

Binary logarithmic effects use a normal approximation. If zero cells occur, the
chosen correction applies to all arms in that study. RD can have zero estimated
variance at extreme probabilities; the estimator requires positive sampling
variances. The SMD constructor uses a joint delta-method approximation including
uncertainty in the estimated denominator. Standardizers must support comparable
estimands across studies.

## Multivariate basic-effect covariance

The likelihood is
\[
y_i\sim N(X_i d,\ S_i+Z_i\Omega Z_i^\top).
\]
`S_i` is sampling covariance. `Omega` describes between-study treatment variation.
For common heterogeneity, every pairwise contrast has variance `tau2`, with
appropriate signed multi-arm covariance. Unstructured covariance relaxes this
restriction while preserving coherence.

```{r multivariate}
Omega <- matrix(c(.04,.015,.015,.06),2,
  dimnames=list(c("d_B","d_C"),c("d_B","d_C")))
mv <- network_meta(d,"study","a","b","effect","variance",reference="A",
  model_type="multivariate",tau2=Omega,observation_id="id",sampling_covariance=S)
network_prediction_intervals(mv)
```

A named `tau2` matrix fixes `Omega`; omitting it estimates unstructured covariance
when identifiable. Its coordinates depend on the reference and mean strata.
Transform a supplied matrix when changing reference. Diagonal covariance in one
reference's basic effects is not a reference-invariant heterogeneity assumption.
Studies may report subsets of outcomes provided the combined network identifies
all requested mean and covariance parameters. See the dependent-effects vignette
for outcome/time strata and cross-outcome covariance.

## Multilevel signed treatment effects

Each grouping level adds covariance `Z_i Omega_level Z_i'`, rather than a shared
unsigned intercept on contrast rows. IDs in `random_levels` are interpreted within
study; crossed groups are allowed. `nested_levels` combines each ID with its
parents. Across-study random clustering is not supported by these interfaces.

```{r multilevel}
sites <- data.frame(study=rep(1:8,each=4),site=rep(rep(1:2,each=2),8),
  a="A",b=rep(c("B","C"),16),effect=rep(c(.2,.5,.4,.7),8),variance=.04,
  id=paste0("site",1:32))
site_S <- diag(sites$variance);dimnames(site_S)<-list(sites$id,sites$id)
for(ii in split(seq_len(nrow(sites)),interaction(sites$study,sites$site)))
  site_S[ii,ii]<-matrix(c(.04,.01,.01,.04),2)
ml <- network_meta(sites,"study","a","b","effect","variance",model_type="multilevel",
  random_levels="site",tau2=c(study=.03,site=.02),
  observation_id="id",sampling_covariance=site_S)
predict(ml,data.frame(treatment_1="A",treatment_2="B"),interval="prediction",new_levels="site")
```

The last interval adds site variance only. Default prediction adds every fitted
level's variance for new units. Omitted levels are fixed at zero; this is not a
BLUP prediction conditioned on an observed study. Prediction concerns true effects,
not future measured effects with additional sampling error.

## Moderators and inference

Numeric column names or a one-sided formula specify treatment interactions.
Formula factors are expanded consistently for prediction; numeric covariates should
be centered at a meaningful value. Reported summary effects use covariate zero.
`inference="CR1"` uses study-cluster covariance and t inference with K-1 degrees
of freedom at fitting time. Summary-time options also allow CR2/Satterthwaite
inference without refitting the model.

### Selecting summary-time inference

Use `inference="model", test="z"` for normal Wald inference, or
`inference="robust"` to select a sandwich covariance adjustment. Networks default
to clustering all contrast rows from the same study together. Explicit settings
make the covariance, test, and pointwise confidence level clear:

```{r network-summary-inference}
summary(fit, inference="model", test="z", level=0.90)
robust_summary <- summary(adjusted, inference="robust", robust_type="CR2",
  test="Satterthwaite", level=0.90, comparisons="all")
robust_summary

# Extract total treatment-contrast intervals using the same inference settings.
confint(adjusted, type="contrasts", inference="robust", robust_type="CR2",
  test="Satterthwaite", level=0.90)
```

The robust Satterthwaite calculation uses study-cluster influences and produces
contrast-specific degrees of freedom. Robust `test="naive-t"` instead uses K-1
degrees of freedom; `"naive-tp"` uses K-p, where p is the number of mean
coefficients. Robust adjustments require independent study clusters, estimable
covariance adjustments, and positive degrees of freedom.

Model-based `test="Satterthwaite"` uses expected covariance-parameter information
with GLS standard errors. It requires estimated, interior, identifiable
heterogeneity in a converged model. The teaching data above have little
between-study variation; the following separate example has enough variation
to illustrate this calculation.

```{r network-model-satterthwaite}
heterogeneous_data <- data.frame(
  study=1:9, a=rep(c("A","A","B"),3), b=rep(c("B","C","C"),3),
  effect=c(.1,.8,.4,.9,.2,-.3,-.4,.6,1.1), variance=.01
)
heterogeneous_fit <- network_meta(heterogeneous_data,"study","a","b",
  "effect","variance",reference="A",heterogeneity="common")
summary(heterogeneous_fit, inference="model", test="Satterthwaite")
```

HKSJ and residual-df model `test="t"` are unsupported for networks. These
summary choices update basic coefficients and total treatment contrasts,
including p-values under the fit's existing multiplicity adjustment. The
intervals remain pointwise. The original fit, direct/indirect tests,
heterogeneity and diagnostic tests, predictions, and rankings retain their
fitted calculations. See `?mars_inference_options` for supported combinations.

```{r profile}
network_heterogeneity_profile(fit)
```

The common-variance profile uses ML and an approximate chi-squared cutoff, including
zero in the parameter space. Coverage at a variance boundary is not guaranteed.
Study bootstrap and jackknife provide additional sensitivity checks.

## Evidence assessment and reporting

```{r assessment}
network_design_incoherence(fit)
network_nodesplit(fit)
network_influence(fit)$summary
```

Global design-by-treatment tests and local pair-specific design-deviation tests relax mean
coherence. Formal node-splitting uses independent study allocation. Descriptive
`direct`/`indirect` summaries in `fit$effects` retain shared-study covariance and
are not formal node-splitting. Neither nonsignificance nor an imposed fitted loop
closure establishes transitivity. See the incoherence vignette for interpretation.

```{r figures, fig.width=7, fig.height=5}
network_forest_plot(fit,prediction=TRUE)
network_contribution_heatmap(fit)
```

Contribution percentages are study shares of model-based contrast variance,
conditional on fitted covariance. Ranking probabilities describe uncertain mean
treatment ordering, not clinical importance or certainty of evidence. Use
`network_rankings()` with the appropriate benefit direction. Its draws retain the
full covariance of basic treatment effects and condition on fitted heterogeneity.
SUCRA is reported as a simulated percentage. See `?network_rankings` for details
on the Gaussian draws, CR1 covariance, Monte Carlo variability, and the
relationship between expected Gaussian SUCRA and the analytic P-score.
