inst/examples/bayesian_swissmetro/plot_b18b_ordinal_probit.R

#!/usr/bin/env Rscript

# b18b. Bayesian ordinal probit model.
#
# As in b18a, the example treats Swissmetro choice codes 1 -> 2 -> 3 as an
# ordered response solely to illustrate the native ordinal-model syntax.

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_b18b_ordinal_probit_model <- function(database) {
  positive_lower_bound <- 1e-5
  b_time <- biogeme_beta("b_time", start = 0)
  b_cost <- biogeme_beta("b_cost", start = 0)
  tau1 <- biogeme_beta("tau1", start = -1, upper = 0)
  delta2 <- biogeme_beta("delta2", start = 2, lower = positive_lower_bound)
  tau2 <- tau1 + delta2
  utility <- b_time * variable("TRAIN_TT_SCALED") +
    b_cost * variable("TRAIN_COST_SCALED")

  # ordered_probit_log_probability() delegates the normal CDF and ordinal
  # probabilities to native Biogeme's OrderedLogProbit expression.
  biogeme_model(
    database = database,
    formula = ordered_probit_log_probability(
      eta = utility,
      cutpoints = list(tau1, tau2),
      alternative = variable("CHOICE"),
      categories = c(1, 2, 3),
      neutral_labels = numeric()
    ),
    control = biogeme_control(
    output_directory = prepared$output,
      model_name = "b18b_ordinal_probit",
      generate_html = TRUE,
      generate_yaml = TRUE,
      generate_netcdf = TRUE
    )
  )
}

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

database <- swissmetro_data(prepared$data)
model <- build_b18b_ordinal_probit_model(database)
fit <- bayesian_estimate(
  model,
  model_name = "b18b_ordinal_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.