Source code for biogeme.likelihood.negative_likelihood
"""Class that provides the function to the optimization algorithmMichel BierlaireSat Mar 29 16:27:47 2025"""importloggingfromtypingimportCallableimportnumpyasnpfrombiogeme_optimization.functionimportFunctionData,FunctionToMinimizefrombiogeme.exceptionsimportBiogemeErrorfrombiogeme.function_outputimportFunctionOutputlogger=logging.getLogger(__name__)
[docs]classNegativeLikelihood(FunctionToMinimize):"""Provides the value of the function to be minimized, as well as its derivatives. To be used by the optimization package. """def__init__(self,dimension:int,loglikelihood:Callable[[np.ndarray,bool,bool,bool],FunctionOutput],parameters:dict[str,float]|None=None,):"""Constructor"""tolerance=Nonesteptol=NoneifparametersisnotNone:if'tolerance'inparameters:tolerance=parameters['tolerance']if'steptol'inparameters:steptol=parameters['steptol']super().__init__(epsilon=tolerance,steptol=steptol)self.the_dimension:int=dimension#: number of parameters to estimateself.loglikelihood:Callable[[np.ndarray,bool,bool,bool],FunctionOutput]=(loglikelihood)self.filename_for_best_iteration:str|None=Noneself.free_beta_names:list[str]|None=Noneself.best_value:float|None=None
[docs]defdimension(self)->int:"""Provides the number of variables of the problem"""returnself.the_dimension
def_f(self)->float:ifself.xisNone:raiseBiogemeError('The variables must be set first.')results=self.loglikelihood(self.x,gradient=False,hessian=False,bhhh=False)self._save_best_iteration(self.x,results.function)return-results.functiondef_f_g(self)->FunctionData:ifself.xisNone:raiseBiogemeError('The variables must be set first.')the_function_output:FunctionOutput=self.loglikelihood(self.x,gradient=True,hessian=False,bhhh=False)self._save_best_iteration(self.x,the_function_output.function)returnFunctionData(function=-the_function_output.function,gradient=-the_function_output.gradient,hessian=None,)def_f_g_h(self)->FunctionData:ifself.xisNone:raiseBiogemeError('The variables must be set first.')the_function_output:FunctionOutput=self.loglikelihood(self.x,gradient=True,hessian=True,bhhh=False)self._save_best_iteration(self.x,the_function_output.function)returnFunctionData(function=-the_function_output.function,gradient=-the_function_output.gradient,hessian=-the_function_output.hessian,)def_save_best_iteration(self,x:np.ndarray,f:float)->None:ifself.filename_for_best_iterationisNone:returnifself.best_valueisNone:self.best_value=fiff>=self.best_value:self.best_value=fwithopen(self.filename_for_best_iteration,"w",encoding="utf-8",)aspf:fori,vinenumerate(x):print(f"{self.free_beta_names[i]} = {v}",file=pf,)