Estimation API Reference

This page documents the functions for data loading, observation generation, and model fitting.

Data Loading

load_events

REM.load_events — Function
load_events(filepath::String; kwargs...) -> EventSequence

Load events from a CSV file.

Arguments

  • filepath: Path to the CSV file

Keyword Arguments

  • sender_col::Symbol=:sender: Column name for sender IDs
  • receiver_col::Symbol=:receiver: Column name for receiver IDs
  • time_col::Symbol=:time: Column name for timestamps
  • type_col::Union{Symbol,Nothing}=nothing: Column name for event types
  • weight_col::Union{Symbol,Nothing}=nothing: Column name for event weights
  • time_type::Type=Float64: Type to parse timestamps as
  • actor_names::Bool=false: If true, treat sender/receiver as names and assign numeric IDs

Returns

  • EventSequence: Sequence of loaded events. The actor universe is inferred from the event endpoints (actors_declared == false): declare it before fitting — EventSequence(collect(seq); actors=ActorSet(ids)) — or pass at_risk= to fit_rem, which otherwise warns.

Example

using REM, CSV, DataFrames
path = joinpath(mktempdir(), "events.csv")
CSV.write(path, DataFrame(sender=[1, 2, 1], receiver=[2, 1, 3], time=[1.0, 2.0, 3.0]))
seq = load_events(path)
length(seq), seq.n_actors            # (3, 3)
named = joinpath(mktempdir(), "named.csv")
CSV.write(named, DataFrame(from=["Ann", "Bob"], to=["Bob", "Ann"], t=[1.0, 2.0]))
load_events(named; sender_col=:from, receiver_col=:to, time_col=:t, actor_names=true)
source
load_events(df::DataFrame; kwargs...) -> EventSequence

Load events from a DataFrame (same keywords as the file method: sender_col, receiver_col, time_col, type_col, weight_col, time_type, actor_names). String timestamps are parsed as time_type (Float64, Int, DateTime or Date).

Example

using REM, DataFrames, Dates
df = DataFrame(sender=[1, 2, 1], receiver=[2, 1, 3], time=[1.0, 2.0, 3.0],
               kind=[:email, :email, :call], w=[1.0, 2.0, 1.0])
seq = load_events(df; type_col=:kind, weight_col=:w)
seq[2].weight, seq.eventtypes          # (2.0, Set([:email, :call]))
stamped = DataFrame(sender=[1, 2], receiver=[2, 1],
                    time=["2024-01-01T10:00:00", "2024-01-01T11:00:00"])
load_events(stamped; time_type=DateTime)[1].time    # DateTime("2024-01-01T10:00:00")
source
REM.load_events! — Function
load_events!(seq::EventSequence, filepath::String; kwargs...)

Load events from a CSV file and add them to an existing EventSequence (inserted in time order). Same keywords as load_events except time_type, which is the sequence's clock.

Example

using REM, CSV, DataFrames
path = joinpath(mktempdir(), "more.csv")
CSV.write(path, DataFrame(sender=[3, 1], receiver=[1, 3], time=[2.5, 4.0]))
seq = EventSequence([Event(1, 2, 1.0), Event(2, 1, 3.0)]; actors=ActorSet(1:3))
load_events!(seq, path)
[e.time for e in seq]           # [1.0, 2.5, 3.0, 4.0]
source
load_events!(seq::EventSequence, df::DataFrame; kwargs...)

Load events from a DataFrame and add them to an existing EventSequence (inserted in time order). With actor_names=true, pass the same name_to_id dictionary across calls to keep the name → ID assignment stable.

Example

using REM, DataFrames
seq = EventSequence{Float64}(; actors=ActorSet(1:3))
load_events!(seq, DataFrame(sender=[1, 2], receiver=[2, 1], time=[1.0, 2.0]))
load_events!(seq, DataFrame(sender=[3], receiver=[1], time=[1.5]))
[(e.sender, e.receiver) for e in seq]     # [(1, 2), (3, 1), (2, 1)]
source

Observation Generation

The design is the DataFrame that generate_observations returns (one row per case or control: event_index, sender, receiver, is_event, stratum, risk_set_size, sampling_prob, tie_weight and one column per statistic); a hand-built design is a DataFrame with at least is_event, stratum and the statistic columns.

CaseControlSampler

REM.CaseControlSampler — Type
CaseControlSampler

Generates observations using case-control sampling. For each observed event (case), samples a specified number of non-events (controls) from the risk set.

Fields

  • n_controls::Int: Number of control samples per case (controls are drawn without replacement; when fewer distinct dyads exist the full risk set is enumerated instead, with a one-time warning)
  • exclude_self_loops::Bool: Whether to exclude self-loops from sampling

The sampler holds no random state: the control draw comes from the rng keyword of generate_observations (or fit_rem), the ecosystem's one randomness keyword.

Example

using REM, Random
sampler = CaseControlSampler(n_controls=100)
seq = EventSequence([Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 3, 3.0)];
                    actors=ActorSet(1:4))
obs = generate_observations(seq, [Repetition()], sampler; rng=Xoshiro(42))   # 12 dyads: full risk set
size(obs, 1)                                                # 3 cases + 3·11 controls = 36
source

generate_observations

REM.generate_observations — Function
generate_observations(seq::EventSequence, stats, sampler::CaseControlSampler;
                      kwargs...) -> DataFrame

Generate observations for model estimation using case-control sampling.

Arguments

  • seq::EventSequence: The event sequence to analyze
  • stats: Statistics to compute (a StatisticSet or a vector of statistics; vectors are converted to a tuple-backed StatisticSet internally so the inner loop is dispatch-free)
  • sampler::CaseControlSampler: Sampling configuration

