Source code for biogeme.segmentation.segmentation_context
"""Class representing the characterization of a discrete segmentation.A discrete segmentation divides a population based on the values of a socio-economicvariable, mapping each value to a category name. A reference category is definedfor comparison in model estimation.Michel BierlaireThu Apr 3 10:08:10 2025"""from__future__importannotationsfromtypingimportTYPE_CHECKINGfrombiogeme.exceptionsimportBiogemeErrorifTYPE_CHECKING:frombiogeme.expressionsimportVariable
[docs]classDiscreteSegmentationTuple:"""Characterization of a discrete segmentation. This class is used to define how a discrete socio-economic variable is mapped to category names for segmentation purposes. One category is selected as the reference for use in estimation. """def__init__(self,variable:Variable|str,mapping:dict[int,str],reference:str|None=None,):"""Initialize a discrete segmentation characterization. :param variable: Socio-economic variable used for segmentation, either as a Variable instance or a string name. :param mapping: Dictionary mapping integer values of the variable to category names. :param reference: Optional name of the reference category. If not provided, the first category in the mapping is used. :raises BiogemeError: If the provided reference category is not found in the mapping. """frombiogeme.expressionsimportVariableself.variable:Variable=(variableifisinstance(variable,Variable)elseVariable(variable))self.mapping:dict[int,str]=mappingifreferenceisNone:self.reference:str=next(iter(mapping.values()))elifreferencenotinmapping.values():error_msg=(f'Reference category {reference} does not appear in the list 'f'of categories: {mapping.values()}')raiseBiogemeError(error_msg)else:self.reference:str=referenceifself.referenceisNone:raiseBiogemeError('Reference should not be None')def__repr__(self)->str:result=f'{self.variable.name}: [{self.mapping}] ref: {self.reference}'returnresultdef__str__(self)->str:result=f'{self.variable.name}: [{self.mapping}] ref: {self.reference}'returnresult