Fitting API Reference
Risk sets and designs
Revel.RiskSetView — Type
RiskSetViewWhat each_risk_set hands its callback for one event:
index— the event's position in the time-sorted sequence;event— the event itself;dyads— the risk set, a vector of(sender, receiver);X— thelength(dyads) × pmatrix of statistics on it;case— the row of the observed dyad;tied— underties=:efron, the rows of every case tied with this one (empty otherwise);tie_weight— the Efron denominator weight1 − (j−1)/dthose rows take (1.0otherwise);risk_set_size— the number of dyads in the risk set (length(dyads), unlessevent_designsampled controls from it).
dyads, X and tied are buffers reused from one event to the next: copy them to keep them beyond the callback, and do not modify them.
Example
using Revel
events = [Event(1, 2, 1.0), Event(2, 1, 2.0)]
sizes = Int[]
each_risk_set(events, [Inertia()], 3) do view
push!(sizes, length(view.dyads))
end
sizes # [6, 6] — three actors, six ordered dyadsRevel.each_risk_set — Function
each_risk_set(f, events, statistics, n_actors; directed=true, riskset=:full,
ties=:error, cases=nothing) -> SymbolStream the risk sets of an event sequence: for each event (in time order) call f(view::RiskSetView) with the risk set and the statistics of every dyad in it, read off the history before the event. Returns the tie policy that actually applied (:none when the data had no ties).
directed—falsetreats events as undirected: every event is rewritten as the pair(min, max)before the history is built, so nothing depends on how a pair happened to be stored, and the risk set holds unordered pairs(i, j)withi < j. Build the statistics on symmetric layers: a directed statistic would then read the pair in ID order, which carries no meaning.riskset—:full(every dyad among1:n_actors);:active(only dyads that occur somewhere in the sequence — remify's "active" risk set);:sender(the observed sender'sn−1possible receivers: the receiver-choice step of an actor-oriented model, DyNAM-choice);:receiver(the observed receiver's possible senders); a vector of dyads (e.g.two_mode_dyads); or a function(index, event) -> dyadsfor a risk set that changes over time.ties—:error(default),:ordered,:breslowor:efron, the sharedNetworkCore.TIE_POLICIESvocabulary. Under the two corrections the history is frozen across a block of tied events.cases— which events are visited:nothing(all), indices into the time-sorted sequence, aBoolmask, or a predicateevent -> Bool. Events that are not cases still enter the history, which is what stratified and moving-window fits need. A predicate that depends on who acts (e -> group[e.sender] == 2) also restricts each case's risk set to the dyads whose candidate eventEvent(s, r, time; eventtype, weight)it accepts: the likelihood is then conditional on the event being a case, as it must be — against the full risk set the statistics would "explain" the selection itself. A predicate on the time or the type keeps the risk set. Indices and masks cannot be inspected and are taken to be chosen without regard to which dyad acted; pass a predicate when they are not.
The pass costs O(events × risk set × statistics) and holds one design matrix at a time. It evaluates private copies of statistics (see EventLayer), so one specification can be streamed from several tasks at once.
Example
using Revel
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 2, 3.0)]
cases = Vector{Float64}[]
each_risk_set(events, [Inertia(), Reciprocation()], 3) do view
push!(cases, view.X[view.case, :]) # copy the row: `X` is reused
end
cases # [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] — inertia and reciprocity of each eventRevel.event_design — Function
event_design(events, statistics, n_actors; directed=true, riskset=:full,
ties=:error, cases=nothing, n_controls=nothing,
rng=Random.default_rng()) -> DataFrameThe stratified design of a relational event model as a DataFrame: one row per dyad in each event's risk set, with the statistics as columns (named by name(stat)) and the bookkeeping columns REM.fit_rem(::DataFrame, names) reads — event_index, sender, receiver, time, is_event, stratum, risk_set_size, sampling_prob, tie_weight. The tie policy that applied rides along as the "tie_method" metadata.
This is the frame to take to a different estimator (a GAM, a mixed model, a penalised regression), to inspect for collinearity, or to fit with fit_rem(design, names). directed, riskset, ties and cases are as in each_risk_set.
n_controls keeps the case plus that many dyads drawn without replacement from the rest of each risk set (nested case-control sampling; Vu, Pattison & Robins 2015; Lerner & Lomi 2020), with all randomness from rng. The statistics are evaluated on the drawn dyads only, so the cost is events × (n_controls + 1) evaluations however large the risk set. nothing keeps the full risk set, which costs events × risk set rows.
Example
using Revel
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 3, 3.0)]
design = event_design(events, [Inertia(), Reciprocation()], 3)
size(design, 1) # 18 — three events × six dyads
design[design.is_event, :reciprocity] # [0.0, 1.0, 0.0]Revel.two_mode_dyads — Function
two_mode_dyads(senders, receivers) -> Vector{Tuple{Int,Int}}The risk set of a two-mode event network: every (sender, receiver) pair with the sender in one node set and the receiver in the other (users and articles, actors and claims, authors and papers). Pass it as riskset= to fit_revel, event_design or each_risk_set. The two node sets must use disjoint actor IDs.
Example
using Revel
dyads = two_mode_dyads(1:2, 11:13)
length(dyads) # 6
first(dyads) # (1, 11)Fitting
Revel.fit_revel — Function
fit_revel(events, statistics, n_actors; model=:ordinal, directed=true,
riskset=:full, cases=nothing, ties=:error, n_controls=nothing,
rng=Random.default_rng(), se=:hessian, engine=:auto,
maxiter=100, tol=1e-8, kwargs...) -> RevelFitFit a relational event model with Revel's statistics (or any statistic with the history interface compute(stat, ::InteractionHistory, sender, receiver, time); a REM.jl statistic, which has only REM's interface, is refused with an ArgumentError — fit it with REM.fit_rem). revel is an alias.
model=:ordinal (default) models which dyad acts next given the history — the ordinal likelihood of relevent::rem.dyad, a conditional logit with one stratum per event. model=:timing adds the waiting times under an exponential baseline (Revel.fit_timing; pass t0/t_end through kwargs); it needs the full directed risk set and statistics that are constant between events: FullMemory layers and any layer with clock=:order, static covariates, recency ranks and participation shifts qualify; a decaying memory on the time clock, TimeSince, GlobalEffect and time-varying covariates are refused.
For the ordinal model:
directed,riskset,casesandtiesare as ineach_risk_set.riskset=:senderfits the receiver-choice step of an actor-oriented model (seefit_receiver_choice); a vector fromtwo_mode_dyadsfits a two-mode model;casesrestricts the likelihood to some events while the rest still build the history. Acasespredicate that depends on who acts (e -> group[e.sender] == 2) also restricts each case's risk set to the dyads that would have produced a case — the conditional likelihood of "which dyad, given that the event is a case" — and that restricted risk set is what the fit stores and shows.n_controlssamples that many controls per event (nested case-control sampling) instead of enumerating the risk set, with all randomness fromrng.se—:hessianor:sandwich(REM.fit_rem's event-clustered sandwich. Each event is its own cluster, so it guards against a misspecified functional form but not against dependence between the score contributions of successive events).engine—:streamusesRevel.fit_obpm, which evaluates the full risk set interval by interval and can stream it instead of holding the design in memory;:designbuilds theevent_designframe and fits it withREM.fit_rem.:autopicks:streamwhenever the model is one it can fit (full directed risk set, every event a case, no sampling,se=:hessian) and:designotherwise. Both maximise the same likelihood exactly; on a common model they agree to optimizer tolerance.
Remaining keywords are forwarded to the underlying fitter (cache, chunk, cache_bytes for Revel.fit_obpm/Revel.fit_timing; t0, t_end for the timing model). The streamed engine keeps the design matrices in memory up to cache_bytes and otherwise recomputes the statistics on every pass of the optimizer; fit_revel's default cache_bytes is a quarter of the free memory (between 256 MiB and 8 GiB), because the statistics are costly to recompute.
Separation. When no finite maximum exists (a statistic that every case maximises within its risk set, say), every route follows the ecosystem's separation policy, decided by the shared verdict of NetworkCore.jl on the risk sets actually fitted: a warning, converged == false, the separated coefficients named in fit.fit.separated, and z values, p-values and confint withheld (NaN). The diagnostics refuse such a fit.
Statistic names must be unique; pass name= to tell apart two effects that differ only in a filter. A GlobalEffect outside an Interaction is refused under the ordinal model, which cannot identify it. The statistics are evaluated on private copies (see EventLayer), so one specification can be fitted from several tasks at once.
Example
using Revel, Random
truth = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(truth, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, truth, 6)
round.(coef(fit); digits=1) # [0.6, 0.5] — the truth is [0.8, 0.6]
round.(stderror(fit); digits=2) # [0.13, 0.13]
choice = fit_revel(events, truth, 6; riskset=:sender) # receiver choice
nobs(choice) # 200Revel.revel — Function
revel(events, statistics, n_actors; kwargs...) -> RevelFitAlias for fit_revel (the ecosystem's convention: every model answers to a fit_<model> name and a short one).
Example
using Revel, Random
events = simulate_events([Inertia(transform=:log1p)], [1.0], 5, 80; rng=Xoshiro(2))
revel === fit_revel # true
fit = revel(events, [Inertia(transform=:log1p)], 5)
coef(fit)[1] > 0 # trueRevel.fit_receiver_choice — Function
fit_receiver_choice(events, statistics, n_actors; kwargs...) -> RevelFitThe receiver-choice step of an actor-oriented event model: given the sender of each event, which receiver did it choose among the other n−1 actors? This is the multinomial choice model of DyNAM (Stadtfeld & Block 2017; goldfish subModel = "choice") and of remstats' actor-oriented model. It is fit_revel(…; riskset=:sender).
A statistic that depends on the sender alone — SendEffect, OutdegreeSender — is constant within every choice set and cannot be estimated here (the fit does not converge, and statistic_collinearity reports it with an infinite VIF); it can enter only as a moderator, through an Interaction.
Stadtfeld & Block (2017, p. 340) report estimates of opposite sign for the same effect ("outdegree × friendship") in a tie-oriented and an actor-oriented model of the same data, and explain the difference by what the other effects of each model (transitivity of friendship) absorb. Fitting both is therefore a specification check. A reason of the same kind, which is ours rather than theirs: a tie-oriented model carries the sender's activity in its intercept of dyads, so a sender-level term there mixes "active senders" with "senders who repeat".
The sender-rate step (who acts next, and when) is not implemented.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(3))
choice = fit_receiver_choice(events, stats, 6)
choice.riskset # :sender
length(coef(choice)) # 2Revel.RevelFit — Type
RevelFitA fitted relational event model: the underlying estimator's result (fit.fit — a Revel.OrdinalBPMResult, a Revel.TimingModelResult or a REM.REMResult) together with the time-sorted events, the statistics and the risk-set specification that produced it.
It answers the StatsAPI verbs (coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic, coeftable, coefnames) and the ecosystem's result-metadata protocol (NetworkCore.fit_metadata), and it is what event_diagnostics, prediction_summary, score_process_test, score_test and gof take.
Example
using Revel, Random
events = simulate_events([Inertia(transform=:log1p)], [1.0], 5, 60; rng=Xoshiro(1))
fit = fit_revel(events, [Inertia(transform=:log1p), Reciprocation(transform=:log1p)], 5)
fit isa RevelFit # true
coefnames(fit) # ["log1p(inertia)", "log1p(reciprocity)"]
length(coef(fit)), nobs(fit) # (2, 60)The full-risk-set engine
The two exact likelihoods behind fit_revel on the full directed risk set — the ordinal and the interval-timing likelihood of relevent::rem.dyad — and their results. They are public but not exported (Revel.fit_obpm, …): fit_revel is the entry point, and it wraps the result for the diagnostics.
Revel.fit_obpm — Function
Revel.fit_obpm(events, statistics, n_actors; ties=:error, cache=:auto,
chunk=nothing, cache_bytes=2^28, maxiter=100, tol=1e-8)
-> Revel.OrdinalBPMResultFit the ordinal relational event model (Butts 2008) by exact maximum likelihood over the full risk set of all n(n−1) ordered dyads: each event contributes the multinomial-logit term exp(θ'x_case) / Σ_{(i,j)} exp(θ'x_ij), with the statistics read off the history before the event. This is the likelihood of relevent::rem.dyad(…, ordinal = TRUE), and the estimator behind fit_revel for the ordinal model on the full directed risk set (which also sorts the events, checks the statistics and wraps the result for the diagnostics: prefer it). The likelihood is maximised by the ecosystem's shared Newton optimizer, NetworkCore.newton_fit.
statistics may be any statistic with the history interface compute(stat, ::InteractionHistory, sender, receiver, time). The likelihood models event choice conditional on the history, without a waiting-time likelihood; finite-half-life statistics still use the observed time differences.
Separation
Whether a finite maximum exists is decided on the risk sets, before the optimizer runs, by the ecosystem's shared verdict: a direction along which every case scores at least as high as every alternative of its risk set, strictly somewhere, is searched for by a linear programme and certified in exact arithmetic (NetworkCore.separation_from_margins; the risk set is a stratum of a conditional logit). Complete and quasi-complete separation are both found, and tiny genuine overlap is never rounded into one. A separated fit warns, returns converged == false, names the separated coefficients in fit.separated (the verdict is fit.separation), and withholds inference: z values, p-values and confint are NaN. The coefficients and standard errors are kept for diagnosis; they are where the optimizer stopped, not estimates.
Risk-set caching
The full risk set means an n(n−1) × p design matrix per event. Materializing them all costs O(E · n² · p) doubles — 906 MiB at (n, E, p) = (100, 2000, 6) — so cache= decides how many are alive at once:
:auto(default) —:allwhile the projected footprint fits incache_bytes(256 MiB here;fit_revelpasses a quarter of the free memory),:chunkedabove it.:all— every design matrix materialized once. Fastest;O(E · n² · p).:chunked— a bounded cache ofchunkmatrices (default: as many as fit incache_bytes), refilled by replaying the event history on each pass.:none—:chunkedwithchunk = 1: one matrix alive at a time, least memory, most recomputation.
Every policy visits the intervals in the same order and reads the same statistics off the same histories, so the fits are bit-identical; only memory and time differ.
Tied event times
A tied timestamp means the event order is unobserved, and sorting the tie invents it (worse: the statistics are read off the pre-event history, so the event sorted first enters the statistics of the one sorted second). ties= (the shared NetworkCore.TIE_POLICIES vocabulary) says what to do:
:error(default) — name the tie and refuse.:ordered— sequence order, no correction.:breslow— the Breslow correction: the tied events share one risk set (the history is frozen across the tie block, so they cannot enter each other's statistics) and each contributes the same denominator.:efron— the Efron correction: as:breslow, plus the1 − (j−1)/ddenominator weights on the tied cases; the better approximation, and whatsurvival::coxphdefaults to. Requires the tied events to be distinct dyads.:batch— refused: with the history frozen, a simultaneous batch in an ordinal likelihood IS the Breslow correction. (It isRevel.fit_timing's policy, where there is an exposure interval for a batch to consume.)
On tie-free data all four give the identical fit. tie_method(fit) reports what actually happened and approximations(fit) carries the caveat.
Example
using Revel, Random
truth = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(truth, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
direct = Revel.fit_obpm(events, truth, 6)
direct.converged # true
coef(direct) == coef(fit_revel(events, truth, 6)) # true — the same estimator
small = Revel.fit_obpm(events, truth, 6; cache=:none)
coef(small) == coef(direct) # true — one design matrix in memoryRevel.fit_timing — Function
Revel.fit_timing(events, statistics, n_actors; t0=zero(T), t_end=nothing,
ties=:error, cache=:auto, chunk=nothing, cache_bytes=2^28,
maxiter=100, tol=1e-8) -> Revel.TimingModelResultFit the interval-timing relational event model with an exponential baseline by exact maximum likelihood over the full risk set: with waiting time Δt_m before event m and per-dyad hazards λ₀·exp(θ'x_ij) (statistics constant between events),
ℓ(λ₀, θ) = Σ_m [ log λ₀ + θ'x_case − λ₀ Δt_m Σ_{ij} exp(θ'x_ij) ].(log λ₀, θ) are estimated jointly by NetworkCore.newton_fit; standard errors come from the observed information. This is the estimator behind fit_revel(…; model=:timing), which wraps the result for the diagnostics: prefer it. Only the exponential baseline is implemented (baseline=:exponential, the default; any other value is refused).
Every statistic must satisfy Revel.is_interval_constant; a statistic that is not (a decaying memory on the time clock, an uncertified custom statistic) is refused with an ArgumentError, because multiplying the hazard evaluated at an event endpoint by the preceding interval is not its integral. Fit such statistics with the ordinal likelihood, or define an interval-constant model deliberately (a FullMemory layer, or clock=:order) — changing the memory changes the model.
Observation window
t0 is the observation onset: the first event's waiting time is Δt_1 = t_1 − t0. The default t0 = zero(T) matches relevent, where "event times should be relative to onset of observation". For a process already running when recording started, pass the window start as t0; it must not exceed the first event time.
t_end is the time recording stopped. It adds the right-censored final interval [t_M, t_end] — exposure with no event — to the likelihood, ℓ += −λ₀ (t_end − t_M) Σ_{ij} exp(θ'x_ij). relevent::rem.dyad always has this term (its last edgelist row is the termination time, and any event on it is ignored), so t_end is required to reproduce it: without it the sequence is treated as ending at its last event, and λ₀ is biased upward. (rem.dyad's temporal likelihood also has no intercept: give it a constant CovSnd column, whose coefficient is then log λ₀.)
Separation
Decided before the optimizer runs, by the shared verdict, and handled as in Revel.fit_obpm: a warning, converged == false, fit.separated naming the coefficients ("log_baseline" among them when the baseline runs away), and NaN z values, p-values and confidence intervals. The likelihood is a Poisson log-linear likelihood with offset log Δt over the dyads of every interval of positive length, so a direction separates when no dyad's log-rate rises in an interval with exposure, no event's log-rate falls, and some exposure strictly falls. The censored tail counts as exposure. An event in a zero-length interval (a tie under ties=:ordered or :batch) is required to rise on its own; this can miss a direction along which such events trade off against each other, but never reports a separation that does not exist.
Risk-set caching
cache=:auto|:all|:chunked|:none (with chunk and cache_bytes) bounds the memory the risk-set design matrices take, exactly as in Revel.fit_obpm; the fit is bit-identical under every policy.
Tied event times
This is an exact-time likelihood. Under the continuous-time process it fits, two events at one instant have probability zero: a tie is the model's own assumption failing — a coarse clock or a genuinely batched observation — and the policies (NetworkCore.TIE_POLICIES) say which:
ties=:error(default) — name the tie and refuse.ties=:ordered— each tied event after the first enters with a zero-length waiting interval (an event term with no exposure) while still updating the statistics of the next: the fit then claims one event caused another in no time at all.ties=:batch— one simultaneous batch: the statistics are frozen across the block and the block consumes one exposure interval. The coarsened-observation reading, and the one to prefer when the clock is coarse.ties=:breslow/ties=:efron— refused: Breslow and Efron correct a partial likelihood, in which the baseline hazard is profiled out and only the order of events survives. Fit the ordinal model withties=:efronif the order is what matters.
On tie-free data every policy gives the identical fit, and is_exact(fit) turns false as soon as a tie was in the data.
Example
using Revel, Random
truth = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(truth, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = Revel.fit_timing(events, truth, 6; t_end=events[end].time + 1.0)
coefnames(fit) # ["log_baseline", "log1p(inertia)", "log1p(reciprocity)"]
fit.converged # true
decaying = try Revel.fit_timing(events, [Inertia(memory=HalfLife(5.0))], 6) catch e; e end
decaying isa ArgumentError # true — a decaying memory is not interval-constantRevel.OrdinalBPMResult — Type
Revel.OrdinalBPMResultThe result of Revel.fit_obpm, the ordinal relational event model (Butts 2008) fitted by exact maximum likelihood over the full risk set, with observed-information standard errors. A RevelFit of the ordinal model on the full directed risk set holds one in fit.fit.
It answers the StatsAPI verbs — coef, coefnames, stderror, vcov, confint, loglikelihood, nobs (events), dof, aic, aicc, bic and coeftable (a NetworkCore.CoefficientTable) — and the ecosystem's result-metadata protocol (NetworkCore.fit_metadata): the objective is the ordinal likelihood itself (nothing is sampled), is_exact is true on data without tied event times, and tie_method reports what was done with ties (:none, :ordered, :breslow or :efron; :error never appears, since under it a tie throws). Fields include coefficients, std_errors, loglik, converged, iterations, tie_type, separation (the shared NetworkCore.SeparationVerdict on the risk sets) and separated (the names of the coefficients it flags, empty when a finite maximum exists).
Example
using Revel
events = [Event(1, 2, 1.0), Event(2, 1, 2.0), Event(1, 3, 3.0), Event(3, 1, 4.0),
Event(2, 3, 5.0), Event(1, 2, 6.0), Event(3, 2, 7.0), Event(2, 1, 8.0)]
fit = Revel.fit_obpm(events, [PShift(:AB_BA)], 3)
fit isa Revel.OrdinalBPMResult # true
coefnames(fit) # ["PSAB-BA"]
nobs(fit), dof(fit) # (8, 1)
Revel.NetworkCore.tie_method(fit) # :noneRevel.TimingModelResult — Type
Revel.TimingModelResultThe result of Revel.fit_timing, the interval-timing relational event model with an exponential baseline, fitted by exact maximum likelihood over the full risk set. A RevelFit with model=:timing holds one in fit.fit.
The coefficient vector is [log(λ₀); θ]: coef, coefnames (which starts with "log_baseline"), stderror, vcov, confint and coeftable all use that order, and dof counts the baseline. The effect-only vectors remain in the fields coefficients and std_errors, and baseline_params[1] is the fitted baseline rate λ₀. nobs counts events (a right-censored tail is exposure, not an event). The metadata protocol (NetworkCore.fit_metadata) reports the exact likelihood, is_exact == false as soon as the data carried tied event times (under a continuous-time model a tie has probability zero, so no policy can make the likelihood exact for such data), and tie_method (:none, :ordered or :batch). separation and separated are as in Revel.OrdinalBPMResult, with "log_baseline" among the names that can be flagged.
Example
using Revel
events = [Event(1, 2, 1.0), Event(2, 3, 2.0), Event(3, 1, 3.0),
Event(1, 3, 4.0), Event(2, 1, 5.0), Event(3, 2, 6.0)]
fit = Revel.fit_timing(events, [SendEffect([0.0, 1.0, 2.0])], 3; t_end=7.0)
fit isa Revel.TimingModelResult # true
coefnames(fit) # ["log_baseline", "send.x"]
abs(coef(fit)[2]) < 1e-8 # true — every sender acts twice
exp(coef(fit)[1]) == fit.baseline_params[1] # trueRevel.is_interval_constant — Function
Revel.is_interval_constant(stat) -> BoolWhether compute(stat, history, sender, receiver, t) is constant as t advances between events with the history and candidate dyad fixed. The interval-timing likelihood (Revel.fit_timing, fit_revel(…; model=:timing)) requires it, because its exposure is the waiting time times the hazard. The default is false: a custom statistic must explicitly extend this function (Revel.is_interval_constant(::MyStat) = true) to declare that the identity holds for every admissible history. The trait is public, not exported.
Revel's statistics answer it themselves: true for layers on FullMemory (or HalfLife(Inf)) and for any layer on the event clock (clock=:order), for static covariates, recency ranks and participation shifts (PShift, PShiftABAB, UndirectedPShift), and for TimeSince(…; clock=:order); false for a decaying memory on the time clock, TimeSince on the time clock, GlobalEffect and time-varying covariates. A wrapper (Interaction, Transformed, Standardized) is constant when its parts are. Finite-half-life statistics remain available to the ordinal likelihood; their continuously varying hazard is not integrated by the timing fitter.
Example
using Revel
Revel.is_interval_constant(PShift(:AB_BA)) # true
Revel.is_interval_constant(Inertia()) # true
Revel.is_interval_constant(Inertia(memory=HalfLife(2.0))) # falseModeration by refitting
Revel.fit_stratified — Function
fit_stratified(events, statistics, n_actors; by, kwargs...) -> DictFit the model separately within strata of the events being explained, while every event still builds the history: by is a function event -> key, and the result maps each key to a RevelFit whose cases are the events with that key.
This is the stratified form of moderation — every coefficient is free to differ by event type (by = e -> e.eventtype; the type-specific intensities of Vu, Lomi, Mascia & Pallotti 2017), weekday, period or context. It equals a product-term model only when all interactions with the stratifier are included (the stratum likelihoods are disjoint factors of one partial likelihood), and it is not the same model as a statistic filtered on the stratifier. Because the factors are disjoint, the estimates of different strata are asymptotically independent, and compare_coefficients with reference= gives the Wald test of each difference. A difference in significance is not a significant difference.
The risk set of a stratum. When the stratum of an event depends on who acts — by = e -> department[e.sender] — the events of one stratum can only have been produced by some of the dyads, and fitting them against every dyad would let the model "explain" the stratum itself (a sender covariate then absorbs the selection). So each event's risk set is restricted to the dyads that would have produced an event of the same stratum: by is applied to the candidate event Event(s, r, time; eventtype, weight) of every dyad, and the dyads whose key differs are dropped. A stratifier that does not depend on the dyad (the time, the event type) keeps the full risk set, as before. The restriction is applied to riskset=:full or a vector of dyads; with another riskset a dyad-dependent stratifier is refused.
Keywords are those of fit_revel (the ordinal model), except cases, which the strata define.
Example
using Revel, Random
stats = [Inertia(transform=:log1p)]
events = simulate_events(stats, [1.0], 5, 120; rng=Xoshiro(5))
fits = fit_stratified(events, stats, 5; by = e -> e.time <= 60 ? :early : :late)
sort(collect(keys(fits))) # [:early, :late]
nobs(fits[:early]) + nobs(fits[:late]) # 120Revel.fit_moving_window — Function
fit_moving_window(events, statistics, n_actors; width, step=width,
min_events=10, kwargs...) -> Vector{NamedTuple}Refit the model on the events of successive time windows [from, from + width), advancing by step, with the whole earlier sequence as history. Each element is (from, to, n_events, fit); a window with fewer than min_events events is skipped.
This is the moving-window route to time-varying coefficients (Mulder & Leenders 2019; Meijerink-Bosman, Leenders & Mulder 2022): it shows whether an effect such as reciprocity strengthens or fades over the observation period without committing to a functional form. Overlapping windows (step < width) smooth the path and make neighbouring estimates dependent. Use compare_coefficients for the path as a table; with non-overlapping windows its reference= Wald tests are valid.
Example
using Revel, Random
stats = [Inertia(transform=:log1p)]
events = simulate_events(stats, [1.0], 5, 150; rng=Xoshiro(6))
path = fit_moving_window(events, stats, 5; width=50.0)
length(path) # 3
[w.n_events for w in path] # [50, 50, 50]Revel.compare_coefficients — Function
compare_coefficients(fits; reference=nothing) -> DataFrameA long table — one row per (fit, coefficient) with group, term, estimate, std_error, z, n_events — of several fits of the same specification: the Dict returned by fit_stratified, the vector returned by fit_moving_window (grouped by window start), or any collection of key => fit pairs. It lays the stratified, windowed and pooled estimates side by side, which is how the literature reads a moderation by refitting.
With reference=key the table also holds, for every other group, the Wald test of the difference from the reference group's coefficient: difference, se_difference = √(se² + se_ref²) and its two-sided p_difference (missing in the reference rows). A fit with no finite maximum (separation) has z, and every p_difference that involves it, NaN. The test assumes the fits are independent, which holds for the strata of fit_stratified and for non-overlapping windows — their likelihoods are disjoint factors of one partial likelihood — and is refused for overlapping windows.
Example
using Revel, Random
stats = [Inertia(transform=:log1p)]
events = simulate_events(stats, [1.0], 5, 120; rng=Xoshiro(5))
fits = fit_stratified(events, stats, 5; by = e -> e.time <= 60 ? :early : :late)
table = compare_coefficients(fits)
size(table) # (2, 6)
names(table) # ["group", "term", "estimate", "std_error", "z", "n_events"]
tested = compare_coefficients(fits; reference=:early)
tested.p_difference[2] > 0.05 # true — one process throughoutRevel.profile_memory — Function
profile_memory(build, events, n_actors, grid; level=0.95, kwargs...) -> DataFrameEstimate a memory parameter by profile likelihood: for each value in grid, fit the model whose statistics are build(value) and record the maximised log-likelihood. The table has one row per value — value, loglik, aic, bic, converged, in_ci, best. best marks the maximum among the fits that converged to a finite likelihood; in_ci marks the values inside the profile-likelihood confidence set {h : 2(ℓ_max − ℓ(h)) ≤ χ²₁(level)}, which is as fine as the grid. aic and bic count the memory parameter as estimated, so they compare directly with a model that has no memory parameter. A value whose fit has no finite maximum (separation) is kept with converged = false and left out of best and in_ci; a value whose fit throws is kept with loglik = NaN, converged = false, and the error is reported as a warning.
The literature's guidance is that memory should be estimated, not assumed: transitivity estimates move from about zero to above one across plausible half-lives (Arena, Mulder & Leenders 2023), and half-lives and windows in applied work span orders of magnitude. The same function profiles a window width, a power-law exponent (the grid search of the Lomi–Vu line) or any other scalar the statistics depend on. Keywords are those of fit_revel; with n_controls, every grid value is fitted on the same draw of controls (the rng is copied before each fit), so the profile compares models, not samples.
The profile treats the memory parameter as fixed when the standard errors of the other coefficients are computed; they do not reflect its uncertainty.
Example
using Revel, Random
truth = [Inertia(memory=HalfLife(5.0), transform=:log1p)]
events = simulate_events(truth, [1.5], 6, 300; rng=Xoshiro(8))
profile = profile_memory(events, 6, [1.0, 5.0, 25.0, 125.0]) do h
[Inertia(memory=HalfLife(h), transform=:log1p)]
end
profile.value[profile.best] # [5.0] — the half-life the data prefer
profile.value[profile.in_ci] # the half-lives the data do not rejectSimulation
Revel.simulate_events — Function
simulate_events(statistics, coefficients, n_actors, n_events;
rng=Random.default_rng(), times=nothing, ties=:ordered,
baseline=nothing, t0=nothing, directed=true, riskset=:full,
senders=nothing, history=Event{Float64}[], eventtype=:event,
weights=nothing)
-> Vector{Event{Float64}}Simulate a relational event sequence from a model: at each step the next dyad is drawn from the risk set with probability proportional to exp(θ'x), the statistics x being read off the events simulated so far.
The clock is one of three:
- default — events occur at times
1, 2, …, n_events(an ordinal model says nothing about time); times=— the given event times are used, in order. This is how a fitted ordinal model is simulated for goodness of fit: conditional on the observed timestamps, so that time-based memory (a half-life in clock units) keeps its meaning. Withties=:breslowor:efronthe events drawn at one timestamp do not see each other — the history is frozen across the tie, as it is in a fit with those policies;:ordered(default) adds each event to the history as it is drawn. The two corrections also fix how a tie block is drawn::breslowdraws its events independently (with replacement — the model whose likelihood Breslow's is),:efronwithout replacement, so a dyad acts at most once per timestamp, which is what an Efron fit requires;baseline=λ₀— waiting times are exponential with rateλ₀ Σ exp(θ'x), the interval-timing model, starting fromt0(default: the last event ofhistory, or 0). The hazard is held constant between events, so every statistic must be constant between events (seefit_revelfor which are).
riskset is :full, a vector of dyads (e.g. two_mode_dyads), or :sender together with senders= (a vector giving the sender of each event) to simulate receiver choices only. history seeds the process with earlier events. eventtype (one Symbol, or one per event) and weights (one per event) are exogenous marks stamped on the simulated events — the ordinal model conditions on them. All randomness comes from rng.
Cumulative statistics with positive coefficients feed back on themselves and can make the process explode; scale them (transform=:log1p, Standardized) or use a decaying memory.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [1.0, 0.5], 5, 100; rng=Xoshiro(1))
length(events), events[end].time # (100, 100.0)
timed = simulate_events([Inertia(transform=:log1p)], [1.0], 5, 50;
baseline=0.1, rng=Xoshiro(1))
issorted(e.time for e in timed) # trueResult accessors
A RevelFit forwards the StatsAPI verbs to the underlying estimator's result, and the ecosystem's result-metadata protocol (NetworkCore.fit_metadata(fit): estimand, objective, exactness, standard-error method, tie method, approximations) likewise.
StatsAPI.coef — Method
coef(fit::RevelFit) -> Vector{Float64}The estimated coefficients, in coefnames order (StatsAPI). An interval-timing fit puts the log baseline rate first.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
round.(coef(fit); digits=1) # [0.6, 0.5] — the truth is [0.8, 0.6]StatsAPI.stderror — Method
stderror(fit::RevelFit) -> Vector{Float64}Standard errors of the coefficients (StatsAPI): the square roots of the diagonal of vcov, under the estimator NetworkCore.se_method(fit) names.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
all(0 .< stderror(fit) .< 0.2) # trueStatsAPI.vcov — Method
vcov(fit::RevelFit) -> Matrix{Float64}The covariance matrix of the coefficients (StatsAPI): the inverse observed information, or the event-clustered sandwich for a fit with se=:sandwich.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
size(vcov(fit)) # (2, 2)
sqrt.([vcov(fit)[1, 1], vcov(fit)[2, 2]]) ≈ stderror(fit) # trueStatsAPI.confint — Method
confint(fit::RevelFit; level=0.95) -> Matrix{Float64}Wald confidence intervals, one row per coefficient (StatsAPI).
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
ci = confint(fit; level=0.9)
all(ci[:, 1] .< coef(fit) .< ci[:, 2]) # trueStatsAPI.loglikelihood — Method
loglikelihood(fit::RevelFit) -> Float64The maximised log-likelihood (StatsAPI): the ordinal partial likelihood of the risk sets the fit used, or the interval-timing likelihood. Likelihoods of fits on different risk sets, or of the two kinds of model, are not comparable.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
loglikelihood(fit) < 0 # true
-2loglikelihood(fit) ≈ prediction_summary(fit).deviance # trueStatsAPI.nobs — Method
nobs(fit::RevelFit) -> IntThe number of events the likelihood was built from (StatsAPI) — the events selected by cases, not the rows of the design.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
nobs(fit) # 200
nobs(fit_revel(events, stats, 6; cases=101:200)) # 100StatsAPI.dof — Method
dof(fit::RevelFit) -> IntThe number of estimated coefficients (StatsAPI), including the log baseline of an interval-timing fit.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
dof(fit) # 2
dof(fit_revel(events, stats, 6; model=:timing)) # 3StatsAPI.aic — Method
aic(fit::RevelFit) -> Float64Akaike's information criterion, -2 loglikelihood + 2 dof (StatsAPI). Compare only fits of the same events on the same risk sets.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
aic(fit) ≈ -2loglikelihood(fit) + 2dof(fit) # true
aic(fit) < aic(fit_revel(events, stats[1:1], 6)) # reciprocity earns its placeStatsAPI.bic — Method
bic(fit::RevelFit) -> Float64The Bayesian information criterion, -2 loglikelihood + log(nobs) dof (StatsAPI), with the number of events as the sample size.
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
bic(fit) ≈ -2loglikelihood(fit) + log(nobs(fit)) * dof(fit) # trueStatsAPI.coeftable — Method
coeftable(fit::RevelFit) -> NetworkCore.CoefficientTableThe coefficient table — estimates, standard errors, z- and p-values — as the ecosystem's shared NetworkCore.CoefficientTable (StatsAPI's coeftable).
Example
using Revel, Random
stats = [Inertia(transform=:log1p), Reciprocation(transform=:log1p)]
events = simulate_events(stats, [0.8, 0.6], 6, 200; rng=Xoshiro(7))
fit = fit_revel(events, stats, 6)
table = coeftable(fit)
table isa Revel.NetworkCore.CoefficientTable # trueStatsAPI.coefnames — Method
coefnames(fit::RevelFit) -> Vector{String}The coefficient names in coef(fit) order: the statistic names, preceded by "log_baseline" for an interval-timing fit.
Example
using Revel, Random
events = simulate_events([Inertia(transform=:log1p)], [1.0], 5, 60; rng=Xoshiro(4))
coefnames(fit_revel(events, [Inertia(transform=:log1p), OTP()], 5)) # ["log1p(inertia)", "otp"]