API Reference¶
Auto-generated from the source docstrings. For a task-oriented walkthrough with examples, see the API Guide.
All symbols below are importable directly from the top-level logit_graph package, e.g.
from logit_graph import simulate_graph.
The model — Logistic Random Graph (LG)¶
There is a single model, the Logistic Random Graph (LG) of Ottoni, Takahashi & Fujita (2026);
the entries below are its computational forms and the general-pairwise-features extension (§3.7).
All score an edge with a logistic link and differ only in what enters the linear predictor η_ij.
| Form | Edge log-odds η_ij |
Packaged as |
|---|---|---|
| Equilibrium sampler | σ + α·[g(S_i)+g(S_j)] at stationarity (Gibbs) |
simulate_graph, GraphModel |
| Iterative generation | same, with S evaluated on the lagged graph G(t-1) (Eq. 3.5) |
LG generation & estimation |
| General pairwise features (§3.7) | σ + Σₖ θₖ·φₖ(i,j) — degree term plus extra features |
Unified LG |
σ— baseline connection propensity (baseline log-odds; typically negative).α ≥ 0— strength of the neighborhood degree effect ong(S_i)+g(S_j),g(s)=log(1+s),S_i = Σ_{l∈N_d(i)} k_lthe neighborhood degree sum over thed-hop ball.d— the neighborhood radius (hops).d=0uses each node's own degree only (S_i = k_i);d=1adds the neighbors' degrees; largerdreaches further. Selected from data by AIC.φₖ(extra features) — appended columns: exogenous / pair-local ones (e.g. block membership viacommunity_feature) are directly estimable; globally-coupled ones (e.g. latent proximity vialatent_feature, or the degree term itself) are made consistent by the predetermined-predictor (temporal) form that reads them offG(t-1). The unified five-feature LG model of the thesis is the instance with degree + coarse/fine community (γc,γf) + latent proximity (λ).
Paper-consistent sampler & estimator¶
simulate_graph ¶
simulate_graph(
n: int,
d: int,
sigma: Optional[float] = None,
*,
beta: Optional[float] = None,
n_iter: int,
feature_mode: FeatureMode = "incremental",
target_density: float = 0.1,
signal: float = 0.5,
seed: Optional[int] = None,
return_meta: bool = False,
collect_feature_mean: bool = False,
materialize_adjacency: bool = True,
feature_mode_est: Optional[FeatureMode] = None,
adaptive_stopping: bool = False,
adaptive_check_interval: int = 20000,
adaptive_patience: int = 3,
adaptive_cv_tol: float = 0.02,
adaptive_min_iter: int = 20000
) -> np.ndarray | tuple[np.ndarray, dict[str, float]]
Generate a graph at fixed sigma. d=0 uses a direct ER sample at p=expit(sigma) (exact equilibrium, no degree feedback); d>=1 runs leave-one-out Gibbs with the feature coefficient fixed at beta=1 (matching the paper offset estimator).
Source code in src/logit_graph/experiments/sweeps.py
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
select_d_ensemble ¶
select_d_ensemble(
graphs: list[ndarray],
d_candidates: list[int],
feature_mode: FeatureMode,
extra_penalty_per_d: float = 0.0,
*,
csr_rows_list: Optional[list[Optional[list]]] = None
) -> tuple[int, dict[int, dict[str, float]]]
Source code in src/logit_graph/experiments/sweeps.py
estimate_sigma_from_graph ¶
estimate_sigma_from_graph(
adj: Optional[ndarray],
d: int,
feature_mode: FeatureMode = "incremental",
beta: float = 1.0,
*,
csr_rows: Optional[list] = None
) -> float
Source code in src/logit_graph/experiments/sweeps.py
High-level API (scikit-learn style)¶
LogitGraphFitter ¶
LogitGraphFitter(
d: int = 0,
n_iteration: int = 10000,
warm_up: int = 500,
patience: int = 2000,
dist_type: str = "KL",
edge_delta: Optional[float] = None,
min_gic_threshold: float = 5,
check_interval: int = 50,
verbose: bool = True,
er_p: float = 0.05,
init_graph: Optional[Graph] = None,
)
Fits a single Logit Graph model to a real graph, following a scikit-learn-like API.
Initialize the LogitGraphFitter: d (latent depth), n_iteration cap, warm_up, patience (checks without improvement before stopping), dist_type for GIC, edge_delta / min_gic_threshold convergence thresholds, check_interval, verbose.
Source code in src/logit_graph/simulation.py
fit ¶
Fit the Logit Graph model to original_graph; returns self with the
fitted_graph and metadata attributes populated.
Source code in src/logit_graph/simulation.py
LogitGraphSimulation ¶
LogitGraphSimulation(
n: int,
d: int,
sigma: float,
alpha: float = 1.0,
beta: float = 1.0,
er_p: float = 0.05,
n_iteration: int = 10000,
warm_up: int = 500,
patience: int = 2000,
check_interval: int = 50,
edge_cv_tol: float = 0.02,
spectrum_cv_tol: float = 0.02,
verbose: bool = True,
init_graph: Optional[Graph] = None,
layer2: bool = True,
feature_mode: FeatureMode = "bounded",
fast_mode: bool = False,
)
Simulate a Logit Graph directly from provided parameters (scikit-learn-like API):
sim = LogitGraphSimulation(n=100, d=2, sigma=1.0, alpha=1.0, beta=1.0); sim.simulate(),
then read sim.simulated_graph and sim.metadata.
Initialize the LogitGraphSimulation: model params (n, d, sigma, alpha, beta, er_p) and run params (n_iteration, warm_up, patience window, check_interval, edge/spectrum CV tolerances, verbose, init_graph).
Source code in src/logit_graph/simulation.py
simulate ¶
Run the simulation, storing the graph and metadata. d=0 samples directly from ER(p=expit(sigma)) (exact equilibrium); d>=1 warm-starts the Gibbs chain near expit(sigma) clipped to [0.02, 0.5], unless init_graph or a non-default er_p overrides.
Source code in src/logit_graph/simulation.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
GraphModelComparator ¶
GraphModelComparator(
d_list: list[int],
lg_params: dict[str, Any],
other_model_n_runs: int = 2,
other_model_params: Optional[
list[dict[str, Any]]
] = None,
dist_type: str = "KL",
verbose: bool = True,
other_models: Optional[list[str]] = None,
other_model_grid_points: int = 5,
random_state: Optional[int] = 42,
)
Compares Logit Graph with other random graph models, with a scikit-learn-like API.
Initialize the GraphModelComparator: d_list to test, lg_params (LG fitting), other_model_n_runs / other_model_params for the baselines, dist_type for GIC, verbose, and random_state (None for non-reproducible runs).
Source code in src/logit_graph/simulation.py
compare ¶
Fit LG and the other models to original_graph (graph_filepath used only
for logging) and compare them; returns self with summary_df and
fitted_graphs_data populated.
Source code in src/logit_graph/simulation.py
estimate_sigma_only ¶
estimate_sigma_only(
graph_input: Union[ndarray, Graph],
d: int,
max_pairs: Optional[int] = None,
feature_mode: FeatureMode = "incremental",
random_state: Optional[int] = None,
verbose: bool = False,
max_edges: Optional[int] = None,
max_non_edges: Optional[int] = None,
l1_wt: float = 1,
alpha: float = 0,
) -> tuple[float, Any]
Estimate sigma via the leave-one-out (full conditional) offset logit (paper formulation),
using :func:build_pair_dataset (layer2=True) so it stays consistent with generation.
Returns (sigma_hat, fit_result); legacy max_edges/max_non_edges/l1_wt/alpha unused.
Source code in src/logit_graph/simulation.py
estimate_sigma_many ¶
estimate_sigma_many(
graph_input: Union[ndarray, Graph],
d: int,
n_repeats: int = 30,
max_pairs: Optional[int] = None,
feature_mode: FeatureMode = "incremental",
seed: int = 42,
verbose: bool = False,
max_edges: Optional[int] = None,
max_non_edges: Optional[int] = None,
l1_wt: float = 1,
alpha: float = 0,
) -> list[float]
Repeat the leave-one-out sigma estimation n_repeats times with different seeds, returning
a list of sigma_hat. Variability comes from random pair sampling when max_pairs
is set; with max_pairs=None on a small graph every repetition is identical.
Source code in src/logit_graph/simulation.py
calculate_graph_attributes ¶
Calculate various graph attributes for a given graph.
Source code in src/logit_graph/simulation.py
Core model & estimator¶
GraphModel ¶
GraphModel(
n: int,
d: int,
sigma: float,
alpha: float = 1,
beta: float = 1,
er_p: float = 0.05,
init_graph: Optional[Graph] = None,
layer2: bool = True,
feature_mode: FeatureMode = "incremental",
seed: Optional[int] = None,
)
Source code in src/logit_graph/graph.py
generate_small_er_graph ¶
Vectorized ER sample (symmetric, uses self._rng).
calculate_spectrum
classmethod
¶
Sorted eigenvalues of the Laplacian L = D - A.
get_edge_logit ¶
Bernoulli draw with probability = logistic(sum_degrees). Kept for backward compatibility; the add_remove_edge hot-path inlines a faster equivalent.
Source code in src/logit_graph/graph.py
add_remove_edge ¶
Propose a random node pair and set / clear their edge.
Source code in src/logit_graph/graph.py
add_remove_edge_adj_only ¶
Neighbor-list path without dense-matrix sync (fast_mode partial).
materialize_adjacency ¶
Rebuild dense adjacency from neighbor lists.
Source code in src/logit_graph/graph.py
populate_edges_baseline ¶
populate_edges_baseline(
warm_up: int,
max_iterations: int,
patience: int,
check_interval: int = 50,
edge_cv_tol: float = 0.02,
spectrum_cv_tol: float = 0.02,
fast_mode: bool = False,
) -> tuple[list[np.ndarray], np.ndarray]
Generate a graph without a ground-truth reference. Convergence uses the
coefficient of variation (std/mean) of edge counts and spectrum norms over the last
patience checks; fast_mode=True skips checks and runs max_iterations steps.
Source code in src/logit_graph/graph.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
populate_edges_spectrum ¶
populate_edges_spectrum(
warm_up: int,
max_iterations: int,
patience: int,
real_graph: ndarray,
edge_delta: Optional[float] = None,
check_interval: int = 50,
verbose: bool = True,
) -> tuple[list[np.ndarray], np.ndarray, list[float], int]
Legacy spectrum-only convergence (no GIC gate).
Source code in src/logit_graph/graph.py
populate_edges_spectrum_min_gic ¶
populate_edges_spectrum_min_gic(
max_iterations: int,
patience: int,
real_graph: Union[ndarray, Graph],
min_gic_threshold: float,
gic_dist_type: str = "KL",
edge_delta: Optional[float] = None,
check_interval: int = 50,
verbose: bool = True,
er_p: float = 0.05,
) -> tuple[
list[np.ndarray],
np.ndarray,
list[float],
int,
np.ndarray,
list[float],
]
Populate edges targeting a real graph via a two-phase criterion: Phase 1 (GIC
gate) iterates until GIC vs the real graph drops below min_gic_threshold; Phase 2
tracks the best Laplacian-spectrum distance and stops after patience checks w/o gain.
Source code in src/logit_graph/graph.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
LogitRegEstimator ¶
LogitRegEstimator(
graph: Union[ndarray, Graph],
d: int,
verbose: bool = False,
layer2: bool = True,
feature_mode: FeatureMode = "incremental",
)
Source code in src/logit_graph/logit_estimator.py
compute_aic ¶
compute_aic(
d_est: Optional[int] = None,
feature_mode: Optional[FeatureMode] = None,
layer2: Optional[bool] = None,
extra_penalty: float = 0.0,
) -> dict[str, float]
Paper AIC: -2*ll + 2 (one parameter sigma).
Source code in src/logit_graph/logit_estimator.py
select_d ¶
select_d(
d_candidates: Optional[list[int]] = None,
feature_mode: Optional[FeatureMode] = None,
extra_penalty_per_d: float = 0.0,
) -> tuple[int, dict[int, dict[str, float]]]
Return argmin_d AIC(d) and per-d stats.
Source code in src/logit_graph/logit_estimator.py
estimate_parameters ¶
estimate_parameters(
l1_wt: float = 1,
alpha: float = 0,
features: Optional[ndarray] = None,
labels: Optional[list[int]] = None,
fix_beta: bool = True,
) -> tuple[Any, np.ndarray, np.ndarray]
Fit the logistic regression on the extracted features/labels. fix_beta=True (default) fixes the degree-sum coefficient at 1 (offset) and estimates only sigma (paper form); fix_beta=False frees both sigma and beta, using l1_wt/alpha (legacy).
Source code in src/logit_graph/logit_estimator.py
Features¶
build_pair_dataset ¶
build_pair_dataset(
graph: Union[ndarray, Graph],
d: int,
mode: FeatureMode = "bounded",
layer2: bool = True,
alpha_gwesp: float = ALPHA_GWESP_DEFAULT,
max_pairs: Optional[int] = None,
seed: Optional[int] = None,
) -> tuple[np.ndarray, np.ndarray]
Build offset vector and binary labels for all upper-triangle pairs. Returns
(offsets, labels): offsets are (m,) feature values (the fixed beta=1 offset),
labels are (m,) 0/1 edge indicators.
Source code in src/logit_graph/lg_features.py
pair_feature ¶
pair_feature(
graph: ndarray,
i: int,
j: int,
d: int,
mode: FeatureMode = "bounded",
alpha_gwesp: float = ALPHA_GWESP_DEFAULT,
) -> float
Pair feature x_ij used as offset (beta fixed at 1 in paper estimator).
Source code in src/logit_graph/lg_features.py
pair_feature_layer2 ¶
pair_feature_layer2(
graph: Union[ndarray, Graph],
i: int,
j: int,
d: int,
mode: FeatureMode = "bounded",
alpha_gwesp: float = ALPHA_GWESP_DEFAULT,
) -> float
Leave-one-out (full conditional) feature: computed on the graph with edge (i,j) removed.
Source code in src/logit_graph/lg_features.py
incremental_h ¶
incremental_h(
graph: ndarray,
i: int,
j: int,
d: int,
alpha_gwesp: float = ALPHA_GWESP_DEFAULT,
) -> float
Source code in src/logit_graph/lg_features.py
recommended_iterations ¶
Gibbs steps so each edge is resampled O(1) times.
LG: iterative generation & estimation¶
The LG iterative generation algorithm and its estimator: logit Pr[A_ij(t)=1 | G(t-1)] = σ + α·D(t-1)
(Eq. 3.5), with the degree term D = g(S_i)+g(S_j) read from the predetermined previous graph so the
pooled dyad design is an ordinary logistic regression and the MLE of (σ, α) is consistent.
grow_graph ¶
grow_graph(
n: int,
d: int,
sigma: float,
alpha: float,
*,
n_steps: int,
degree_mode: FeatureMode = DEGREE_MODE,
seed: int | None = None,
p0: float = 0.02,
record_design: bool = True,
store_snapshots: bool = True,
allow_removal: bool = True,
until_convergence: bool = False,
esd_tol: float = 0.01,
patience: int = 3,
esd_nbins: int = 50,
step_callback=None
) -> GrowthResult
Grow a temporal Logit-Graph from a sparse ER seed (degree-only). allow_removal (default) resamples every dyad from lagged expit(sigma+alpha*D) — edges form and dissolve (ergodic chain); allow_removal=False grows add-only to saturation.
Source code in src/logit_graph/temporal.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
GrowthResult
dataclass
¶
Output of :func:grow_graph: final adjacency adj (n x n, 0/1, symmetric),
pooled design X (m,1)=[D] / outcomes y (1=at-risk non-edge formed),
snapshots G(0..n_steps) (empty if not stored), and the generative params.
growth_design_from_snapshots ¶
growth_design_from_snapshots(
snapshots: list,
d: int,
*,
degree_mode: FeatureMode = DEGREE_MODE,
allow_removal: bool = True
) -> tuple[np.ndarray, np.ndarray]
Build the at-risk logistic-regression design from observed snapshots: predictor D from G(t-1), outcome = formed in G(t). With allow_removal the set is all dyads and the outcome is each dyad's full new state — matching grow_graph (whose design it reproduces).
Source code in src/logit_graph/temporal.py
fit_growth_params ¶
Fit logit(P[form]) = sigma + alpha*D by ordinary logistic regression — the exact, consistent MLE for the growth model (dyad-independent given the past). Returns sigma, alpha, their SEs, the log-likelihood, AIC (k=2), and n_params.
Source code in src/logit_graph/temporal.py
fit_growth_from_result ¶
Unified LG: general pairwise features¶
The §3.7 extension logit p_ij = σ + Σₖ θₖ·φₖ(i,j): the degree term plus arbitrary appended pairwise
features. grow_graph_multi / fit_multi_params mirror the degree-only API but carry the extra features;
community_feature (block membership) and latent_feature (latent proximity) build the canonical
covariates of the thesis's unified five-feature LG model from an observed graph.
grow_graph_multi ¶
grow_graph_multi(
n: int,
d: int,
sigma: float,
alpha: float,
features: ndarray,
coefs,
*,
n_steps: int,
feature_names: list | None = None,
degree_mode: FeatureMode = DEGREE_MODE,
allow_removal: bool = True,
seed: int | None = None,
p0: float = 0.02,
record_design: bool = True,
store_snapshots: bool = True
) -> MultiGrowthResult
Generate from the unified LG (general pairwise features) by growth from a sparse ER seed:
features (n(n-1)/2, k) are fixed pairwise covariates phi_k with coefficients coefs, and each
step draws dyads from expit(sigma + alphaD + features @ coefs), D from G(t-1) (allow_removal=ergodic).
Source code in src/logit_graph/temporal_multi.py
MultiGrowthResult
dataclass
¶
MultiGrowthResult(
adj: ndarray,
X: ndarray,
y: ndarray,
feature_names: list,
snapshots: list,
params: dict,
)
Output of :func:grow_graph_multi: final adjacency adj (n x n, 0/1, symmetric),
pooled design X (m, 1+k) = [D, F_1..F_k] / outcomes y, the feature_names for the
extra covariates, the snapshots G(0..n_steps) (empty if not stored), and params.
multi_design_from_snapshots ¶
multi_design_from_snapshots(
snapshots: list,
d: int,
features: ndarray,
*,
degree_mode: FeatureMode = DEGREE_MODE,
allow_removal: bool = True
) -> tuple[np.ndarray, np.ndarray]
Build the pooled [D, F_1..F_k] design from observed snapshots: D from G(t-1), the extra
fixed features repeated each step, outcome from G(t). With allow_removal the design is
over all dyads (else the at-risk non-edges). Reproduces grow_graph_multi's recorded design.
Source code in src/logit_graph/temporal_multi.py
fit_multi_params ¶
Fit logit(P) = sigma + alphaD + sum_k beta_kF_k by pooled logistic regression — the exact, consistent MLE for the multi-feature temporal model. Returns sigma, alpha, the per-feature coefficients and their SEs, the log-likelihood, AIC, and n_params (solver fallbacks for robustness).
Source code in src/logit_graph/temporal_multi.py
community_feature ¶
Same-community indicator over upper-triangle dyads from a fixed Louvain partition of the graph at the given resolution (higher resolution -> finer communities). An exogenous node covariate, like SBM uses, so it stays identifiable. Returns a (n*(n-1)/2,) float array.
Source code in src/logit_graph/temporal_multi.py
latent_feature ¶
Latent proximity over upper-triangle dyads from a rank-k adjacency spectral embedding z (eigvecs scaled by sqrt|eigval|). kind="dot": z_i . z_j (RDPG inner product); kind="dist": -||z_i - z_j|| (Hoff latent-space distance). Standardized; returns a (n*(n-1)/2,) array.
Source code in src/logit_graph/temporal_multi.py
Experiment configuration¶
AICSweepConfig
dataclass
¶
AICSweepConfig(
d_true_values: list[int] = (lambda: [0, 1, 2, 3])(),
d_est_values: list[int] = (lambda: [0, 1, 2, 3])(),
n_sizes: list[int] = (lambda: [100])(),
n_runs: int = 4,
m_ensemble: int = 3,
iter_cap: Optional[int] = 30000,
target_density: float = 0.1,
signal: float = 0.5,
aic_penalty_per_d: float = 3.0,
feature_mode_gen: str = "incremental",
feature_mode_est: str = "incremental",
seed_base: int = 1000,
sigma_gen: float = -3.0,
iter_cap_by_d: Optional[dict] = None,
sigma_gen_per_n: Optional[dict] = None,
m_ensemble_by_d: Optional[dict] = None,
sigma_gen_per_n_d: Optional[dict] = None,
)
SigmaSweepConfig
dataclass
¶
SigmaSweepConfig(
sigma_values: list[float] = (
lambda: [-2.0, -4.0, -6.0, -8.0]
)(),
d_values: list[int] = (lambda: [0, 1, 2])(),
n_values: list[int] = (lambda: [50, 100])(),
n_reps: int = 4,
iter_cap: Optional[int] = 80000,
target_density: float = 0.1,
signal: float = 0.5,
feature_mode_gen: str = "incremental",
feature_mode_est: str = "incremental",
seed_base: int = 0,
adaptive_stopping: bool = False,
adaptive_check_interval: int = 20000,
adaptive_patience: int = 3,
adaptive_cv_tol: float = 0.02,
adaptive_min_iter: int = 20000,
iter_cap_by_d: Optional[dict] = None,
n_values_by_sigma: Optional[dict] = None,
)