% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ergm.R, R/ergm.utility.R, R/is.na.ergm.R,
%   R/logLik.ergm.R, R/print.ergm.R, R/vcov.ergm.R
\name{ergm}
\alias{ergm}
\alias{is.ergm}
\alias{ergm.object}
\alias{is.na.ergm}
\alias{anyNA.ergm}
\alias{nobs.ergm}
\alias{print.ergm}
\alias{vcov.ergm}
\title{Exponential-Family Random Graph Models}
\usage{
ergm(
  formula,
  response = NULL,
  reference = ~Bernoulli,
  constraints = ~.,
  obs.constraints = ~. - observed,
  offset.coef = NULL,
  target.stats = NULL,
  eval.loglik = getOption("ergm.eval.loglik"),
  estimate = c("MLE", "MPLE", "CD"),
  control = control.ergm(),
  verbose = FALSE,
  ...,
  basis = ergm.getnetwork(formula),
  newnetwork = c("one", "all", "none")
)

is.ergm(object)

\method{is.na}{ergm}(x)

\method{anyNA}{ergm}(x, ...)

\method{nobs}{ergm}(object, ...)

\method{print}{ergm}(x, digits = max(3, getOption("digits") - 3), ...)

\method{vcov}{ergm}(object, sources = c("all", "model", "estimation"), ...)
}
\arguments{
\item{formula}{An \R \code{\link{formula}} object, of the form
\code{y ~ <model terms>}, where \code{y} is a
\code{\link[network]{network}} object or a matrix that can be
coerced to a \code{\link[network]{network}} object.  For the
details on the possible \code{<model terms>}, see
\code{\link{ergmTerm}} and Morris, Handcock and Hunter (2008)
for binary ERGM terms and Krivitsky (2012) for valued ERGM terms
(terms for weighted edges).  To create a
\code{\link[network]{network}} object in \R, use the
\code{network()} function, then add nodal attributes to it using
the \code{\%v\%} operator if necessary. Enclosing a model term in
\code{offset()} fixes its value to one specified in
\code{offset.coef}.  (A second argument---a logical or numeric
index vector---can be used to select \emph{which} of the parameters
within the term are offsets.)}

\item{response}{Either a character string, a formula, or \code{NULL} (the default), to specify the response attributes and whether the ERGM is binary or valued. Interpreted as follows: \describe{

\item{\code{NULL}}{Model simple presence or absence, via a binary ERGM.}

\item{character string}{The name of the edge attribute whose value is to be modeled. Type of ERGM will be determined by whether the attribute is \code{\link{logical}} (\code{TRUE}/\code{FALSE}) for binary or \code{\link{numeric}} for valued.}

\item{a formula}{must be of the form \code{NAME~EXPR|TYPE} (with \code{|} being literal). \code{EXPR} is evaluated in the formula's environment with the network's edge attributes accessible as variables. The optional \code{NAME} specifies the name of the edge attribute into which the results should be stored, with the default being a concise version of \code{EXPR}. Normally, the type of ERGM is determined by whether the result of evaluating \code{EXPR} is logical or numeric, but the optional \code{TYPE} can be used to override by specifying a scalar of the type involved (e.g., \code{TRUE} for binary and \code{1} for valued).}

}}

\item{reference}{A one-sided formula specifying
the reference measure (\eqn{h(y)}) to be used.
See help for \link[=ergm-references]{ERGM reference measures} implemented in the
\strong{\link[=ergm-package]{ergm}} package.}

\item{constraints}{A formula specifying one or more constraints
on the support of the distribution of the networks being modeled. Multiple constraints
may be given, separated by \dQuote{+} and \dQuote{-} operators. See
\code{\link{ergmConstraint}} for the detailed explanation of
their semantics and also for an indexed list of the constraints visible to the \pkg{ergm} package.

The default is to have no constraints except those provided through
the \code{\link{ergmlhs}} API.

Together with the model terms in the formula and the reference measure, the constraints
define the distribution of networks being modeled.

It is also possible to specify a proposal function directly either
by passing a string with the function's name (in which case,
arguments to the proposal should be specified through the
\code{MCMC.prop.args} argument to the relevant control function, or
by giving it on the LHS of the hints formula to \code{MCMC.prop}
argument to the control function. This will override
the one chosen automatically.

Note that not all possible combinations of constraints and reference
measures are supported. However, for relatively simple constraints
(i.e., those that simply permit or forbid specific dyads or sets of
dyads from changing), arbitrary combinations should be possible.}

\item{obs.constraints}{A one-sided formula specifying one or more
constraints or other modification \emph{in addition} to those
specified by \code{constraints}, following the same syntax as the
\code{constraints} argument.

This allows the domain of the integral in the numerator of the
partially obseved network face-value likelihoods of Handcock and
Gile (2010) and Karwa et al. (2017) to be specified explicitly.

The default is to constrain the integral to only integrate over
the missing dyads (if present), after incorporating constraints
provided through the \code{\link{ergmlhs}} API.

It is also possible to specify a proposal function directly by
passing a string with the function's name of the \code{obs.MCMC.prop}
argument to the relevant control function. In that case,
arguments to the proposal should be specified through the
\code{obs.prop.args} argument to the relevant control function.}

\item{offset.coef}{{A vector of coefficients for the offset terms.}}

\item{target.stats}{{vector of "observed network statistics,"
if these statistics are for some reason different than the
actual statistics of the network on the left-hand side of
\code{formula}.
Equivalently, this vector is the mean-value parameter values for the
model.  If this is given, the algorithm finds the natural
parameter values corresponding to these mean-value parameters.
If \code{NULL}, the mean-value parameters used are the observed
statistics of the network in the formula.
}}

\item{eval.loglik}{{Logical:  For dyad-dependent models, if TRUE, use bridge
sampling to evaluate the log-likelihoood associated with the
fit. Has no effect for dyad-independent models.
Since bridge sampling takes additional time, setting to FALSE may
speed performance if likelihood values (and likelihood-based
values like AIC and BIC) are not needed. Can be set globally via \code{option(ergm.eval.loglik=...)}, which is set to \code{TRUE} when the package is loaded. (See \code{\link[=ergm-options]{options?ergm}}.)
}}

\item{estimate}{{If "MPLE," then the maximum pseudolikelihood estimator
is returned.  If "MLE" (the default), then an approximate maximum likelihood
estimator is returned.  For certain models, the MPLE and MLE are equivalent,
in which case this argument is ignored.  (To force MCMC-based approximate
likelihood calculation even when the MLE and MPLE are the same, see the
\code{force.main} argument of \code{\link{control.ergm}}. If "CD" (\emph{EXPERIMENTAL}),
the Monte-Carlo contrastive divergence estimate is returned. )
}}

\item{control}{A list of control parameters for algorithm tuning,
typically constructed with \code{\link[=control.ergm]{control.ergm()}}. Its documentation
gives the the list of recognized control parameters and their
meaning. The more generic utility \code{\link[=snctrl]{snctrl()}} (StatNet ConTRoL)
also provides argument completion for the available control
functions and limited argument name checking.}

\item{verbose}{A logical or an integer to control the amount of
progress and diagnostic information to be printed. \code{FALSE}/\code{0}
produces minimal output, with higher values producing more
detail. Note that very high values (5+) may significantly slow
down processing.}

\item{\dots}{Additional
arguments, to be passed to lower-level functions.}

\item{basis}{a value (usually a \code{\link{network}}) to override the LHS of the formula.}

\item{newnetwork}{One of \code{"one"} (the default), \code{"all"}, or
\code{"none"} (or, equivalently, \code{FALSE}), specifying whether the
network(s) from the last iteration of the MCMC sampling should be
returned as a part of the fit as a elements \code{newnetwork} and
\code{newnetworks}. (See their entries in section Value below for
details.) Partial matching is supported.}

\item{object}{{an \code{ergm} object.}}

\item{x, digits}{See \code{\link[=print]{print()}}.}

\item{sources}{For the \code{vcov} method, specify whether to return
the covariance matrix from the ERGM model, the estimation
process, or both combined.}
}
\value{
\code{\link{ergm}} returns an object of class \code{\link{ergm}} that is a list
consisting of the following elements:
\item{coef}{The Monte Carlo maximum likelihood estimate
of \eqn{\theta}, the vector of coefficients for the model
parameters.}
\item{sample}{The \eqn{n\times p} matrix of network statistics,
where \eqn{n} is the
sample size and \eqn{p} is the number of network statistics specified in the
model, generated by the last iteration of the MCMC-based likelihood maximization routine. These statistics are centered with respect to the observed statistics or \code{target.stats}, unless missing data MLE is used.}
\item{sample.obs}{As \code{sample}, but for the constrained sample.}
\item{iterations}{The number of Newton-Raphson iterations required
before convergence.}
\item{MCMCtheta}{The value of \eqn{\theta} used to produce the Markov chain
Monte Carlo sample.  As long as the Markov chain mixes sufficiently
well, \code{sample} is roughly a random sample from the distribution
of network statistics specified by the model with the parameter equal
to \code{MCMCtheta}.  If \code{estimate="MPLE"} then
\code{MCMCtheta} equals the MPLE.}
\item{loglikelihood}{The approximate change in log-likelihood
in the last iteration.
The value is only approximate because it is estimated based
on the MCMC random sample.}
\item{gradient}{The value of the gradient vector of the approximated
loglikelihood function, evaluated at the maximizer.  This vector
should be very close to zero.}
\item{covar}{Approximate covariance matrix for the MLE, based on the inverse
Hessian of the approximated loglikelihood evaluated at the maximizer.}
\item{failure}{Logical:  Did the MCMC estimation fail?}
\item{network}{Network passed on the left-hand side of \code{formula}. If \code{target.stats} are passed, it is replaced by the network returned by \code{\link[=san]{san()}}.}
\item{newnetworks}{If argument \code{newnetwork} is \code{"all"}, a list of the final networks at the end of the MCMC
simulation, one for each thread.}
\item{newnetwork}{If argument \code{newnetwork} is \code{"one"} or \code{"all"}, the first (possibly only) element of \code{newnetworks}.}
\item{coef.init}{The initial value of \eqn{\theta}.}
\item{est.cov}{The covariance matrix of the model statistics in the final MCMC sample.}
\item{coef.hist, steplen.hist, stats.hist, stats.obs.hist}{
For the MCMLE method, the history of coefficients, Hummel step lengths, and average model statistics for each iteration..
}
\item{control}{The control list passed to the call.}
\item{etamap}{The set of functions mapping the true parameter theta
to the canonical parameter eta (irrelevant except in a curved exponential
family model)}
\item{formula}{The original \code{\link{formula}} entered into the \code{\link{ergm}} function.}
\item{target.stats}{The target.stats used during estimation (passed through from the Arguments)}
\item{target.esteq}{Used for curved models to preserve the target mean values of the curved terms. It is identical to target.stats for non-curved models.}
\item{constraints}{Constraints used during estimation (passed through from the Arguments)}
\item{reference}{The reference measure used during estimation (passed through from the Arguments)}
\item{estimate}{The estimation method used (passed through from the Arguments).}
\item{offset}{vector of logical telling which model parameters are to be set
at a fixed value (i.e., not estimated).}

\item{drop}{If \code{\link[=control.ergm]{control$drop}=TRUE}, a numeric vector indicating which terms were dropped due to to extreme values of the
corresponding statistics on the observed network, and how:
\describe{
\item{\code{0}}{The term was not dropped.}
\item{\code{-1}}{The term was at its minimum and the coefficient was fixed at
\code{-Inf}.}
\item{\code{+1}}{The term was at its maximum and the coefficient was fixed at
\code{+Inf}.}
}
}

\item{estimable}{A logical vector indicating which terms could not be
estimated due to a \code{constraints} constraint fixing that term at a
constant value.
}

\item{info}{A list with miscellaneous information that would typically be accessed by the user via methods; in general, it should not be accessed directly. Current elements include: \describe{

\item{\code{terms_dind}}{Logical indicator of whether the model terms are all dyad-independent.}

\item{\code{space_dind}}{Logical indicator of whether the sample space (constraints) are all dyad-independent.}

\item{\code{n_info_dyads}}{Number of \dQuote{informative} dyads: those that are observed (not missing) \emph{and} not constrained by sample space constraints; one of the measures of sample size.}

\item{\code{obs}}{Logical indicator of whether an observational (missing data) process was involved in estimation.}

\item{\code{valued}}{Logical indicator of whether the model is valued.}

}}

\item{null.lik}{Log-likelihood of the null model. Valid only for
unconstrained models.}
\item{mle.lik}{The approximate log-likelihood for the MLE.
The value is only approximate because it is estimated based
on the MCMC random sample.}
}
\description{
\code{\link{ergm}} is used to fit exponential-family random graph
models (ERGMs), in which
the probability of a given network, \eqn{y}, on a set of nodes is
\eqn{h(y) \exp\{\eta(\theta) \cdot
g(y)\}/c(\theta)}, where
\eqn{h(y)} is the reference measure (usually \eqn{h(y)=1}),
\eqn{g(y)} is a vector of network statistics for \eqn{y},
\eqn{\eta(\theta)} is a natural parameter vector of the same
length (with \eqn{\eta(\theta)=\theta} for most terms), and \eqn{c(\theta)} is the
normalizing constant for the distribution.
\code{\link{ergm}} can return a maximum pseudo-likelihood
estimate, an approximate maximum likelihood estimate based on a Monte
Carlo scheme, or an approximate contrastive divergence estimate based
on a similar scheme.
(For an overview of the package \insertCite{HuHa08e,KrHu23e}{ergm}, see \code{\link{ergm-package}}.)
}
\section{Methods (by generic)}{
\itemize{
\item \code{is.na(ergm)}: Return \code{TRUE} if the ERGM was fit to a partially observed network and/or an observational process, such as missing (\code{NA}) dyads.

\item \code{anyNA(ergm)}: Alias to the \code{is.na()} method.

\item \code{nobs(ergm)}: Return the number of informative dyads of a model fit.

\item \code{print(ergm)}: Print the call, the estimate, and the method used to obtain it.

\item \code{vcov(ergm)}: extracts the variance-covariance matrix of
parameter estimates.

}}
\section{Notes on model specification}{

Although each of the statistics in a given model is a summary
statistic for the entire network, it is rarely necessary to
calculate statistics for an entire network
in a proposed Metropolis-Hastings step.
Thus, for example, if the triangle term is included in the model,
a census of all triangles in the observed network is never
taken; instead, only the change in the number of triangles
is recorded for each edge toggle.

In the implementation of \code{\link{ergm}}, the model is
initialized in \R, then all the model information is passed to a C
program that generates the sample of network statistics using MCMC.
This sample is then returned to \R, which then uses one of several
algorithms, selected by \verb{main.method=} \code{\link[=control.ergm]{control.ergm()}} parameter
to update the estimate.

The mechanism for proposing new networks for the MCMC sampling
scheme, which is a Metropolis-Hastings algorithm, depends on
two things:  The \code{constraints}, which define the set of possible
networks that could be proposed in a particular Markov chain step,
and the weights placed on these possible steps by the
proposal distribution.  The former may be controlled using the
\code{constraints} argument described above.  The latter may
be controlled using the \code{prop.weights} argument to the
\code{\link{control.ergm}} function.

The package is designed so that the user could conceivably add additional
proposal types.
}