Keyword Arguments

  • start_index::Int=1: Index of first event to include as a case (the events before it build the network state only). A tie block that straddles start_index is treated as a tie: under ties=:error it is refused, under :breslow/:efron the earlier members of the block do not enter the state before the block's own strata are built (they are the block's other tied cases, Efron-weighted under :efron), and only :ordered absorbs them first

  • end_index::Int=length(seq): Index of last event to include

  • decay::Float64=0.0: Exponential decay rate for network state (eventnet's halflife model — halflife_to_decay(h); the only memory model eventnet offers)

  • window=nothing: Sliding window — events older than current_time − window stop counting in every count, degree and adjacency set. A Real in the clock's units (seconds for Date/DateTime), or a Dates.Period (Day(2)) on a calendar clock. The fixed-memory alternative to decay; mutually exclusive with decay > 0 (ArgumentError). window=Inf is no window. See EventNetworkState.

  • at_risk=nothing: The risk set. One of

    • nothing: the sequence's actor universe (seq.actors)
    • an ActorSet, Set{Int} or Vector{Int}: a static actor universe
    • a RiskSet: a static (possibly asymmetric) sender/receiver risk set
    • a list of (sender, receiver) pairs (or RiskSet(i, pairs)): a dyad-level risk set — exactly the listed dyads are at risk
    • a Vector of such specs, one per event: per-event (time-varying) risk sets
    • a callback (event_index::Int, state::EventNetworkState) -> RiskSet (or an actor collection), evaluated at each event against the current network state
  • directed::Bool=true: false treats the events as undirected: each event is rewritten as the pair (min, max) and the risk set holds the unordered pairs s < r of a symmetric actor set (n(n−1)/2 of them), not the n(n−1) ordered dyads. Use undirected statistics with it (Repetition(directed=false), CommonNeighbors, …): a directed statistic would read the pair in ID order, which carries no meaning

  • ties::Symbol=:error: how to handle tied timestamps (the shared NetworkCore.TIE_POLICIES vocabulary). The statistics of an event are read off the network state as it stands before it, so ordering a tie is not a mere sort: it lets the event placed first enter the statistics of the event placed second.

    • :error (default) — refuse: name the tie and throw
    • :ordered — sequence order, no correction (the legacy behaviour)
    • :breslow — the Breslow correction: the tied events share one risk set (the network state is frozen across the tie block and absorbs the whole block at once) and each is a stratum with the same denominator. Valid with sampled controls: each stratum is an ordinary nested-case-control stratum
    • :efron — the Efron correction: as :breslow, and the d tied cases enter the denominator of the j-th of their strata with weight 1 − (j−1)/d (carried in the tie_weight column). Matches survival::coxph(..., ties="efron"). Full risk set only: a tie block whose risk set would be sampled is refused (see REM.check_tie_sampling for why)
    • :batch — rejected here, with a pointer to :breslow (see NetworkCore.check_tie_policy)

    On tie-free data every policy produces the identical design — a tie correction on untied data is a no-op, and that is tested.

  • eventtypes::Symbol=:error: a sequence with more than one event type is refused until you say how the types enter the model. :pool makes every event a case and lets untyped statistics count all types together; OfType statistics read one type's history.

  • cases_of=nothing: an event type (or a collection of types) to model — only those events are cases, every event still builds the history. The likelihood is then conditional on the type of each event. Combine with OfType statistics for type-specific effects.

  • rng::AbstractRNG=Random.default_rng(): the source of the control draw, so generate_observations(...; rng=Xoshiro(9)) is reproducible — never the global RNG behind the caller's back.

Every case is validated against its own risk set, and each risk set must admit at least one control; both throw an ArgumentError otherwise.

The stream is processed in O(events): the per-event cost is the statistics of one case and n_controls controls, independent of the number of actors (a static risk set's dyad count is computed once; the design is accumulated column-major into one matrix rather than one vector per row). Memory is the design itself.

Returns

  • DataFrame: Observations with columns for each statistic, plus event_index, sender, receiver, is_event, stratum, risk_set_size, sampling_prob and tie_weight. The policy that was actually applied is attached as the DataFrame metadata key "tie_method" (:none when the data had no ties), so fit_rem(::DataFrame, ...) can report the truth without being told again.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 3, 3.0), Event(3, 2, 4.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
stats = [Repetition(), Reciprocity()]
obs = generate_observations(seq, stats, CaseControlSampler(n_controls=5);
                            rng=Xoshiro(1))              # rng-driven, reproducible
size(obs, 1)                                             # 24 = 4 cases + 4·5 controls
und = generate_observations(seq, [Repetition(directed=false)],
                            CaseControlSampler(n_controls=100); directed=false)
und.risk_set_size[1]                                     # 10 = 5·4/2 unordered pairs
source

compute_statistics

REM.compute_statistics — Function
compute_statistics(seq::EventSequence, stats; decay=0.0, window=nothing,
                   ties=:error, eventtypes=:error) -> DataFrame

Compute statistics for all events in a sequence (without sampling controls): one row per event, each statistic read off the network state as it stands before that event. stats may be a StatisticSet or a vector of statistics. decay (eventnet's halflife model) and window (events older than current_time − window stop counting; a Real in clock units or a Dates.Period on a calendar clock) are the two memory models of EventNetworkState and are mutually exclusive.

ties follows the ecosystem's tied-event contract, as in generate_observations: :error (default) refuses a sequence with tied timestamps (ordering them would let the event placed first enter the statistics of its simultaneous partner); :breslow and :efron freeze the state across each tie block, so the tied events do not see each other (the two give the same statistics — they differ only in a likelihood's denominator); :ordered is sequence order. The policy that applied rides along as the "tie_method" metadata. eventtypes is as in generate_observations: a multi-type sequence is refused unless eventtypes=:pool.

Returns

  • DataFrame: One row per event with sender, receiver, time and the computed statistics

Example

using REM
seq = EventSequence([Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0)]; actors=ActorSet(1:3))
df = compute_statistics(seq, [Repetition(), Reciprocity()])
df.repetition           # [0.0, 0.0, 1.0]
df.reciprocity          # [0.0, 1.0, 1.0]
dfw = compute_statistics(seq, [Repetition()]; window=1.0)
dfw.repetition          # [0.0, 0.0, 0.0] — the 1→2 event at t = 1 is 2.0 old at t = 3
tied = EventSequence([Event(1, 2, 1.0), Event(2, 1, 1.0)]; actors=ActorSet(1:3))
compute_statistics(tied, [Reciprocity()]; ties=:breslow).reciprocity   # [0.0, 0.0]
source

Tie corrections and sampled controls

ties=:efron is offered with the full risk set only; with sampled controls the design is biased toward zero and is refused, pointing at :breslow. The guard is public (not exported) so that Revel.jl's design refuses the same combination with the same words.

REM.check_tie_sampling — Function
REM.check_tie_sampling(ties, block_size, n_controls, n_eligible; context="")

The guard that keeps the Efron tie correction away from sampled controls. It throws an ArgumentError when ties === :efron, the tie block holds block_size > 1 events and only n_controls < n_eligible of the n_eligible non-case dyads of its risk set would be kept; otherwise it returns nothing.

Why the combination is refused. Efron's denominator for the j-th of d tied events is the sum over the risk set with the d tied cases down-weighted by 1 − (j−1)/d. With sampled controls the other tied cases have to stay in every stratum of the block (with probability one), while the other dyads enter with probability m/(N−d): the tied cases — the dyads that just acted, with high linear predictors — then dominate the sampled denominator by a factor of about (N−d)/m, and the estimate is biased toward zero with confident standard errors (truth 1.0: 0.63 at 5 controls, 0.88 at 100, with 0 % coverage). Neither Horvitz–Thompson weights on the controls (they overcorrect: 1.47) nor nested case-control sampling with the Efron weight on any tied case that happens to be drawn (+12 % at 5 controls) removes the bias: Efron's factors are not the conditional probabilities that make the case-control argument work. Breslow's are — the Breslow correction is the likelihood of the tied events drawn independently from one frozen risk set, so each of its strata is an ordinary nested-case-control stratum, and ties=:breslow is unbiased with sampled controls (pinned by simulation in the test suite).

REM.check_tie_sampling is public: Revel.jl's event_design calls it, so the two packages refuse the same combination with the same words.

Example

using REM
REM.check_tie_sampling(:efron, 3, 1000, 600)      # nothing — the full risk set is kept
REM.check_tie_sampling(:breslow, 3, 5, 600)       # nothing — Breslow may be sampled
REM.check_tie_sampling(:efron, 1, 5, 600)         # nothing — an untied event
err = try REM.check_tie_sampling(:efron, 3, 5, 600) catch e e end
err isa ArgumentError                             # true
source

Model Fitting

fit_rem

REM.fit_rem — Function
fit_rem(seq::EventSequence, stats; kwargs...) -> REMResult

Fit a relational event model directly from an event sequence. This is the canonical entry point of the package (the fit_<model> name of the ecosystem vocabulary); there is deliberately no rem alias — see the package notes on why (rem is Base.rem, the remainder function).

Arguments

  • seq::EventSequence: The event sequence
  • stats: Statistics to include in the model (a StatisticSet, a vector of statistics, or a single statistic — fit_rem(seq, Repetition()) is a one-element model). The sequence comes first; fit_rem(stats, seq) is refused with the order spelled out

Keyword Arguments

  • n_controls::Int=100: Number of controls per case
  • decay::Float64=0.0: Exponential decay rate — eventnet's halflife memory model (halflife_to_decay(h)), the only one eventnet offers
  • window=nothing: Sliding window — events older than current_time − window stop counting in every count, degree and adjacency set. A Real in the clock's units (seconds for Date/DateTime clocks) or, on a calendar clock, a Dates.Period such as Day(2) (converted to seconds). A Period on a numeric clock is refused (ArgumentError): the clock counts in its own units, not seconds, so Day(2) has no meaning there. The fixed-memory alternative to decay, mutually exclusive with decay > 0 (ArgumentError); Inf is no window. See EventNetworkState
  • exclude_self_loops::Bool=true: Exclude self-loops from the risk set. A self-loop event in the sequence is then refused at fit time (it cannot be a member of its own risk set); drop such events or pass false
  • at_risk=nothing: The risk set (see generate_observations). One of nothing (the sequence's actor universe), an ActorSet/Set{Int}/Vector{Int} (static universe), a RiskSet, a list of (sender, receiver) dyads (a dyad-level risk set), a vector of per-event risk sets, or a callback (event_index, state) -> RiskSet. riskset is accepted as an alias.
  • ties::Symbol=:error: How to handle tied event times (below)
  • directed::Bool=true: false fits undirected events against the unordered pairs s < r of a symmetric actor set (see generate_observations); use undirected statistics with it
  • eventtypes::Symbol=:error: a sequence with more than one event type is refused until you choose: :pool makes every event a case (untyped statistics count all types together)
  • cases_of=nothing: an event type, or a collection of types, to model — only those events are cases while every event builds the history (a likelihood conditional on the event's type). Under either choice OfType gives a statistic the history of one type
  • maxiter::Int=100: Maximum Newton–Raphson iterations
  • tol::Float64=1e-8: Convergence tolerance
  • se::Symbol=:hessian: How to compute the standard errors (below)
  • rng::AbstractRNG=Random.default_rng(): Source of the control draw. A fixed rng (rng=Xoshiro(42)) reproduces the fit exactly.

The actor universe determines the estimand: the likelihood is conditional on the risk set, so nonparticipants that are eligible but never observed must be part of it. Declare it with EventSequence(events; actors=...) or pass at_risk. When neither is given, the universe falls back to the observed event endpoints (a "participants only" risk set) and a warning is issued.

Every case is validated against its own risk set before fitting, and each stratum must admit at least one control.

Standard errors

  • se=:hessian (default) — the inverse negative Hessian (observed information) of the partial likelihood on the risk set that was used. With the full risk set this is the classical Cox-model variance. With a sampled risk set it is the observed information of the sampled partial likelihood, which nested case-control theory shows to be a consistent estimator of the estimator's variance (Goldstein & Langholz 1992; Borgan, Goldstein & Langholz 1995): the information lost by sampling fewer controls is what makes it larger than the full-risk-set one, and nothing further needs adding. Under a correctly specified model its Wald intervals are calibrated (the "Sampled-risk-set standard errors are calibrated" testset pins 95 % coverage over replicate sequences).
  • se=:sandwich — the event-clustered Godambe sandwich H⁻¹ B H⁻¹, with the bread H the observed information and the meat B = Σ_e u_e u_eᵀ the outer product of the per-event score contributions (each event is one stratum, so the event is the clustering unit). This drops the information-equals- score-variance assumption — it is robust to misspecification of the within-stratum conditional model. Equals survival::coxph(..., robust=TRUE) with the stratum as the cluster (pinned by rem_clogit.toml).

There is deliberately no se=:bootstrap. Redrawing the controls and refitting does not expose a missing variance component — the sampled likelihood's own information already accounts for the sampling — what it exposes is how far the point estimate of a misspecified model depends on the particular draw (a pseudo-true value that moves with the draw, cured by a larger n_controls, not by a wider interval). That draw-to-draw spread is a sensitivity diagnostic and is offered as one: control_draw_cov.

Whichever was asked for, vcov(fit) is the full covariance matrix that the reported stderror(fit) are the square-rooted diagonal of.

The control inclusion probabilities are on the result: see sampling_probs and risk_set_sizes. With the full risk set (sampling_probs all 1.0) the partial likelihood is the exact ordinal one.

Collinearity and separation

Two things make a "converged" fit meaningless, and both are reported loudly (a warning naming the statistics, an entry in NetworkCore.approximations, NetworkCore.is_exact == false, a caveat under the table in show): a singular information matrix (fit.singular, standard errors NaN; fit.singular_suspects names the statistics that load on the null direction — collinear ones such as NodeSum(x) next to SenderAttribute(x) and ReceiverAttribute(x), or one constant within every stratum), and separation (fit.separated: coefficients whose maximum is at infinity, e.g. a covariate product that no event ever realises). Separation is a property of the design, decided by NetworkCore.jl's shared verdict (NetworkCore.clogit_separation: a linear programme over the case-minus- control rows, with the direction certified in exact arithmetic), so it does not depend on where Newton stopped or on the units of a covariate. A separated fit has converged == false and NaN z values, p-values and confidence intervals.

Tied event times

This is a Cox partial likelihood — one stratum per event, the case against the risk set — so a tied timestamp is the classical Cox tie problem and the classical vocabulary (NetworkCore.TIE_POLICIES) applies. Note what a tie does here: the statistics are read off the network state as it stands before the event, so ordering two simultaneous events lets the one placed first enter the statistics of the one placed second. That is not a tie-break, it is invented information.

  • ties=:error (default) — a tie is named and refused. The model claims a strict order; if the data does not have one, the user is told.
  • ties=:ordered — sequence order, no correction (what the package did before).
  • ties=:breslow — the Breslow correction: the network state is frozen across the tie block (the tied events cannot see each other), each is a stratum, and all share one denominator. Equals survival::coxph(..., ties="breslow"). The correction to use with sampled controls: each of its strata is an ordinary nested-case-control stratum, so it stays unbiased when the risk set is sampled (pinned by simulation).
  • ties=:efron — the Efron correction: as Breslow, plus the 1 − (j−1)/d denominator weights on the d tied cases. Equals survival::coxph(..., ties="efron"), R's own default, and the better approximation when ties are heavy — with the full risk set only. With sampled controls the other tied cases stay in every stratum with probability one while the controls are sampled, which biases the estimate toward zero, so a tie block whose risk set would be sampled is refused with an ArgumentError pointing at :breslow (see REM.check_tie_sampling).
  • ties=:batch — refused, with a pointer: with the risk set held fixed, a "simultaneous batch" in an ordinal likelihood IS the Breslow correction.

On tie-free data all four produce the identical design and the identical fit (pinned by the tests). tie_method(fit) reports what actually happened — :none when the data had no ties — and approximations(fit) carries the caveat when a correction was in fact applied.

Convergence

The optimizer is the shared NetworkCore.newton_fit (Newton–Raphson with step halving). A fit that exhausts maxiter warns, naming the gradient norm it stopped at, and comes back with converged == false, is_exact == false and an entry in NetworkCore.approximations(fit); fit.iterations is the count of Newton steps taken.

Returns

  • REMResult: Fitted model results (se_method(fit) reports which of the two standard-error estimators was used, tie_method(fit) what happened to ties)

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
stats = [Repetition(), Reciprocity()]

fit = fit_rem(seq, stats; n_controls=10, rng=Xoshiro(42))  # rng-driven, reproducible
coef(fit) == coef(fit_rem(seq, stats; n_controls=10, rng=Xoshiro(42)))   # true
coef(fit); stderror(fit); vcov(fit); aic(fit); confint(fit)
source

REMResult

REM.REMResult — Type
REMResult

Results from fitting a relational event model.

Fields

  • coefficients::Vector{Float64}: Estimated coefficients
  • std_errors::Vector{Float64}: Standard errors of coefficients
  • z_values::Vector{Float64}: Z-statistics
  • p_values::Vector{Float64}: P-values (two-sided)
  • stat_names::Vector{String}: Names of statistics
  • n_events::Int: Number of events in the model
  • n_observations::Int: Total number of observations
  • log_likelihood::Float64: Log-likelihood at convergence
  • converged::Bool: Whether the optimization converged to a finite maximum (see fit_rem: an unconverged fit warns, is never is_exact, and says so in NetworkCore.approximations). false on a separated design, whatever Newton's stopping rule said, because no finite maximum exists
  • strata::Vector{Int}: Stratum IDs, in the order of the risk-set bookkeeping below
  • risk_set_sizes::Vector{Int}: Size of each stratum's risk set (case included); empty when the observations carry no risk-set bookkeeping
  • sampling_probs::Vector{Float64}: Probability with which each non-case dyad of the stratum's risk set entered the sample as a control (1.0 = full risk set). These are the control inclusion probabilities; read them with sampling_probs and the risk-set sizes with risk_set_sizes.
  • se_type::Symbol: How std_errors were ACTUALLY computed — :hessian or :sandwich (see fit_rem). This is what NetworkCore.se_method(fit) reports.
  • tie_type::Symbol: What was ACTUALLY done with tied event times — :none (the data had no ties, so no policy could bite), or the policy that did: :ordered, :breslow or :efron (see ties= in fit_rem). :error can never appear: under it a tie throws instead of fitting. This is what NetworkCore.tie_method(fit) reports.
  • var_cov::Matrix{Float64}: The covariance matrix of the coefficients that matches se_type — the inverse observed information for :hessian, the Godambe sandwich H⁻¹BH⁻¹ for :sandwich — so that std_errors == sqrt.(diag(var_cov)) always. Read it with vcov(fit). NaN throughout when the Hessian at the solution is not negative definite (see NetworkCore.newton_fit and singular below).
  • iterations::Int: Newton–Raphson iterations taken by NetworkCore.newton_fit
  • stop::Symbol: why the iteration ended, as NetworkCore.newton_fit reports it — :converged, :maxiter, :singular_start (the information is singular at the starting value, so there is no Newton direction: collinear statistics; raising maxiter cannot help), :singular (the same at a later iterate), :no_ascent or :singular_information (settled, but the information at the solution is singular). The warning, show and NetworkCore.approximations name this reason.
  • singular::Bool: true when the observed information at the solution is singular (not positive definite), so the standard errors are undefined (NaN) — collinear statistics (NodeSum(x) next to SenderAttribute(x) and ReceiverAttribute(x)), a statistic constant within every stratum, or a separated one. The fit warns, converged and NetworkCore.is_exact are false, and NetworkCore.approximations and show name the suspects.
  • singular_suspects::Vector{String}: The statistics that load on the null direction of the information matrix (empty unless singular) — the ones to drop or combine.
  • separated::Vector{String}: The statistics whose coefficient is infinite at the maximum (separation: along some combination of them the case scores at least as high as every control in every stratum, so the partial likelihood keeps improving as the coefficients run away), decided on the design by NetworkCore.clogit_separation. The fit then follows the ecosystem's separation policy: it warns, converged is false, the z values, p-values and confidence intervals are NaN, NetworkCore.is_exact is false, and show prints the caveat under the table. Empty when nothing separated.

The StatsAPI verbs coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic and coeftable all have methods for REMResult (NetworkCore.check_statsapi(fit; strict=true) passes), and the result-metadata accessors NetworkCore.is_exact, se_method, tie_method, approximations and fit_metadata read off it what the fit actually did. show(fit) prints the R-style block every tutorial relies on: the header (events, observations, risk-set size and control sampling probability, log-likelihood, convergence with the iteration count, the standard-error estimator, the tie policy when one bit), the coefficient table, and the caveat that matches the estimator.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=19, rng=Xoshiro(1))   # full risk set
fit isa REMResult                       # true
fit.stat_names                          # ["repetition", "reciprocity"]
fit.converged, fit.n_events, fit.se_type, fit.tie_type   # (true, 8, :hessian, :none)
coef(fit) == fit.coefficients           # true
println(fit)                            # the R-style results block
source

Result Accessors (the StatsAPI surface)

REMResult answers all eleven verbs of the ecosystem's StatsAPI surface — each a method on the StatsAPI generic that StatsBase, GLM and NetworkCore share, so using REM, StatsBase dispatches one coef. NetworkCore.check_statsapi(fit; strict=true) passes. coeftable returns the shared, inspectable NetworkCore.CoefficientTable (not a DataFrame), and vcov is the covariance that matches se_method(fit): stderror(fit) == sqrt.(diag(vcov(fit))) under :hessian and :sandwich alike.

StatsAPI.coef — Function
coef(result::REMResult) -> Vector{Float64}

The estimated coefficients (log hazard ratios), one per statistic in result.stat_names. A method of StatsAPI.coef.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
coef(fit)                    # 2-element Vector{Float64}
source
StatsAPI.coefnames — Function
coefnames(result::REMResult) -> Vector{String}

The coefficient labels, in coef(result) order: the names of the statistics (R's names(coef(fit)), and coeftable(result).names). A method of StatsAPI.coefnames; the returned vector is a copy.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
coefnames(fit)               # ["repetition", "reciprocity"]
Dict(zip(coefnames(fit), coef(fit)))   # coefficient by name
source
StatsAPI.stderror — Function
stderror(result::REMResult) -> Vector{Float64}

The standard errors of the coefficients, computed the way se_method(result) says (:hessian or :sandwich); always sqrt.(diag(vcov(result))). A method of StatsAPI.stderror.

Example

using REM, LinearAlgebra, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
stderror(fit) ≈ sqrt.(diag(vcov(fit)))    # true
source
StatsAPI.vcov — Function
vcov(result::REMResult) -> Matrix{Float64}

The p × p covariance matrix of the coefficients that matches se_method(result): the inverse observed information for :hessian, the Godambe sandwich H⁻¹BH⁻¹ for :sandwich (see fit_rem). NaN throughout when the Hessian at the solution is not negative definite (result.singular). A method of StatsAPI.vcov.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
size(vcov(fit))              # (2, 2)
source
StatsAPI.confint — Function
confint(result::REMResult; level::Real=0.95) -> Matrix{Float64}

Wald confidence intervals coef ± z_{1−α/2} · stderror, one row per coefficient ([:, 1] lower, [:, 2] upper), on the normal reference distribution — the same standard errors se_method(result) names, so the interval is conditional on whatever they are conditional on. level must lie strictly in (0, 1). A method of StatsAPI.confint.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
ci = confint(fit)            # 2×2 Matrix: lower / upper at 95 %
all(ci[:, 1] .<= coef(fit) .<= ci[:, 2])    # true
confint(fit; level=0.9)      # narrower
source
StatsAPI.loglikelihood — Function
loglikelihood(result::REMResult) -> Float64

The log partial likelihood at the returned coefficients (the field result.log_likelihood): the stratified conditional-logit / Cox partial likelihood, evaluated on the sampled risk set. A method of StatsAPI.loglikelihood.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition()]; n_controls=10, rng=Xoshiro(1))
loglikelihood(fit) == fit.log_likelihood    # true
source
StatsAPI.nobs — Function
nobs(result::REMResult) -> Int

The number of events (result.n_events): one stratum per event, so this is what survival::clogit reports as nevent and what bic scales its penalty by — not the number of case-control rows (result.n_observations), which grows with n_controls and is a property of the sampling design rather than of the data. A method of StatsAPI.nobs.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition()]; n_controls=10, rng=Xoshiro(1))
nobs(fit)                    # 8 — the events, not the 88 case-control rows
source
StatsAPI.dof — Function
dof(result::REMResult) -> Int

