Database

The database management module.

biogeme.database module

Implementation of the class Database, wrapping a pandas dataframe for specific services to Biogeme

author:

Michel Bierlaire

date:

Tue Mar 26 16:42:54 2019

class biogeme.database.Database(name, pandasDatabase)[source]

Bases: object

Class that contains and prepare the database.

DefineVariable(name, expression)[source]

Insert a new column in the database and define it as a variable.

MLHS_anti(number_of_draws)[source]
__init__(name, pandasDatabase)[source]

Constructor

Parameters:
  • name (string) – name of the database.

  • pandasDatabase (pandas.DataFrame) – data stored in a pandas data frame.

Raises:
addColumn(expression, column)[source]

Add a new column in the database, calculated from an expression.

Parameters:
  • expression (biogeme.expressions.Expression) – expression to evaluate

  • column (string) – name of the column to add

Returns:

the added column

Return type:

numpy.Series

Raises:
  • ValueError – if the column name already exists.

  • BiogemeError – if the database is empty.

buildPanelMap()[source]

Sorts the data so that the observations for each individuals are contiguous, and builds a map that identifies the range of indices of the observations of each individuals.

checkAvailabilityOfChosenAlt(avail, choice)[source]

Check if the chosen alternative is available for each entry in the database.

Parameters:
  • avail (list of biogeme.expressions.Expression) – list of expressions to evaluate the availability conditions for each alternative.

  • choice (biogeme.expressions.Expression) – expression for the chosen alternative.

Returns:

numpy series of bool, long as the number of entries in the database, containing True is the chosen alternative is available, False otherwise.

Return type:

numpy.Series

Raises:
  • BiogemeError – if the chosen alternative does not appear in the availability dict

  • BiogemeError – if the database is empty.

check_segmentation(segmentation_tuple)[source]

Check that the segmentation covers the complete database

Parameters:

segmentation_tuple (DiscreteSegmentationTuple) – object describing the segmentation

Returns:

number of observations per segment.

Return type:

dict(str: int)

choiceAvailabilityStatistics(avail, choice)[source]

Calculates the number of time an alternative is chosen and available

Parameters:
  • avail (list of biogeme.expressions.Expression) – list of expressions to evaluate the availability conditions for each alternative.

  • choice (biogeme.expressions.Expression) – expression for the chosen alternative.

Returns:

for each alternative, a tuple containing the number of time it is chosen, and the number of time it is available.

Return type:

dict(int: (int, int))

Raises:

BiogemeError – if the database is empty.

count(columnName, value)[source]

Counts the number of observations that have a specific value in a given column.

Parameters:
  • columnName (string) – name of the column.

  • value (float) – value that is seeked.

Returns:

Number of times that the value appears in the column.

Return type:

int

data

Pandas data frame containing the data.

descriptionOfNativeDraws()[source]

Describe the draws available draws with Biogeme

Returns:

dict, where the keys are the names of the draws, and the value their description

Example of output:

{'UNIFORM: Uniform U[0, 1]',
 'UNIFORM_ANTI: Antithetic uniform U[0, 1]'],
 'NORMAL: Normal N(0, 1) draws'}
Return type:

dict

dumpOnFile()[source]

Dumps the database in a CSV formatted file.

Returns:

name of the file

Return type:

string

excludedData

Number of observations removed by the function biogeme.Database.remove()

fullData

Pandas data frame containing the full data. Useful when batches of the sample are used for approximating the log likelihood.

fullIndividualMap

complete map identifying the range of observations for each individual in a panel data context. None if data is not panel. Useful when batches of the sample are used to approximate the log likelihood function.

generateDraws(types, names, number_of_draws)[source]

Generate draws for each variable.

