Calculation of willingness to pay

We calculate and plot willingness to pay. Details about this example are available in Section 4 of Bierlaire (2018) Calculating indicators with PandasBiogeme

Michel Bierlaire, EPFL Sat Jun 28 2025, 21:00:12

import sys

import numpy as np
import pandas as pd
from IPython.core.display_functions import display
from biogeme.biogeme import BIOGEME
from biogeme.results_processing import EstimationResults

try:
    import matplotlib.pyplot as plt

    can_plot = True
except ModuleNotFoundError:
    can_plot = False
from biogeme.expressions import Derive
from biogeme.data.optima import read_data, normalized_weight
from scenarios import scenario

Obtain the specification for the default scenario The definition of the scenarios is available in scenarios.py.

v, _, _, _ = scenario()

v_pt = v[0]
v_car = v[1]

Calculation of the willingness to pay using derivatives.

wtp_pt_time = Derive(v_pt, 'TimePT') / Derive(v_pt, 'MarginalCostPT')
wtp_car_time = Derive(v_car, 'TimeCar') / Derive(v_car, 'CostCarCHF')

Formulas to simulate.

simulate = {
    'weight': normalized_weight,
    'WTP PT time': wtp_pt_time,
    'WTP CAR time': wtp_car_time,
}

Read the data

database = read_data()

Create the Biogeme object.

the_biogeme = BIOGEME(database, simulate)

Read the estimation results from the file.

try:
    results = EstimationResults.from_yaml_file(
        filename='saved_results/b02estimation.yaml'
    )
except FileNotFoundError:
    sys.exit(
        'Run first the script b02estimation.py in order to generate '
        'the file b02estimation.yaml.'
    )

simulated_values is a Pandas dataframe with the same number of rows as the database, and as many columns as formulas to simulate.

simulated_values = the_biogeme.simulate(results.get_beta_values())
display(simulated_values)
        weight  WTP PT time  WTP CAR time
0     0.893779     0.038431      0.038431
1     0.868674     0.038431      0.038431
2     0.868674     0.038431      0.038431
3     0.965766     0.111010      0.111010
4     0.868674     0.038431      0.038431
...        ...          ...           ...
1894  2.053830     0.038431      0.038431
1895  0.868674     0.111010      0.111010
1896  0.868674     0.111010      0.111010
1897  0.965766     0.038431      0.038431
1898  0.965766     0.038431      0.038431

[1899 rows x 3 columns]

Note the multiplication by 60 to have the valus of time per hour and not per minute.

wtpcar = (60 * simulated_values['WTP CAR time'] * simulated_values['weight']).mean()

Calculate confidence intervals

b = results.get_betas_for_sensitivity_analysis()

Returns data frame containing, for each simulated value, the left and right bounds of the confidence interval calculated by simulation.

left, right = the_biogeme.confidence_intervals(b, 0.9)
  0%|          | 0/100 [00:00<?, ?it/s]
100%|██████████| 100/100 [00:00<00:00, 2065.22it/s]

Lower bounds of the confidence intervals

display(left)
        weight  WTP PT time  WTP CAR time
0     0.893779     0.008235      0.008235
1     0.868674     0.008235      0.008235
2     0.868674     0.008235      0.008235
3     0.965766     0.065411      0.065411
4     0.868674     0.008235      0.008235
...        ...          ...           ...
1894  2.053830     0.008235      0.008235
1895  0.868674     0.065411      0.065411
1896  0.868674     0.065411      0.065411
1897  0.965766     0.008235      0.008235
1898  0.965766     0.008235      0.008235

[1899 rows x 3 columns]

Upper bounds of the confidence intervals

display(right)
        weight  WTP PT time  WTP CAR time
0     0.893779     0.081041      0.081041
1     0.868674     0.081041      0.081041
2     0.868674     0.081041      0.081041
3     0.965766     0.165686      0.165686
4     0.868674     0.081041      0.081041
...        ...          ...           ...
1894  2.053830     0.081041      0.081041
1895  0.868674     0.165686      0.165686
1896  0.868674     0.165686      0.165686
1897  0.965766     0.081041      0.081041
1898  0.965766     0.081041      0.081041

[1899 rows x 3 columns]

Lower and upper bounds of the willingness to pay.

wtpcar_left = (60 * left['WTP CAR time'] * left['weight']).mean()
wtpcar_right = (60 * right['WTP CAR time'] * right['weight']).mean()
print(
    f'Average WTP for car: {wtpcar:.3g} ' f'CI:[{wtpcar_left:.3g}, {wtpcar_right:.3g}]'
)
Average WTP for car: 3.89 CI:[1.74, 6.71]

In this specific case, there are only two distinct values in the population: for workers and non workers

print(
    'Unique values:      ',
    [f'{i:.3g}' for i in 60 * simulated_values['WTP CAR time'].unique()],
)
Unique values:       ['2.31', '6.66']

Function calculating the willingness to pay for a group.

def wtp_for_subgroup(the_filter: 'pd.Series[np.bool_]') -> tuple[float, float, float]:
    """
    Check the value for groups of the population. Define a function that
    works for any filter to avoid repeating code.

    :param the_filter: pandas filter

    :return: willingness-to-pay for car and confidence interval
    """
    size = the_filter.sum()
    sim = simulated_values[the_filter]
    total_weight = sim['weight'].sum()
    weight = sim['weight'] * size / total_weight
    _wtpcar = (60 * sim['WTP CAR time'] * weight).mean()
    _wtpcar_left = (60 * left[the_filter]['WTP CAR time'] * weight).mean()
    _wtpcar_right = (60 * right[the_filter]['WTP CAR time'] * weight).mean()
    return _wtpcar, _wtpcar_left, _wtpcar_right

Full time workers.

a_filter = database.dataframe['OccupStat'] == 1
w, l, r = wtp_for_subgroup(a_filter)
print(f'WTP car for workers: {w:.3g} CI:[{l:.3g}, {r:.3g}]')
WTP car for workers: 6.66 CI:[3.92, 9.94]

Females.

a_filter = database.dataframe['Gender'] == 2
w, l, r = wtp_for_subgroup(a_filter)
print(f'WTP car for females: {w:.3g} CI:[{l:.3g}, {r:.3g}]')
WTP car for females: 3.09 CI:[1.11, 5.78]

Males.

a_filter = database.dataframe['Gender'] == 1
w, l, r = wtp_for_subgroup(a_filter)
print(f'WTP car for males  : {w:.3g} CI:[{l:.3g}, {r:.3g}]')
WTP car for males  : 4.89 CI:[2.53, 7.88]

We plot the distribution of WTP in the population. In this case, there are only two values

if can_plot:
    plt.hist(
        60 * simulated_values['WTP CAR time'],
        weights=simulated_values['weight'],
    )
    plt.xlabel('WTP (CHF/hour)')
    plt.ylabel('Individuals')
    plt.show()
plot b09wtp

Total running time of the script: (0 minutes 1.303 seconds)

Gallery generated by Sphinx-Gallery