The number of estimated coefficients (length(coef(result))); the model has no intercept and no nuisance parameters. A method of StatsAPI.dof.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
dof(fit)                     # 2
source
StatsAPI.aic — Function
aic(result::REMResult) -> Float64

Akaike's information criterion −2ℓ + 2k with ℓ = loglikelihood(result) the log partial likelihood and k = dof(result). A method of StatsAPI.aic.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
aic(fit) ≈ -2 * loglikelihood(fit) + 2 * dof(fit)    # true
source
StatsAPI.bic — Function
bic(result::REMResult) -> Float64

The Bayesian information criterion −2ℓ + k·log(n) with n = nobs(result) the number of events (one stratum each — the nevent of a Cox model, which is what survival uses in BIC(coxph) too). A method of StatsAPI.bic.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
bic(fit) ≈ -2 * loglikelihood(fit) + dof(fit) * log(nobs(fit))    # true
source
StatsAPI.coeftable — Function
coeftable(result::REMResult) -> NetworkCore.CoefficientTable

The coefficient table as the ecosystem's inspectable NetworkCore.CoefficientTable — names, estimates, standard errors, z-values and p-values exactly as show(result) prints them (the p-values are the fit's own, floored and NaN-aware). Index rows by position (tbl[1]) or by name (tbl["repetition"]), iterate them, or read the vectors off the fields. A method of StatsAPI.coeftable.

