.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/indicators/plot_b09wtp.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_indicators_plot_b09wtp.py: 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 `_ :author: Michel Bierlaire, EPFL :date: Wed Apr 12 20:57:00 2023 .. GENERATED FROM PYTHON SOURCE LINES 16-37 .. code-block:: Python import sys import numpy as np import pandas as pd from IPython.core.display_functions import display try: import matplotlib.pyplot as plt can_plot = True except ModuleNotFoundError: can_plot = False import biogeme.biogeme as bio from biogeme.exceptions import BiogemeError import biogeme.results as res from biogeme.expressions import Derive from biogeme.data.optima import read_data, normalized_weight from scenarios import scenario .. GENERATED FROM PYTHON SOURCE LINES 38-40 Obtain the specification for the default scenario The definition of the scenarios is available in :ref:`scenarios`. .. GENERATED FROM PYTHON SOURCE LINES 40-45 .. code-block:: Python V, _, _, _ = scenario() V_PT = V[0] V_CAR = V[1] .. GENERATED FROM PYTHON SOURCE LINES 46-47 Calculation of the willingness to pay using derivatives. .. GENERATED FROM PYTHON SOURCE LINES 47-50 .. code-block:: Python WTP_PT_TIME = Derive(V_PT, 'TimePT') / Derive(V_PT, 'MarginalCostPT') WTP_CAR_TIME = Derive(V_CAR, 'TimeCar') / Derive(V_CAR, 'CostCarCHF') .. GENERATED FROM PYTHON SOURCE LINES 51-52 Formulas to simulate. .. GENERATED FROM PYTHON SOURCE LINES 52-58 .. code-block:: Python simulate = { 'weight': normalized_weight, 'WTP PT time': WTP_PT_TIME, 'WTP CAR time': WTP_CAR_TIME, } .. GENERATED FROM PYTHON SOURCE LINES 59-60 Read the data .. GENERATED FROM PYTHON SOURCE LINES 60-62 .. code-block:: Python database = read_data() .. GENERATED FROM PYTHON SOURCE LINES 63-64 Create the Biogeme object. .. GENERATED FROM PYTHON SOURCE LINES 64-66 .. code-block:: Python the_biogeme = bio.BIOGEME(database, simulate) .. GENERATED FROM PYTHON SOURCE LINES 67-68 Read the estimation results from the file. .. GENERATED FROM PYTHON SOURCE LINES 68-76 .. code-block:: Python try: results = res.bioResults(pickle_file='saved_results/b02estimation.pickle') except BiogemeError: sys.exit( 'Run first the script b02estimation.py in order to generate ' 'the file b02estimation.pickle.' ) .. GENERATED FROM PYTHON SOURCE LINES 77-79 `simulated_values` is a Pandas dataframe with the same number of rows as the database, and as many columns as formulas to simulate. .. GENERATED FROM PYTHON SOURCE LINES 79-82 .. code-block:: Python simulated_values = the_biogeme.simulate(results.get_beta_values()) display(simulated_values) .. rst-class:: sphx-glr-script-out .. code-block:: none weight WTP PT time WTP CAR time 0 0.886023 0.026513 0.026513 2 0.861136 0.026513 0.026513 3 0.861136 0.026513 0.026513 4 0.957386 0.086226 0.086226 5 0.861136 0.026513 0.026513 ... ... ... ... 2259 2.036009 0.026513 0.026513 2261 0.861136 0.086226 0.086226 2262 0.861136 0.086226 0.086226 2263 0.957386 0.026513 0.026513 2264 0.957386 0.026513 0.026513 [1906 rows x 3 columns] .. GENERATED FROM PYTHON SOURCE LINES 83-84 Note the multiplication by 60 to have the valus of time per hour and not per minute. .. GENERATED FROM PYTHON SOURCE LINES 84-86 .. code-block:: Python wtpcar = (60 * simulated_values['WTP CAR time'] * simulated_values['weight']).mean() .. GENERATED FROM PYTHON SOURCE LINES 87-88 Calculate confidence intervals .. GENERATED FROM PYTHON SOURCE LINES 88-90 .. code-block:: Python b = results.get_betas_for_sensitivity_analysis(the_biogeme.free_beta_names) .. GENERATED FROM PYTHON SOURCE LINES 91-93 Returns data frame containing, for each simulated value, the left and right bounds of the confidence interval calculated by simulation. .. GENERATED FROM PYTHON SOURCE LINES 93-95 .. code-block:: Python left, right = the_biogeme.confidence_intervals(b, 0.9) .. GENERATED FROM PYTHON SOURCE LINES 96-97 Lower bounds of the confidence intervals .. GENERATED FROM PYTHON SOURCE LINES 97-98 .. code-block:: Python display(left) .. rst-class:: sphx-glr-script-out .. code-block:: none weight WTP PT time WTP CAR time 0 0.886023 0.009167 0.009167 2 0.861136 0.009167 0.009167 3 0.861136 0.009167 0.009167 4 0.957386 0.071430 0.071430 5 0.861136 0.009167 0.009167 ... ... ... ... 2259 2.036009 0.009167 0.009167 2261 0.861136 0.071430 0.071430 2262 0.861136 0.071430 0.071430 2263 0.957386 0.009167 0.009167 2264 0.957386 0.009167 0.009167 [1906 rows x 3 columns] .. GENERATED FROM PYTHON SOURCE LINES 99-100 Upper bounds of the confidence intervals .. GENERATED FROM PYTHON SOURCE LINES 100-102 .. code-block:: Python display(right) .. rst-class:: sphx-glr-script-out .. code-block:: none weight WTP PT time WTP CAR time 0 0.886023 0.066435 0.066435 2 0.861136 0.066435 0.066435 3 0.861136 0.066435 0.066435 4 0.957386 0.146445 0.146445 5 0.861136 0.066435 0.066435 ... ... ... ... 2259 2.036009 0.066435 0.066435 2261 0.861136 0.146445 0.146445 2262 0.861136 0.146445 0.146445 2263 0.957386 0.066435 0.066435 2264 0.957386 0.066435 0.066435 [1906 rows x 3 columns] .. GENERATED FROM PYTHON SOURCE LINES 103-104 Lower and upper bounds of the willingness to pay. .. GENERATED FROM PYTHON SOURCE LINES 104-110 .. code-block:: Python 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}]' ) .. rst-class:: sphx-glr-script-out .. code-block:: none Average WTP for car: 2.88 CI:[1.9, 5.72] .. GENERATED FROM PYTHON SOURCE LINES 111-113 In this specific case, there are only two distinct values in the population: for workers and non workers .. GENERATED FROM PYTHON SOURCE LINES 113-119 .. code-block:: Python print( 'Unique values: ', [f'{i:.3g}' for i in 60 * simulated_values['WTP CAR time'].unique()], ) .. rst-class:: sphx-glr-script-out .. code-block:: none Unique values: ['1.59', '5.17'] .. GENERATED FROM PYTHON SOURCE LINES 120-121 Function calculating the willingness to pay for a group. .. GENERATED FROM PYTHON SOURCE LINES 121-140 .. code-block:: Python 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 .. GENERATED FROM PYTHON SOURCE LINES 141-142 Full time workers. .. GENERATED FROM PYTHON SOURCE LINES 142-146 .. code-block:: Python aFilter = database.data['OccupStat'] == 1 w, l, r = wtp_for_subgroup(aFilter) print(f'WTP car for workers: {w:.3g} CI:[{l:.3g}, {r:.3g}]') .. rst-class:: sphx-glr-script-out .. code-block:: none WTP car for workers: 5.17 CI:[4.29, 8.79] .. GENERATED FROM PYTHON SOURCE LINES 147-148 Females. .. GENERATED FROM PYTHON SOURCE LINES 148-152 .. code-block:: Python aFilter = database.data['Gender'] == 2 w, l, r = wtp_for_subgroup(aFilter) print(f'WTP car for females: {w:.3g} CI:[{l:.3g}, {r:.3g}]') .. rst-class:: sphx-glr-script-out .. code-block:: none WTP car for females: 2.22 CI:[1.21, 4.83] .. GENERATED FROM PYTHON SOURCE LINES 153-154 Males. .. GENERATED FROM PYTHON SOURCE LINES 154-158 .. code-block:: Python aFilter = database.data['Gender'] == 1 w, l, r = wtp_for_subgroup(aFilter) print(f'WTP car for males : {w:.3g} CI:[{l:.3g}, {r:.3g}]') .. rst-class:: sphx-glr-script-out .. code-block:: none WTP car for males : 3.72 CI:[2.77, 6.84] .. GENERATED FROM PYTHON SOURCE LINES 159-161 We plot the distribution of WTP in the population. In this case, there are only two values .. GENERATED FROM PYTHON SOURCE LINES 161-169 .. code-block:: Python 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() .. image-sg:: /auto_examples/indicators/images/sphx_glr_plot_b09wtp_001.png :alt: plot b09wtp :srcset: /auto_examples/indicators/images/sphx_glr_plot_b09wtp_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 2.687 seconds) .. _sphx_glr_download_auto_examples_indicators_plot_b09wtp.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_b09wtp.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_b09wtp.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_b09wtp.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_