Parameters:
  • types (dict) –

    A dict indexed by the names of the variables, describing the types of draws. Each of them can be a native type or any type defined by the function setRandomNumberGenerators().

    Native types:

    • 'UNIFORM': Uniform U[0, 1],

    • 'UNIFORM_ANTI: Antithetic uniform U[0, 1]’,

    • 'UNIFORM_HALTON2': Halton draws with base 2, skipping the first 10,

    • 'UNIFORM_HALTON3': Halton draws with base 3, skipping the first 10,

    • 'UNIFORM_HALTON5': Halton draws with base 5, skipping the first 10,

    • 'UNIFORM_MLHS': Modified Latin Hypercube Sampling on [0, 1],

    • 'UNIFORM_MLHS_ANTI': Antithetic Modified Latin Hypercube Sampling on [0, 1],

    • 'UNIFORMSYM': Uniform U[-1, 1],

    • 'UNIFORMSYM_ANTI': Antithetic uniform U[-1, 1],

    • 'UNIFORMSYM_HALTON2': Halton draws on [-1, 1] with base 2, skipping the first 10,

    • 'UNIFORMSYM_HALTON3': Halton draws on [-1, 1] with base 3, skipping the first 10,

    • 'UNIFORMSYM_HALTON5': Halton draws on [-1, 1] with base 5, skipping the first 10,

    • 'UNIFORMSYM_MLHS': Modified Latin Hypercube Sampling on [-1, 1],

    • 'UNIFORMSYM_MLHS_ANTI': Antithetic Modified Latin Hypercube Sampling on [-1, 1],

    • 'NORMAL': Normal N(0, 1) draws,

    • 'NORMAL_ANTI': Antithetic normal draws,

    • 'NORMAL_HALTON2': Normal draws from Halton base 2 sequence,

    • 'NORMAL_HALTON3': Normal draws from Halton base 3 sequence,

    • 'NORMAL_HALTON5': Normal draws from Halton base 5 sequence,

    • 'NORMAL_MLHS': Normal draws from Modified Latin Hypercube Sampling,

    • 'NORMAL_MLHS_ANTI': Antithetic normal draws from Modified Latin Hypercube Sampling]

    For an updated description of the native types, call the function descriptionOfNativeDraws().

  • names (list of strings) – the list of names of the variables that require draws to be generated.

  • number_of_draws (int) – number of draws to generate.

Returns:

a 3-dimensional table with draws. The 3 dimensions are

  1. number of individuals

  2. number of draws

  3. number of variables

Return type:

numpy.array

Example:

types = {'randomDraws1': 'NORMAL_MLHS_ANTI',
         'randomDraws2': 'UNIFORM_MLHS_ANTI',
         'randomDraws3': 'UNIFORMSYM_MLHS_ANTI'}
theDrawsTable = myData.generateDraws(types,
    ['randomDraws1', 'randomDraws2', 'randomDraws3'], 10)
Raises:
  • BiogemeError – if a type of draw is unknown.

  • BiogemeError – if the output of the draw generator does not have the requested dimensions.

generateFlatPanelDataframe(saveOnFile=None, identical_columns=())[source]

Generate a flat version of the panel data

Parameters:
  • saveOnFile (bool) – if True, the flat database is saved on file.

  • identical_columns (tuple(str)) – tuple of columns that contain the same values for all observations of the same individual. Default: empty list.

Returns:

the flatten database, in Pandas format

Return type:

pandas.DataFrame

Raises:

BiogemeError – if the database in not panel

generate_segmentation(variable, mapping=None, reference=None)[source]

Generate a segmentation tuple for a variable.

Parameters:
  • variable (biogeme.expressions.Variable or string) – Variable object or name of the variable

  • mapping (dict(int: str)) – mapping associating values of the variable to names. If incomplete, default names are provided.

  • reference (str) – name of the reference category. If None, an arbitrary category is selected as reference. :type:

getNumberOfObservations()[source]

Reports the number of observations in the database.

Note that it returns the same value, irrespectively if the database contains panel data or not.

Returns:

Number of observations.

Return type:

int

See also: getSampleSize()

getSampleSize()[source]

Reports the size of the sample.

If the data is cross-sectional, it is the number of observations in the database. If the data is panel, it is the number of individuals.

Returns:

Sample size.

Return type:

int

See also: getNumberOfObservations()

halton2(number_of_draws)[source]
halton3(number_of_draws)[source]
halton5(number_of_draws)[source]
individualMap

map identifying the range of observations for each individual in a panel data context. None if data is not panel.

isPanel()[source]

Tells if the data is panel or not.

Returns:

True if the data is panel.

Return type:

bool

mdcev_count(list_of_columns, new_column)[source]
For the MDCEV models, we calculate the number of

alternatives that are chosen, that is the number of columns with a non zero entry.

Parameters:
  • list_of_columns (list[str]) – list of columns containing the quantity of each good.

  • new_column (str) – name of the new column where the result is stored

Return type:

None

name

Name of the database. Used mainly for the file name when dumping data.