Until 0.2.0 this returned a DataFrame; the example shows how to get one back.

Example

using REM, DataFrames, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition(), Reciprocity()]; n_controls=10, rng=Xoshiro(1))
tbl = coeftable(fit)
tbl.names                    # ["repetition", "reciprocity"]
tbl["reciprocity"].estimate == coef(fit)[2]    # true
tbl                          # prints the R-style table
# The pre-0.2 DataFrame, if you need one
DataFrame(statistic=tbl.names, coefficient=tbl.estimates, std_error=tbl.std_errors,
          z_value=tbl.z_values, p_value=tbl.p_values)
source

Utility Functions

Time Decay

REM.halflife_to_decay — Function
halflife_to_decay(halflife::Real) -> Float64
halflife_to_decay(halflife::Dates.Period) -> Float64

Convert a halflife to an exponential decay rate: λ = log(2) / halflife, so that an event's weight exp(−λ·Δ) is 0.5 when it is halflife old. This is eventnet's halflife parameterisation; pass the result as decay= to fit_rem, generate_observations or EventNetworkState. The halflife is in clock units — seconds for Date/DateTime clocks, so on a calendar clock pass a Dates.Period (halflife_to_decay(Day(7)), which is halflife_to_decay(7 * 86400)) rather than counting seconds by hand.

