""".. _plot_b28_parameter_overrides:

28. Explicit parameter overrides in a simple model
===================================================

This example illustrates the preprocessing API used to control parameters in
an expression.  The override is applied before the expression is passed to
``BIOGEME``; estimation itself is unchanged.

Two types of control are shown:

* ``b_cost`` is replaced by a fixed ``Beta`` with a user-supplied initial
  value and bounds;
* ``asc_train`` is replaced by ``Numeric(0)``, so it is no longer an estimated
  parameter.

The same mechanism can later be used with parameters generated by catalogs,
assisted specification, or latent-variable builders.

Michel Bierlaire, EPFL
"""

from swissmetro_data import (
    CAR_AV_SP,
    CAR_CO_SCALED,
    CAR_TT_SCALED,
    CHOICE,
    SM_AV,
    SM_COST_SCALED,
    SM_TT_SCALED,
    TRAIN_AV_SP,
    TRAIN_COST_SCALED,
    TRAIN_TT_SCALED,
    database,
)

import biogeme.biogeme_logging as blog
from biogeme.biogeme import BIOGEME
from biogeme.expressions import (
    Beta,
    Numeric,
    ParameterOverrides,
    apply_parameter_overrides,
)
from biogeme.models import loglogit

logger = blog.get_screen_logger(level=blog.INFO)
logger.info('Example plot_b28_parameter_overrides.py')

# %%
# Define the ordinary multinomial-logit specification.
asc_car = Beta('asc_car', 0, None, None, 0)
asc_train = Beta('asc_train', 0, None, None, 0)
b_time = Beta('b_time', 0, None, None, 0)
b_cost = Beta('b_cost', 0, None, None, 0)

v_train = asc_train + b_time * TRAIN_TT_SCALED + b_cost * TRAIN_COST_SCALED
v_swissmetro = b_time * SM_TT_SCALED + b_cost * SM_COST_SCALED
v_car = asc_car + b_time * CAR_TT_SCALED + b_cost * CAR_CO_SCALED

utilities = {1: v_train, 2: v_swissmetro, 3: v_car}
availability = {1: TRAIN_AV_SP, 2: SM_AV, 3: CAR_AV_SP}
log_probability = loglogit(utilities, availability, CHOICE)

# %%
# Explicitly control parameters before creating the BIOGEME object.  The key
# is the original Beta name.  A replacement can be a full Beta definition or
# any other valid Biogeme expression.
overrides = ParameterOverrides()
overrides.set('b_cost', Beta('b_cost', -1.0, -10.0, 0.0, 1))
overrides.set('asc_train', Numeric(0))

log_probability = apply_parameter_overrides(log_probability, overrides)

# %%
# Estimate the resulting model.
biogeme = BIOGEME(database, log_probability)
biogeme.model_name = 'b28_parameter_overrides'
results = biogeme.estimate()

print(results.short_summary())
print(results.get_beta_values())
