inst/examples/bayesian_swissmetro/plot_b23b_binary_probit.R

#!/usr/bin/env Rscript

# b23b. Bayesian binary probit model.
#
# The same Train-versus-Car sample as b23a is used. The two choice-specific
# probabilities are expressed with native NormalCdf and Elem nodes.

library(rbiogeme)

# prepare_swissmetro_example() is defined in ../swissmetro/example_utils.R.
# It parses --data, --python, and --output and configures the native bridge.
script_path <- commandArgs(trailingOnly = FALSE)
script_path <- sub("^--file=", "", script_path[startsWith(script_path, "--file=")][[1L]])
source(file.path(dirname(normalizePath(script_path)), "..", "swissmetro", "example_utils.R"))

build_b23b_binary_probit_model <- function(database) {
  binary_exclude <- variable("CHOICE") == 2 |
    variable("CAR_AV_SP") == 0 |
    variable("TRAIN_AV_SP") == 0
  database <- biogeme_database_remove(database, binary_exclude)

  # All five native parameters are free and retain their Python names.
  asc_car <- biogeme_beta("asc_car", start = 0)
  b_time_car <- biogeme_beta("b_time_car", start = 0)
  b_time_train <- biogeme_beta("b_time_train", start = 0)
  b_cost_car <- biogeme_beta("b_cost_car", start = 0)
  b_cost_train <- biogeme_beta("b_cost_train", start = 0)

  v_train <- b_time_train * variable("TRAIN_TT_SCALED") +
    b_cost_train * variable("TRAIN_COST_SCALED")
  v_car <- asc_car + b_time_car * variable("CAR_TT_SCALED") +
    b_cost_car * variable("CAR_CO_SCALED")

  # Elem selects the native log-probability expression using CHOICE. The
  # complete expression tree is compiled before Bayesian estimation starts.
  log_probability <- Elem(
    list(
      `1` = log(normal_cdf(v_train - v_car)),
      `3` = log(normal_cdf(v_car - v_train))
    ),
    variable("CHOICE")
  )

  biogeme_model(
    database = database,
    formula = log_probability,
    control = biogeme_control(
    output_directory = prepared$output,
      model_name = "b23b_binary_probit",
      generate_html = TRUE,
      generate_yaml = TRUE,
      generate_netcdf = TRUE
    )
  )
}

prepared <- prepare_swissmetro_example(
  commandArgs(trailingOnly = TRUE),
  default_model = "b23b_binary_probit"
)
unlink(file.path(prepared$output, c(
  "b23b_binary_probit.yaml",
  "b23b_binary_probit.nc",
  "b23b_binary_probit.html",
  "__b23b_binary_probit.iter"
)), force = TRUE)

database <- swissmetro_data(prepared$data)
model <- build_b23b_binary_probit_model(database)
fit <- bayesian_estimate(
  model,
  model_name = "b23b_binary_probit",
  control = model$control
)

print(summary(fit))
print(coef(fit))
print(bayesian_stored_variables(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.