Example

using REM, Dates
λ = halflife_to_decay(10.0)          # 0.0693…
compute_decay_weight(10.0, λ)        # 0.5
decay_to_halflife(λ)                 # 10.0
halflife_to_decay(Day(7)) == halflife_to_decay(7 * 86400)   # true — seconds
source
REM.decay_to_halflife — Function
decay_to_halflife(decay::Real) -> Float64

Convert an exponential decay rate back to a halflife: log(2) / decay, the inverse of halflife_to_decay.

Example

using REM
decay_to_halflife(log(2) / 24)      # 24.0
decay_to_halflife(halflife_to_decay(7.0))   # 7.0
source
REM.compute_decay_weight — Function
compute_decay_weight(elapsed_time::Real, decay::Real) -> Float64

The weight exp(−decay · elapsed_time) an event carries elapsed_time after it happened — what every decayed count in an EventNetworkState applies (lazily, on read). Note the argument order: elapsed time first, decay rate second. elapsed_time must be non-negative.

Example

using REM
λ = halflife_to_decay(10.0)
compute_decay_weight(0.0, λ)         # 1.0 — a fresh event
compute_decay_weight(10.0, λ)        # 0.5 — one halflife old
compute_decay_weight(20.0, λ)        # 0.25
source

Risk Set Utilities

