inst/examples/swissmetro/plot_b05b_normal_mixture_integral.R

#!/usr/bin/env Rscript

# b05b. Normal mixture with numerical integration
#
# This example replaces Monte Carlo integration with native deterministic
# Gauss-Hermite integration over a standard-normal random variable. The
# conditional logit kernel, integration node, likelihood, and optimizer all
# remain native Python Biogeme operations.

library(rbiogeme)

# The shared helper contains command-line parsing and data preparation. The
# complete model specification remains in this script.
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_b05b_normal_mixture_integral_model <- function(
    database,
    number_of_quadrature_points = 30L
) {
  # These parameters match the native example. The Swissmetro ASC is fixed
  # at zero to identify the model.
  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_cost <- biogeme_beta("b_cost", start = 0)
  b_time <- biogeme_beta("b_time", start = 0)
  b_time_s <- biogeme_beta("b_time_s", start = 1)

  # random_variable() creates the named native RandomVariable node used by
  # integrate_normal(). It is not an R random number or an R callback.
  b_time_rnd <- b_time + b_time_s * random_variable("omega")

  # Construct the conditional logit kernel symbolically. The observed-choice
  # selector compiles to native models.logit(..., i=CHOICE).
  utilities <- list(
    `1` = asc_train + b_time_rnd * variable("TRAIN_TT_SCALED") +
      b_cost * variable("TRAIN_COST_SCALED"),
    `2` = asc_sm + b_time_rnd * variable("SM_TT_SCALED") +
      b_cost * variable("SM_COST_SCALED"),
    `3` = asc_car + b_time_rnd * 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")
  )
  conditional_probability <- logit_probability(
    utilities = utilities,
    availability = availability,
    alternative = variable("CHOICE")
  )
  log_probability <- log(integrate_normal(
    conditional_probability,
    name = "omega",
    number_of_quadrature_points = number_of_quadrature_points
  ))

  biogeme_model(
    database = database,
    formula = log_probability,
    control = biogeme_control(
    output_directory = prepared$output,
      model_name = "b05b_normal_mixture_integral",
      optimization_algorithm = "simple_bounds_BFGS",
      generate_html = TRUE,
      generate_yaml = FALSE,
      save_iterations = FALSE
    )
  )
}

# 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,
# --output, and --quadrature-points options work from any current working
# directory.
prepared <- prepare_swissmetro_example(
  commandArgs(trailingOnly = TRUE),
  default_model = "b05b_normal_mixture_integral"
)

number_of_quadrature_points <- if (
    !is.null(prepared$options$quadrature_points) &&
      nzchar(prepared$options$quadrature_points)
) {
  example_integer(prepared$options$quadrature_points, "quadrature-points")
} else {
  30L
}

# estimate() always performs fresh native estimation. Remove only exact b05b
# artifacts so a reused output directory cannot silently recycle old results.
stale_files <- c(
  "b05b_normal_mixture_integral.yaml",
  "__b05b_normal_mixture_integral.iter",
  "b05b_normal_mixture_integral.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_b05b_normal_mixture_integral_model(
  database,
  number_of_quadrature_points = number_of_quadrature_points
)

cat(sprintf("Number of quadrature points: %d\n", number_of_quadrature_points))

# The complete integration-aware expression graph is compiled once. Native
# Biogeme performs quadrature, differentiation, optimization, and reporting.
fit <- estimate(
  model,
  model_name = "b05b_normal_mixture_integral",
  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.