Source code for biogeme.segmentation.one_segmentation
"""Handles the segmentation of a single parameter using a discrete variable.This class manages how a single Beta parameter is segmented according to adiscrete variable. It generates distinct parameters for each category in thesegmentation (except the reference), enabling models to estimate category-specificeffects.Attributes: beta: The base Beta parameter being segmented. segmentation_tuple: The DiscreteSegmentationTuple defining the segmentation. variable: The discrete variable used for segmentation. reference: The reference category for the segmentation. mapping: Dictionary of category values to category names, excluding the reference."""from__future__importannotationsfromtypingimportTYPE_CHECKINGfrom.segmentation_contextimportDiscreteSegmentationTuplefrombiogeme.exceptionsimportBiogemeErrorifTYPE_CHECKING:frombiogeme.expressionsimportBeta,Variable,Expression,Numeric
[docs]classOneSegmentation:def__init__(self,beta:Beta,segmentation_tuple:DiscreteSegmentationTuple,):""" Initialize the segmentation of a Beta parameter. Parameters: beta: The base Beta parameter to be segmented. segmentation_tuple: Describes the discrete segmentation including the mapping of values to category names and the reference category. """self.beta:Beta=betaself.segmentation_tuple=segmentation_tupleself.variable:Variable=segmentation_tuple.variableself.reference:str=segmentation_tuple.referenceself.mapping:dict[int,str]={k:vfork,vinsegmentation_tuple.mapping.items()ifv!=self.reference}
[docs]defbeta_name(self,category:str)->str:"""Construct the name of the parameter associated with a specific category :param category: name of the category :return: name of parameter for the category :raise BiogemeError: if the category is not listed in the mapping of the segmentation. """ifcategory!=self.referenceandcategorynotinself.mapping.values():error_msg=(f'Unknown category: {category}. List of known categories: 'f'{self.mapping.values()}')raiseBiogemeError(error_msg)return(f'{self.beta.name}_ref'ifcategory==self.referenceelsef'{self.beta.name}_diff_{category}')
[docs]defbeta_expression(self,category:str|None=None)->Beta:"""Constructs the expression for the parameter associated with a specific category :param category: name of the category. If None, it is the reference category. :return: expression of the parameter for the category """frombiogeme.expressionsimportBetaifcategoryisNone:category=self.referencename=self.beta_name(category)ifcategory==self.reference:lower_bound=self.beta.lower_boundupper_bound=self.beta.upper_boundelse:lower_bound=Noneupper_bound=NonereturnBeta(name,self.beta.init_value,lower_bound,upper_bound,self.beta.status,)
[docs]defbeta_code(self,category:str,assignment:bool)->str:"""Constructs the Python code for the expression of the parameter associated with a specific category :param category: name of the category :param assignment: if True, the code includes the assignment to a variable. :return: the Python code """ifcategory==self.reference:lower_bound=self.beta.lower_boundupper_bound=self.beta.upper_boundelse:lower_bound=Noneupper_bound=Nonename=self.beta_name(category)ifassignment:return(f"{name} = Beta('{name}', {self.beta.init_value}, "f"{lower_bound}, {upper_bound}, {self.beta.status})")return(f"Beta('{name}', {self.beta.init_value}, {lower_bound}, "f"{upper_bound}, {self.beta.status})")
[docs]deflist_of_expressions(self)->list[Expression]:"""Create a list of expressions involved in the segmentation of the parameter :return: list of expressions :rtype: list(biogeme.expressions.Expression) """frombiogeme.expressionsimportNumericterms=[self.beta_expression(category)*(self.variable==Numeric(value))forvalue,categoryinself.mapping.items()]returnterms
[docs]deflist_of_code(self)->list[str]:"""Create a list of Python codes for the expressions involved in the segmentation of the parameter :return: list of codes """return[(f"{self.beta_name(category)} "f"* (Variable('{self.variable.name}') == {value})")forvalue,categoryinself.mapping.items()]