REM.n_dyads — Function
n_dyads(rs::RiskSet) -> Int

Return the number of dyads in the risk set: |senders| × |receivers|, minus the actors that appear on both sides when exclude_self_loops is set.

Allocation-free: when both actor vectors are sorted (which every RiskSet built by generate_observations is) the common actors are counted by a single sorted merge; unsorted or duplicated vectors are counted through sets instead, so a hand-built RiskSet still gets the right answer.

Example

using REM
n_dyads(RiskSet(1, [1, 2, 3], [1, 2, 3]))                            # 6
n_dyads(RiskSet(1, [1, 2, 3], [1, 2, 3]; exclude_self_loops=false))  # 9
n_dyads(RiskSet(1, [1, 2], [3, 4, 5]))                               # 6 (disjoint)
source

Sampling Design

The case-control sampling design that a fit actually ran on — part of the estimand, since the partial likelihood is conditional on the risk set.

REM.risk_set_sizes — Function
risk_set_sizes(result::REMResult) -> Vector{Int}

The size of each stratum's risk set (the case included), one entry per stratum in result.strata order. Empty when the fit carries no risk-set bookkeeping.

See also sampling_probs for the control inclusion probabilities.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition()]; n_controls=10, rng=Xoshiro(1))
risk_set_sizes(fit)          # all 20 — 5·4 ordered dyads per event, case included
source
REM.sampling_probs — Function
sampling_probs(result::REMResult) -> Vector{Float64}

