inst/examples/bayesian_swissmetro/plot_b01a_logit.R

#!/usr/bin/env Rscript

# b01a. Bayesian estimation of a Swissmetro multinomial logit model.
#
# This file deliberately contains the complete model specification.  The
# expressions below are symbolic: rbiogeme compiles the finished expression
# tree once, and native Python Biogeme performs the Bayesian estimation.

library(rbiogeme)

# prepare_swissmetro_example() is defined in the shared Swissmetro example
# helper.  It reads --data, --python, and --output options, configures the
# Python bridge, and makes the example runnable from any 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)), "..", "swissmetro", "example_utils.R"))

build_model <- function(database) {
  # biogeme_beta() creates a symbolic native Biogeme parameter.  The
  # Swissmetro ASC is fixed at zero for identification.
  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, upper = 0)
  b_cost <- biogeme_beta("b_cost", start = 0, upper = 0)

  # R arithmetic is overloaded for Biogeme expressions; these are utilities,
  # not locally evaluated R vectors.
  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")
  )
  logit_model(
    database = database,
    choice = "CHOICE",
    utilities = utilities,
    availability = list(
      `1` = variable("TRAIN_AV_SP"),
      `2` = variable("SM_AV"),
      `3` = variable("CAR_AV_SP")
    )
  )
}

prepared <- prepare_swissmetro_example(
  commandArgs(trailingOnly = TRUE),
  default_model = "b01a_logit"
)
database <- swissmetro_data(prepared$data)

# Bayesian estimation always starts a native run here.  Removing only the
# named outputs makes the example independent of stale YAML/NetCDF files.
unlink(file.path(prepared$output, c("b01a_logit.yaml", "b01a_logit.nc", "b01a_logit.html")))
model <- build_model(database)
fit <- bayesian_estimate(
  model,
  model_name = "b01a_logit",
  control = biogeme_control(
    output_directory = prepared$output,
    generate_yaml = TRUE,
    generate_html = TRUE,
    generate_netcdf = TRUE
  )
)

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.