\examples{
\donttest{
#
# load the Florentine marriage data matrix
#
data(flo)
#
# attach the sociomatrix for the Florentine marriage data
# This is not yet a network object.
#
flo
#
# Create a network object out of the adjacency matrix
#
flomarriage <- network(flo,directed=FALSE)
flomarriage
#
# print out the sociomatrix for the Florentine marriage data
#
flomarriage[,]
#
# create a vector indicating the wealth of each family (in thousands of lira) 
# and add it as a covariate to the network object
#
flomarriage \%v\% "wealth" <- c(10,36,27,146,55,44,20,8,42,103,48,49,10,48,32,3)
flomarriage
#
# create a plot of the social network
#
plot(flomarriage)
#
# now make the vertex size proportional to their wealth
#
plot(flomarriage, vertex.cex=flomarriage \%v\% "wealth" / 20, main="Marriage Ties")
#
# Use 'data(package = "ergm")' to list the data sets in a
#
data(package="ergm")
#
# Load a network object of the Florentine data
#
data(florentine)
#
# Fit a model where the propensity to form ties between
# families depends on the absolute difference in wealth
#
gest <- ergm(flomarriage ~ edges + absdiff("wealth"))
summary(gest)
#
# add terms for the propensity to form 2-stars and triangles
# of families 
#
gest <- ergm(flomarriage ~ kstar(1:2) + absdiff("wealth") + triangle)
summary(gest)

# import synthetic network that looks like a molecule
data(molecule)
# Add a attribute to it to mimic the atomic type
molecule \%v\% "atomic type" <- c(1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3)
#
# create a plot of the social network
# colored by atomic type
#
plot(molecule, vertex.col="atomic type",vertex.cex=3)

# measure tendency to match within each atomic type
gest <- ergm(molecule ~ edges + kstar(2) + triangle + nodematch("atomic type"))
summary(gest)

# compare it to differential homophily by atomic type
gest <- ergm(molecule ~ edges + kstar(2) + triangle
                        + nodematch("atomic type",diff=TRUE))
summary(gest)
}
\donttest{
# Extract parameter estimates as a numeric vector:
coef(gest)
# Sources of variation in parameter estimates:
vcov(gest, sources="model")
vcov(gest, sources="estimation")
vcov(gest, sources="all") # the default
}
}
\references{
\insertAllCited{}

Admiraal R, Handcock MS (2007).
\pkg{networksis}: Simulate bipartite graphs with fixed
marginals through sequential importance sampling.
Statnet Project, Seattle, WA.
Version 1. \url{https://statnet.org}.

Bender-deMoll S, Morris M, Moody J (2008).
Prototype Packages for Managing and Animating Longitudinal
Network Data: \pkg{dynamicnetwork} and \pkg{rSoNIA}.
\emph{Journal of Statistical Software}, 24(7).
\doi{10.18637/jss.v024.i07}

Butts CT (2007).
\pkg{sna}: Tools for Social Network Analysis.
R package version 2.3-2. \url{https://cran.r-project.org/package=sna}.

Butts CT (2008).
\pkg{network}: A Package for Managing Relational Data in \R.
\emph{Journal of Statistical Software}, 24(2).
\doi{10.18637/jss.v024.i02}

Butts C (2015).
\pkg{network}: The Statnet Project (https://statnet.org). R package version 1.12.0, \url{https://cran.r-project.org/package=network}.

Goodreau SM, Handcock MS, Hunter DR, Butts CT, Morris M (2008a).
A \pkg{statnet} Tutorial.
\emph{Journal of Statistical Software}, 24(8).
\doi{10.18637/jss.v024.i08}

Goodreau SM, Kitts J, Morris M (2008b).
Birds of a Feather, or Friend of a Friend? Using Exponential
Random Graph Models to Investigate Adolescent Social Networks.
\emph{Demography}, 45, in press.

Handcock, M. S. (2003)
\emph{Assessing Degeneracy in Statistical Models of Social Networks},
Working Paper #39,
Center for Statistics and the Social Sciences,
University of Washington.
\url{https://csss.uw.edu/research/working-papers/assessing-degeneracy-statistical-models-social-networks}

Handcock MS (2003b).
\pkg{degreenet}: Models for Skewed Count Distributions Relevant
to Networks.
Statnet Project, Seattle, WA.
Version 1.0, \url{https://statnet.org}.

Handcock MS and Gile KJ (2010). Modeling Social Networks from Sampled Data. \emph{Annals of Applied Statistics}, 4(1), 5-25. \doi{10.1214/08-AOAS221}

Handcock MS, Hunter DR, Butts CT, Goodreau SM, Morris M (2003a).
\pkg{ergm}: A Package to Fit, Simulate and Diagnose
Exponential-Family Models for Networks.
Statnet Project, Seattle, WA.
Version 2, \url{https://statnet.org}.

Handcock MS, Hunter DR, Butts CT, Goodreau SM, Morris M (2003b).
\pkg{statnet}: Software Tools for the Statistical Modeling of
Network Data.
Statnet Project, Seattle, WA.
Version 2, \url{https://statnet.org}.

Hunter, D. R. and Handcock, M. S. (2006)
\emph{Inference in curved exponential family models for networks},
Journal of Computational and Graphical Statistics.

Hunter DR, Handcock MS, Butts CT, Goodreau SM, Morris M (2008b).
\pkg{ergm}: A Package to Fit, Simulate and Diagnose
Exponential-Family Models for Networks.
\emph{Journal of Statistical Software}, 24(3).
\doi{10.18637/jss.v024.i03}

Karwa V, Krivitsky PN, and Slavkovi\'c AB (2017). Sharing Social Network
Data: Differentially Private Estimation of Exponential-Family Random
Graph Models. \emph{Journal of the Royal Statistical Society, Series
C}, 66(3):481--500. \doi{10.1111/rssc.12185}

Krivitsky PN (2012). Exponential-Family Random Graph Models for Valued
Networks. \emph{Electronic Journal of Statistics}, 2012, 6,
1100-1128. \doi{10.1214/12-EJS696}

Morris M, Handcock MS, Hunter DR (2008).
Specification of Exponential-Family Random Graph Models:
Terms and Computational Aspects.
\emph{Journal of Statistical Software}, 24(4).
\doi{10.18637/jss.v024.i04}

Snijders, T.A.B. (2002),
Markov Chain Monte Carlo Estimation of Exponential Random Graph Models.
Journal of Social Structure.
Available from
\url{https://www.cmu.edu/joss/content/articles/volume3/Snijders.pdf}.
}
\seealso{
\code{\link{network}}, \code{\link{\%v\%}}, \code{\link{\%n\%}}, \code{\link{ergmTerm}}, \code{\link{ergmMPLE}},
\code{\link[=summary.ergm]{summary.ergm()}}
}
\keyword{models}