The control inclusion probabilities: the probability with which each non-case dyad of a stratum's risk set entered the sample as a control, one entry per stratum (in result.strata order). 1.0 means the full risk set was used (no sampling). Empty when the fit carries no risk-set bookkeeping.

The likelihood is conditional on the sampled risk set, so these probabilities are part of the estimand and not an implementation detail — they are what determines whether NetworkCore.is_exact holds, and how far a misspecified model's estimate can depend on the particular control draw (see control_draw_cov).

See also risk_set_sizes.

Example

using REM, Random
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0), Event(2, 3, 4.0),
          Event(3, 1, 5.0), Event(1, 3, 6.0), Event(2, 1, 7.0), Event(3, 2, 8.0)]
seq = EventSequence(events; actors=ActorSet(1:5))
fit = fit_rem(seq, [Repetition()]; n_controls=19, rng=Xoshiro(1))   # 20 dyads: full risk set
sampling_probs(fit)          # all 1.0 — nothing was sampled away
sampling_probs(fit_rem(seq, [Repetition()]; n_controls=10, rng=Xoshiro(1)))   # all 10/19
source

Control-draw sensitivity

How far the point estimate of a sampled fit depends on which controls were drawn. A diagnostic, not a standard error (the docstring says why there is no se=:bootstrap).

REM.control_draw_cov — Function
control_draw_cov(seq::EventSequence, stats; n_controls=100, n_draws=20, kwargs...)
    -> (cov, sd, replicates, mean, n_unconverged)

Control-draw sensitivity diagnostic for a case-control fit: redraw the sampled risk set n_draws times (independent seeds from rng), refit fit_rem on each draw, and return the covariance of the refitted coefficients across draws. It answers one question — how much does my point estimate depend on which controls happened to be drawn? — and it is not a standard error: it is neither reported by stderror nor combined with the inverse-Hessian covariance, because under nested case-control sampling the sampled likelihood's own observed information is already a consistent variance estimator (Goldstein & Langholz 1992; Borgan, Goldstein & Langholz 1995), and adding a between-draw term to it would double-count.