nativeRandomNumberGenerators = {'NORMAL': (<function getNormalWichuraDraws>, 'Normal N(0, 1) draws'), 'NORMAL_ANTI': (<function Database.normal_antithetic>, 'Antithetic normal draws'), 'NORMAL_HALTON2': (<function Database.normal_halton2>, 'Normal draws from Halton base 2 sequence'), 'NORMAL_HALTON3': (<function Database.normal_halton3>, 'Normal draws from Halton base 3 sequence'), 'NORMAL_HALTON5': (<function Database.normal_halton5>, 'Normal draws from Halton base 5 sequence'), 'NORMAL_MLHS': (<function Database.normal_MLHS>, 'Normal draws from Modified Latin Hypercube Sampling'), 'NORMAL_MLHS_ANTI': (<function Database.normal_MLHS_anti>, 'Antithetic normal draws from Modified Latin Hypercube Sampling'), 'UNIFORM': (<function getUniform>, 'Uniform U[0, 1]'), 'UNIFORMSYM': (<function Database.symm_uniform>, 'Uniform U[-1, 1]'), 'UNIFORMSYM_ANTI': (<function Database.symm_uniform_antithetic>, 'Antithetic uniform U[-1, 1]'), 'UNIFORMSYM_HALTON2': (<function Database.symm_halton2>, 'Halton draws on [-1, 1] with base 2, skipping the first 10'), 'UNIFORMSYM_HALTON3': (<function Database.symm_halton3>, 'Halton draws on [-1, 1] with base 3, skipping the first 10'), 'UNIFORMSYM_HALTON5': (<function Database.symm_halton5>, 'Halton draws on [-1, 1] with base 5, skipping the first 10'), 'UNIFORMSYM_MLHS': (<function Database.symm_MLHS>, 'Modified Latin Hypercube Sampling on [-1, 1]'), 'UNIFORMSYM_MLHS_ANTI': (<function Database.symm_MLHS_anti>, 'Antithetic Modified Latin Hypercube Sampling on [-1, 1]'), 'UNIFORM_ANTI': (<function Database.uniform_antithetic>, 'Antithetic uniform U[0, 1]'), 'UNIFORM_HALTON2': (<function Database.halton2>, 'Halton draws with base 2, skipping the first 10'), 'UNIFORM_HALTON3': (<function Database.halton3>, 'Halton draws with base 3, skipping the first 10'), 'UNIFORM_HALTON5': (<function Database.halton5>, 'Halton draws with base 5, skipping the first 10'), 'UNIFORM_MLHS': (<function getLatinHypercubeDraws>, 'Modified Latin Hypercube Sampling on [0, 1]'), 'UNIFORM_MLHS_ANTI': (<function Database.MLHS_anti>, 'Antithetic Modified Latin Hypercube Sampling on [0, 1]')}
normal_MLHS(number_of_draws)[source]
normal_MLHS_anti(number_of_draws)[source]
normal_antithetic(number_of_draws)[source]
normal_halton2(number_of_draws)[source]
normal_halton3(number_of_draws)[source]
normal_halton5(number_of_draws)[source]
number_of_draws

Number of draws generated by the function Database.generateDraws. Value 0 if this function is not called.

panel(columnName)[source]

Defines the data as panel data

Parameters:

columnName (string) – name of the columns that identifies individuals.

Raises:

BiogemeError – if the data are not sorted properly, that is if the data for the one individuals are not consecutive.

panelColumn

Name of the column identifying the individuals in a panel data context. None if data is not panel.

remove(expression)[source]

Removes from the database all entries such that the value of the expression is not 0.

Parameters:

expression (biogeme.expressions.Expression) – expression to evaluate

sampleIndividualMapWithReplacement(size=None)[source]

Extract a random sample of the individual map from a panel data database, with replacement.

Useful for bootstrapping.

Parameters:

size (int) – size of the sample. If None, a sample of the same size as the database will be generated. Default: None.

Returns:

pandas dataframe with the sample.

Return type:

pandas.DataFrame

Raises:

BiogemeError – if the database in not in panel mode.

sampleWithReplacement(size=None)[source]

Extract a random sample from the database, with replacement.

Useful for bootstrapping.

Parameters:

size (int) – size of the sample. If None, a sample of the same size as the database will be generated. Default: None.

Returns:

pandas dataframe with the sample.

