"""Base module for logical expressions.This module provides the base class for all logical expressions in the logic system.It defines the common interface that all logical expressions must implement,including evaluation, variable extraction, and serialization."""from__future__importannotationsfromtypingimportDict,ListfrompydanticimportBaseModel
[docs]classLogicalExpression(BaseModel):""" Recursive base class for logical expressions. This abstract class defines the interface for all logical expressions in the system. Concrete implementations include Proposition, Not, and BinaryOp. Attributes: model_config: Pydantic model configuration to allow arbitrary types. """model_config={"arbitrary_types_allowed":True}
[docs]defevaluate(self,context:Dict[str,bool])->bool:""" Recursively evaluates the expression under a given truth assignment. Args: context: Dictionary mapping variable names to truth values. Example: {"P": True, "Q": False} Returns: Boolean result of evaluating the expression. Raises: NotImplementedError: This is an abstract method that must be implemented by subclasses. """raiseNotImplementedError
[docs]defvariables(self)->List[str]:""" Recursively extracts all variables in the expression. Returns: List of variable names used in the expression. Raises: NotImplementedError: This is an abstract method that must be implemented by subclasses. """raiseNotImplementedError
[docs]defdepth(self)->int:""" Computes the depth of the logical expression tree. Returns: Integer representing the depth of the expression tree. Raises: NotImplementedError: This is an abstract method that must be implemented by subclasses. """raiseNotImplementedError
[docs]defto_dict(self)->Dict:""" Recursively converts expression to a dictionary. Returns: Dictionary representation of the logical expression. Raises: NotImplementedError: This is an abstract method that must be implemented by subclasses. """raiseNotImplementedError
[docs]@classmethoddeffrom_dict(cls,data:Dict)->LogicalExpression:""" Recursively reconstructs an expression from a dictionary. Args: data: Dictionary representation of a logical expression. Must include a 'type' field. Returns: Reconstructed logical expression. Raises: ValueError: If the data is not a dictionary, doesn't have a type field, or has an unknown expression type. """ifnotisinstance(data,dict):raiseValueError(f"Expected dictionary but got {type(data)}")# Import here to avoid circular importsfromagent_logic.core.operationsimportBinaryOp,Not,Propositionif"type"notindata:raiseValueError(f"Missing 'type' in expression data: {data}")exp_type=data["type"]ifexp_type=="Proposition":returnProposition.from_dict(data)elifexp_type=="Not":returnNot.from_dict(data)elifexp_type=="BinaryOp":returnBinaryOp.from_dict(data)else:raiseValueError(f"Unknown expression type: {exp_type}")