inst/examples/swissmetro/plot_b11c_cnl_sparse.R

#!/usr/bin/env Rscript

# b11c. Cross-nested logit with a sparse structure
#
# This example omits only literal-zero CNL memberships. Train remains in both
# nests through symbolic alpha expressions; those parameter-dependent entries
# are never dropped by the sparse interface.

library(rbiogeme)

# prepare_swissmetro_example() is defined in example_utils.R. It parses the
# command line, validates the data/Python paths, configures the bridge, reads
# the data, and creates a fresh output directory. The --data, --python, and
# --output options work from any current working directory.
script_path <- commandArgs(trailingOnly = FALSE)
script_path <- sub("^--file=", "", script_path[startsWith(script_path, "--file=")][[1L]])
source(file.path(dirname(normalizePath(script_path)), "example_utils.R"))

build_b11c_cnl_sparse_model <- function(database) {
  # These names, starts, bounds, and the fixed ASC match native b11c.
  asc_car <- biogeme_beta("asc_car", start = 0)
  asc_train <- biogeme_beta("asc_train", start = 0)
  asc_sm <- biogeme_beta("asc_sm", start = 0, fixed = TRUE)
  b_time <- biogeme_beta("b_time", start = 0)
  b_cost <- biogeme_beta("b_cost", start = 0)
  existing_nest_parameter <- biogeme_beta(
    "existing_nest_parameter", start = 1, lower = 1, upper = 5
  )
  public_nest_parameter <- biogeme_beta(
    "public_nest_parameter", start = 1, lower = 1, upper = 5
  )
  alpha_existing <- biogeme_beta(
    "alpha_existing", start = 0.5, lower = 0, upper = 1
  )
  alpha_public <- 1 - alpha_existing

  utilities <- list(
    `1` = asc_train + b_time * variable("TRAIN_TT_SCALED") +
      b_cost * variable("TRAIN_COST_SCALED"),
    `2` = asc_sm + b_time * variable("SM_TT_SCALED") +
      b_cost * variable("SM_COST_SCALED"),
    `3` = asc_car + b_time * variable("CAR_TT_SCALED") +
      b_cost * variable("CAR_CO_SCALED")
  )
  availability <- list(
    `1` = variable("TRAIN_AV_SP"),
    `2` = variable("SM_AV"),
    `3` = variable("CAR_AV_SP")
  )

  # sparse=TRUE means missing allocation keys are structural zeros. The
  # supplied alpha_existing and alpha_public nodes remain active symbolic
  # allocations, while the literal zeros for Car/Public and Swissmetro/Existing
  # are omitted exactly as in native b11c.
  nests <- cross_nested_nests(
    choice_set = c(1L, 2L, 3L),
    sparse = TRUE,
    nests = list(
      cross_nested_nest(
        existing_nest_parameter,
        list(`1` = alpha_existing, `3` = 1),
        name = "existing"
      ),
      cross_nested_nest(
        public_nest_parameter,
        list(`1` = alpha_public, `2` = 1),
        name = "public"
      )
    )
  )

  # cross_nested_logit_model() compiles native models.logcnl and preserves the
  # sparse allocation mappings in the native NestsForCrossNestedLogit object.
  cross_nested_logit_model(
    database = database,
    choice = "CHOICE",
    utilities = utilities,
    availability = availability,
    nests = nests,
    control = biogeme_control(
    output_directory = prepared$output,
      model_name = "b11c_cnl_sparse",
      generate_html = TRUE,
      generate_yaml = FALSE,
      save_iterations = FALSE
    )
  )
}

prepared <- prepare_swissmetro_example(
  commandArgs(trailingOnly = TRUE),
  default_model = "b11c_cnl_sparse"
)

# Always estimate from the expression tree. Remove only exact b11c artifacts
# so a previous YAML or iteration file cannot silently be recycled.
stale_files <- c(
  "b11c_cnl_sparse.yaml",
  "__b11c_cnl_sparse.iter",
  "b11c_cnl_sparse.html"
)
stale_files <- file.path(prepared$output, stale_files)
stale_files <- stale_files[file.exists(stale_files)]
if (length(stale_files) > 0L) unlink(stale_files, force = TRUE)

database <- swissmetro_data(prepared$data)
model <- build_b11c_cnl_sparse_model(database)
print(cross_nested_sparsity_report(model$nests))

# Estimation, derivatives, optimization, and reporting are delegated to
# native Biogeme; R only owns the symbolic specification and presentation.
fit <- estimate(
  model,
  model_name = "b11c_cnl_sparse",
  control = model$control
)
print(summary(fit))
print(coef(fit))

invisible(fit)

Try the rbiogeme package in your browser

Any scripts or data that you put into this service are public.

rbiogeme documentation built on Sept. 29, 2026, 5:09 p.m.