Return type:

pandas.DataFrame

scaleColumn(column, scale)[source]

Multiply an entire column by a scale value

Parameters:
  • column (string) – name of the column

  • scale (float) – value of the scale. All values of the column will be multiplied by that scale.

setRandomNumberGenerators(rng)[source]

Defines user-defined random numbers generators.

Parameters:

rng (dict) – a dictionary of generators. The keys of the dictionary characterize the name of the generators, and must be different from the pre-defined generators in Biogeme (see generateDraws() for the list). The elements of the dictionary are functions that take two arguments: the number of series to generate (typically, the size of the database), and the number of draws per series.

Example:

def logNormalDraws(sample_size, number_of_draws):
    return np.exp(np.random.randn(sample_size, number_of_draws))

def exponentialDraws(sample_size, number_of_draws):
    return -1.0 * np.log(np.random.rand(sample_size, number_of_draws))

# We associate these functions with a name
dict = {'LOGNORMAL':(logNormalDraws,
                     'Draws from lognormal distribution'),
        'EXP':(exponentialDraws,
               'Draws from exponential distributions')}
myData.setRandomNumberGenerators(dict)
Raises:

ValueError – if a reserved keyword is used for a user-defined draws.

split(slices, groups=None)[source]

Prepare estimation and validation sets for validation.

Parameters:
  • slices (int) – number of slices

  • groups (str) – name of the column that defines the ID of the groups. Data belonging to the same groups will be maintained together.

Returns:

list of estimation and validation data sets

Return type:

list(tuple(pandas.DataFrame, pandas.DataFrame))

Raises:

BiogemeError – if the number of slices is less than two

suggestScaling(columns=None, reportAll=False)[source]

Suggest a scaling of the variables in the database.

For each column, \(\delta\) is the difference between the largest and the smallest value, or one if the difference is smaller than one. The level of magnitude is evaluated as a power of 10. The suggested scale is the inverse of this value.

\[s = \frac{1}{10^{|\log_{10} \delta|}}\]

where \(|x|\) is the integer closest to \(x\).

Parameters:
  • columns (list(str)) – list of columns to be considered. If None, all of them will be considered.

  • reportAll (bool) – if False, remove entries where the suggested scale is 1, 0.1 or 10

Returns:

A Pandas dataframe where each row contains the name of the variable and the suggested scale s. Ideally, the column should be multiplied by s.

Return type:

pandas.DataFrame

Raises:

BiogemeError – if a variable in columns is unknown.

symm_MLHS(number_of_draws)[source]
symm_MLHS_anti(number_of_draws)[source]
symm_halton2(number_of_draws)[source]
symm_halton3(number_of_draws)[source]
symm_halton5(number_of_draws)[source]
symm_uniform(number_of_draws)[source]
symm_uniform_antithetic(number_of_draws)[source]
theDraws

Draws for Monte-Carlo integration

typesOfDraws

Types of draws for Monte Carlo integration

uniform_antithetic(number_of_draws)[source]
userRandomNumberGenerators

Dictionary containing user defined random number generators. Defined by the function Database.setRandomNumberGenerators that checks that reserved keywords are not used. The element of the dictionary is a tuple with two elements: (0) the function generating the draws, and (1) a string describing the type of draws

valuesFromDatabase(expression)[source]

Evaluates an expression for each entry of the database.

Parameters:

expression (biogeme.expressions.Expression.) – expression to evaluate

Returns:

numpy series, long as the number of entries in the database, containing the calculated quantities.

Return type:

numpy.Series

Raises:

BiogemeError – if the database is empty.

variables

names of the headers of the database so that they can be used as an object of type biogeme.expressions.Expression. Initialized by _generateHeaders()

verify_segmentation(segmentation)[source]

Verifies if the definition of the segmentation is consistent with the data

Parameters:

segmentation (DiscreteSegmentationTuple) – definition of the segmentation

Raises:

BiogemeError – if the segmentation is not consistent with the data.

class biogeme.database.EstimationValidation(estimation, validation)[source]

Bases: NamedTuple

Parameters:
  • estimation (DataFrame) –

  • validation (DataFrame) –

estimation: DataFrame

Alias for field number 0

validation: DataFrame

Alias for field number 1

biogeme.database.logger = <Logger biogeme.database (WARNING)>

Logger that controls the output of messages to the screen and log file.