What the spread does measure. Under a correctly specified model the draws scatter around one value: their spread is the information the sampling threw away, which the standard error already accounts for, and their mean stays put as n_controls changes. Under a misspecified model (every real model) the sampled fit converges to a pseudo-true value that itself depends on the draw and moves with n_controls: the mean drifts toward the full-risk-set estimate as the controls grow, and the draw-to-draw sd is of the order of the standard error with few controls (on the WTC calls' 7-statistic model — the estimation guide's table — 20 of 1331 controls gives repetition a mean of −0.50 with a draw-to-draw sd of 0.07–0.08 over ten draws (Xoshiro(1)/Xoshiro(7)) against a per-draw standard error of 0.08–0.10 (rng=Xoshiro(1)/Xoshiro(42)), and a single draw — Xoshiro(42) — sits at −0.72; 400 controls gives −0.33 ± 0.02 against 0.04; the full risk set −0.34). Either symptom says the same thing — raise n_controls, or enumerate the full risk set — and neither is cured by a wider interval.

Arguments

Keyword Arguments

  • n_controls::Int=100: controls per event in each draw
  • n_draws::Int=20: number of independent control draws (at least 2)
  • decay, window, exclude_self_loops, at_risk/riskset, ties, maxiter, tol: as for fit_rem; the design of every draw is built with them
  • rng::AbstractRNG=Random.default_rng(): the source of the per-draw seeds (drawn up front, so the result is reproducible for a fixed rng and independent of the thread count)
  • threaded::Bool=true: refit the draws on all available threads

Returns

A NamedTuple:

  • cov::Matrix{Float64}: the p × p covariance of the refitted coefficients across draws (centred on their mean — the spread, not the bias)
  • sd::Vector{Float64}: its square-rooted diagonal, the draw-to-draw standard deviation of each coefficient
  • replicates::Matrix{Float64}: the n_draws × p refitted coefficients, in name.(stats) order
  • mean::Vector{Float64}: their mean — compare it with the estimate at a larger n_controls or with the full-risk-set fit
  • n_unconverged::Int: how many refits did not converge (warned about once)

Runs on the shared NetworkCore.bootstrap_cov resampling loop; what is resampled is the sampling design, not the model.

Example

using REM, Random
rng0 = MersenneTwister(4)
events = [Event(rand(rng0, 1:12), rand(rng0, 1:12), Float64(k)) for k in 1:80]
events = [e for e in events if e.sender != e.receiver]
seq = EventSequence(events; actors=ActorSet(1:12))
stats = [Repetition(), Reciprocity()]
fit = fit_rem(seq, stats; n_controls=5, rng=Xoshiro(42))
draws = control_draw_cov(seq, stats; n_controls=5, n_draws=10, rng=Xoshiro(7))
size(draws.replicates)                  # (10, 2)
draws.sd                                # draw-to-draw sd; compare with stderror(fit)
draws.cov == control_draw_cov(seq, stats; n_controls=5, n_draws=10, rng=Xoshiro(7)).cov  # true
source

Result Metadata

REM.jl implements the ecosystem's result-metadata protocol, so what a fit actually did is programmatically inspectable via NetworkCore.fit_metadata(result) rather than buried in a show method.

NetworkCore.is_exact is the one to read first: the case-control partial likelihood is exact only when the sampled risk set is the full risk set. tie_method reports the tie policy that actually ran — never :error, because a fit that would have had to break a tie under ties=:error threw instead of returning.

The remaining accessors (estimand, missing_method, approximations) take their documentation from the generics in the NetworkCore.jl manual.

NetworkCore.objective — Method
objective(::REMResult) -> Symbol

:partial_likelihood — the stratified conditional-logit partial likelihood (one stratum per event: the case dyad against its sampled controls), equivalent to the Cox partial likelihood for case-control data.

source
NetworkCore.is_exact — Method
is_exact(result::REMResult) -> Bool

true only when the risk set was NOT sampled, no tie correction was needed, the optimizer converged, the information matrix is not singular and no coefficient separated. With the full risk set (sampling_prob == 1) on strictly ordered data, the conditional-logit partial likelihood is the exact ordinal relational-event likelihood. Five things make the result an approximation instead:

  • case-control sampling (the default, n_controls = 100);
  • tied event times — Breslow, Efron and arbitrary ordering are all approximations to a likelihood over an order the data does not determine (a fit on tie-free data has tie_type == :none and is unaffected); and
  • non-convergence — an unconverged Newton–Raphson leaves estimates that are not the maximum of anything (converged == false; the fit warned, and approximations says so);
  • a singular information matrix (singular == true) — the standard errors are undefined, and the coefficients of the collinear statistics are not identified; and
  • separation (separated non-empty) — a coefficient whose maximum is at infinity; the returned value is where the optimizer stopped.

It also reports false for a REMResult built without risk-set bookkeeping, where the sampling is unknown — the conservative answer.

source
NetworkCore.se_method — Method
se_method(result::REMResult) -> Symbol

What the reported standard errors ACTUALLY are:

  • :hessian — the inverse negative Hessian (observed information) of the conditional-logit partial likelihood on the risk set that was used (the default)
  • :sandwich — the event-clustered Godambe sandwich H⁻¹ B H⁻¹, with the meat B the outer product of the per-event score contributions

Read straight off the fit, so it can never claim an estimator that was not used. See fit_rem for what each one does and does not account for.

source
NetworkCore.tie_method — Method
tie_method(result::REMResult) -> Symbol

What was ACTUALLY done with tied event times, not what the estimator is willing to do:

  • :none — the data had no tied timestamps, so no policy bit. (The default policy ties=:error guarantees that any fit with ties in it was asked for.)
  • :ordered — ties were broken in sequence order and no correction applied
  • :breslow — the Breslow correction: one risk set per tie block
  • :efron — the Efron correction: Breslow plus the 1 − (j−1)/d denominator weights on the tied cases

:error never appears: under it a tie throws rather than fitting. See ties= in fit_rem.

source