% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/simulate_smallworld.R
\name{simulate_smallworld}
\alias{simulate_smallworld}
\title{Simulates Small-World GGM Data}
\usage{
simulate_smallworld(
  nodes,
  density,
  rewire,
  snr = 1,
  negative_proportion,
  sample_size,
  skew = 0,
  skew_range = NULL,
  target_condition = 30,
  max_correlation = 0.8,
  max_iterations = 100
)
}
\arguments{
\item{nodes}{Numeric (length = 1).
Number of nodes in the network.
Minimum of three nodes. The total number of nodes should be between 8
and 54 to remain within the range of the empirical networks used to fit
the Weibull parameter model; values outside this range are accepted but
will trigger extrapolation and may produce a warning from
\code{\link{weibull_parameters}}.}

\item{density}{Numeric (length = 1).
Target edge density of the network after pruning the initial ring lattice.
Controls the number of nearest neighbors \code{k} each node is connected
to via \eqn{k = \mathrm{round}((\text{nodes} \times
\frac{\text{nodes}-1}{2} \times \text{density}) / \text{nodes})}, subject
to a minimum of 2 and a maximum of
\eqn{\lfloor (\text{nodes}-1)/2 \rfloor}. A ring lattice with
\code{neighbors + 1} connections per node is first generated and then
pruned to this density, introducing degree heterogeneity before rewiring.
Must be between 0 and 1. A minimum density sufficient to maintain a
connected graph is enforced; values below this threshold will produce an
informative error.}

\item{rewire}{Numeric (length = 1).
Probability of rewiring each edge. Unlike the standard Watts-Strogatz
model, rewired edges are placed using degree-weighted random selection:
node pairs with higher combined degree have a greater probability of
receiving a rewired edge (see Details). Values near 0 preserve the
pruned lattice structure; values near 1 produce approximately random
networks. The small-world regime typically occurs at intermediate values
(roughly 0.01 to 0.30). Must be between 0 and 1.}

\item{snr}{Numeric (length = 1).
Signal-to-noise ratio of the absolute partial correlation weights,
defined as \eqn{\bar{|w|} / \mathrm{SD}(|w|)}. Values less than 1
produce wider, more heterogeneous weight distributions; values greater
than 1 produce narrower, more homogeneous distributions. Empirically
observed SNR values ranged from 0.648 to 1.712; values outside this
range are accepted but will trigger a warning. Defaults to \code{1}.}

\item{negative_proportion}{Numeric (length = 1).
Proportion of edges that are negative (inhibitory).
Must be between 0 and 0.50. The upper bound of 0.50 is a mathematical
constraint of the sign-flipping procedure used to assign negative edges
(see Details). If not provided, a value is sampled from a truncated
normal distribution reflecting the empirical distribution of true
negative partial correlations across 194 psychometric networks:
mean = 0.34, SD = 0.086, bounded to \eqn{[0.083, 0.50]}.}

\item{sample_size}{Numeric (length = 1).
Number of observations to generate from the population multivariate
normal distribution. Also influences the predicted Weibull scale
parameter via \code{\link{weibull_parameters}}: larger samples are
associated with smaller, more precisely estimated edge weights.}

\item{skew}{Numeric (length = 1 or \code{nodes}).
Skew applied to each variable after generation from the multivariate
normal. Can be a single value (applied to all variables) or one value
per variable. Values are rounded to the nearest increment of 0.05 in
the range \eqn{[-2, 2]}. Defaults to \code{0} (no skew).}

\item{skew_range}{Numeric (length = 2).
If provided, a skew value is drawn uniformly from this range for each
variable, overriding \code{skew}. Both values must be between -2 and 2.}

\item{target_condition}{Numeric (length = 1).
Target condition number (using \code{\link{kappa}} with \code{exact =
TRUE}) applied when ridge regularization is needed to recover a positive
definite precision matrix. The smallest ridge penalty \eqn{\lambda} that
brings the condition number to this target is found via root-finding
(\code{\link{uniroot}}), subject to a maximum shrinkage of approximately
23\% following Peeters et al. (2020). Lower values produce
better-conditioned matrices. Defaults to \code{30}. Values up to
\code{100} are accepted but not recommended.}

\item{max_correlation}{Numeric (length = 1).
Maximum allowed absolute pairwise correlation in the population
correlation matrix \code{R}. Any draw where
\code{max(abs(R[lower.tri(R)])) > max_correlation} is rejected and a
new attempt is made. Must be between 0 and 1. Defaults to \code{0.80}.}

\item{max_iterations}{Numeric (length = 1).
Maximum number of attempts to find (1) a connected network structure,
(2) a network satisfying the small-world screening criterion, and (3) a
valid set of edge weights. The error message reports a frequency table
of rejection reasons to assist with diagnosing convergence failures.
Defaults to \code{100}.}
}
\value{
A named list with four elements:

\item{data}{Numeric matrix of dimension \code{sample_size x nodes}
containing the simulated observations drawn from the population GGM.
Rows are cases; columns are variables named \code{V01}, \code{V02},
etc. Values are continuous (or skewed continuous when \code{skew != 0}).
To produce ordinal data, pass the columns through
\code{\link{categorize}}.}

\item{parameters}{
A list of input, derived, and estimated parameters:
\itemize{
  \item \code{nodes} --- Number of nodes (as supplied)
  \item \code{density} --- Target edge density (as supplied)
  \item \code{neighbors} --- Number of nearest neighbors \code{k} derived
  from \code{nodes} and \code{density}; the initial ring lattice uses
  \code{neighbors + 1} connections before pruning
  \item \code{rewire} --- Edge rewiring probability (as supplied)
  \item \code{negative_proportion} --- Proportion of negative edges,
  either as supplied or as sampled from the empirical distribution
  \item \code{sample_size} --- Number of simulated observations
  \item \code{skew} --- Named numeric vector of per-variable skew values
  actually applied (after rounding and possible resampling)
  \item \code{weibull} --- Named numeric vector of length 2 giving the
  Weibull \code{shape} and \code{scale} parameters of the absolute edge
  weight distribution actually used. If ridge conditioning was applied,
  these are re-estimated from the conditioned network via MLE.
  \item \code{omega} --- Smallworldness omega statistic of the generated
  network (Telesford et al., 2011). Values near zero indicate small-world
  structure; negative values indicate lattice-like structure; positive
  values indicate random-like structure (see \code{\link[L0ggm]{smallworldness}})
  \item \code{Q} --- Newman-Girvan modularity of the population network
  (\code{Omega}) computed via \code{igraph::modularity} on absolute edge
  weights, using the community partition returned by
  \code{igraph::cluster_leiden} with \code{objective_function =
  "modularity"}. Because \code{cluster_leiden} is a heuristic algorithm,
  \code{Q} reflects a high-quality but not necessarily optimal partition.
  Values near zero indicate absence of community structure, consistent
  with the network theory of psychopathology.
}
}

\item{population}{
Population-level network parameters:
\itemize{
  \item \code{R} --- Population correlation matrix derived from the GGM
  via \code{pcor2cor}
  \item \code{Omega} --- Population partial correlation matrix (the GGM
  edge weight matrix), with zeros for absent edges
}
}

\item{convergence}{
Iteration and conditioning diagnostics:
\itemize{
  \item \code{iterations} --- Number of sampling attempts needed to find
  a valid network
  \item \code{rejections} --- Character vector recording the rejection
  reason for each failed attempt. Common reasons include disconnected
  graph structure, omega exceeding the small-world threshold, condition
  number exceeding \code{target_condition}, and maximum correlation
  exceeding \code{max_correlation}
  \item \code{lambda} --- Ridge regularization parameter \eqn{\lambda}
  added to the diagonal of the precision matrix to ensure positive
  definiteness; \code{NA} if no conditioning was required
  \item \code{condition} --- Condition number of the final population
  correlation matrix \code{R}
}
}
}
\description{
Simulates data from a Gaussian Graphical Model (GGM) with a small-world
network structure. The generative process proceeds in three stages. First,
a ring lattice is constructed with \code{neighbors + 1} nearest-neighbor
connections per node, where \code{neighbors} is derived from \code{nodes}
and \code{density}. Second, the lattice is randomly pruned to the target
\code{density}, introducing degree heterogeneity from the outset. Third,
edges are rewired with probability \code{rewire}, where rewired edges are
placed preferentially on node pairs with higher combined degree (degree-
weighted rewiring). This approach produces more realistic degree
distributions than standard Watts-Strogatz rewiring while preserving
the local clustering structure of the lattice. Edge weights are assigned
by structural priority: edges retained from the pruned lattice receive
larger partial correlation weights based on their original neighbor
distance, grounded in the empirical observation that shorter-distance
connections tend to carry stronger weights in psychometric networks.
The resulting network is used to generate multivariate normal (or skewed)
data. Parameters do not have default values (except
\code{negative_proportion}, \code{snr}, \code{target_condition},
\code{max_correlation}, and \code{max_iterations}) and must each be set.
See Details and Examples to get started.
}
\details{
\strong{Lattice generation and pruning}

The generative process begins by constructing a ring lattice with
\code{neighbors + 1} nearest-neighbor connections per node via
\code{\link[igraph]{sample_smallworld}} with \code{p = 0}. The
\code{+1} overshoot ensures the lattice always has more edges than the
target density, guaranteeing that pruning can proceed. The lattice is
then randomly pruned to the target \code{density} by removing edges
uniformly at random, subject to the constraint that the pruned graph
remains connected. Because removal is random, different nodes lose
different numbers of edges, producing a heterogeneous degree distribution
before any rewiring occurs. This heterogeneity provides a non-uniform
prior for the subsequent degree-weighted rewiring step.

\strong{Degree-weighted rewiring}

Each edge in the pruned lattice is independently selected for rewiring
with probability \code{rewire}. For each selected edge \eqn{(i, j)},
node \eqn{i} is kept fixed and the \eqn{j} endpoint is redirected to a
new target node. Valid targets are restricted to node pairs involving
node \eqn{i} that (1) are not currently connected, and (2) have never
been occupied during the current rewiring pass (i.e., were absent in
the original pruned lattice). Among valid targets, the new endpoint is
selected with probability proportional to \eqn{\sqrt{d_i + d_k}}, where
\eqn{d_i} and \eqn{d_k} are the current degrees of the two nodes in
the candidate pair. The square-root transformation moderates the
rich-get-richer tendency of linear preferential attachment, producing
degree heterogeneity consistent with the empirical range of psychometric
networks without generating extreme hubs. Node degrees are updated
incrementally after each rewire so that subsequent rewiring steps
reflect the current graph state.

\strong{Edge weight assignment}

Edge weights are assigned by ranking edges according to their distance
in the pruned lattice before rewiring. Edges retained from the pruned
lattice receive their original neighbor distance (1 = nearest neighbor,
2 = second nearest, etc.); rewired edges are assigned a distance of
\code{neighbors + 1}, placing them at the bottom of the priority order.
Absolute edge weights are drawn from a Weibull distribution whose
parameters are predicted from the network size, sample size, and signal-
to-noise ratio using a Seemingly Unrelated Regression (SUR) model fitted
to 194 empirical psychometric networks (Huth et al., 2025). The sorted
(descending) Weibull weights are then mapped onto the distance ranking
so that the largest weights go to the shortest-distance edges. This
assignment is grounded in the empirical observation that shorter-distance
local connections tend to carry larger partial correlation weights in
psychometric networks.

\strong{Negative edge assignment}

Negative edges are introduced by flipping the signs of a subset of
nodes — multiplying all edges incident to those nodes by -1. The number
of nodes to flip is derived from \code{negative_proportion} via the
inversion formula \eqn{(1 - \sqrt{1 - 2p}) / 2}, where \eqn{p} is the
target proportion of negative edges. This formula assumes that an edge
is negative if and only if exactly one of its endpoints is flipped,
giving an expected negative proportion of \eqn{2 \cdot (k/n) \cdot
(1 - k/n)} for \eqn{k} flipped nodes out of \eqn{n} total. The formula
requires \eqn{p \leq 0.50}, which is why \code{negative_proportion} is
bounded at 0.50.
}
\examples{
# Basic small-world network (moderate density, moderate rewiring)
result <- simulate_smallworld(
  nodes = 20,
  density = 0.30,
  rewire = 0.20,
  sample_size = 500
)

# Lattice-like structure (low rewiring preserves local connectivity)
result <- simulate_smallworld(
  nodes = 20,
  density = 0.30,
  rewire = 0.01,
  sample_size = 500
)

# Random-like structure (high rewiring destroys lattice regularity)
result <- simulate_smallworld(
  nodes = 20,
  density = 0.30,
  rewire = 0.80,
  sample_size = 500
)

# Fix the proportion of negative edges
result <- simulate_smallworld(
  nodes = 20,
  density = 0.30,
  rewire = 0.20,
  sample_size = 500,
  negative_proportion = 0.20
)

}
\references{
\strong{Seminal introduction to the Watts-Strogatz small-world model} \cr
Watts, D. J., & Strogatz, S. H. (1998).
Collective dynamics of 'small-world' networks.
\emph{Nature}, \emph{393}(6684), 440--442.

\strong{Logic for weight assignments} \cr
Muldoon, S. F., Bridgeford, E. W., & Bassett, D. S. (2016).
Small-world propensity and weighted brain networks.
\emph{Scientific Reports}, \emph{6}(1), 22057.

\strong{Analytical approximation of random-graph average path length} \cr
Newman, M. E. J., Strogatz, S. H., & Watts, D. J. (2001).
Random graphs with arbitrary degree distributions and their applications.
\emph{Physical Review E}, \emph{64}(2), 026118.

\strong{Empirical network data used to fit the Weibull SUR model} \cr
Huth, K. B. S., Haslbeck, J. M. B., Keetelaar, S., Van Holst, R. J., &
Marsman, M. (2025). Statistical evidence in psychological networks.
\emph{Nature Human Behaviour}.

\strong{Maximum ridge shrinkage bound} \cr
Peeters, C. F., van de Wiel, M. A., & van Wieringen, W. N. (2020).
The spectral condition number plot for regularization parameter evaluation.
\emph{Computational Statistics}, \emph{35}(2), 629--646.
}
\author{
Alexander P. Christensen <alexpaulchristensen@gmail.com>
}
