LogicTables Module Documentation

you are?

Overview

The LogicTables module is designed to handle logical expressions, variables, and truth tables. It provides functionality to evaluate logical expressions, generate truth tables, and validate logical statements. The module also includes logging mechanisms to capture various events and errors, ensuring that all operations are traceable.

Class LogicTables

Attributes

  • variables: A list to store the variables involved in logical expressions.
  • expressions: A list to store the logical expressions to be evaluated.
  • valid_truths: A list to store expressions that have been validated as true.
  • logger: A logging object to capture and store log messages.
def __init__(self):
    self.variables = []
    self.expressions = []
    self.valid_truths = []
    self.logger = logging.getLogger('LogicTables')
    self.logger.setLevel(logging.DEBUG)  # Set to DEBUG to capture all logs

Upon initialization, the LogicTables class sets up logging mechanisms and ensures that necessary directories for logs are created.

Logging Methods

def log(self, message, level='info'):
    if level == 'info':
        self.logger.info(message)
    elif level == 'error':
        self.logger.error(message)
    elif level == 'warning':
        self.logger.warning(message)
    self.store_log_in_mindx(message, level)
    self.store_log_in_memory(message, level)

def store_log_in_mindx(self, message, level):
    general_log_path = './mindx/errors/log.txt'
    pathlib.Path(general_log_path).parent.mkdir(parents=True, exist_ok=True)
    with open(general_log_path, 'a') as file:
        file.write(f"{level.upper()}: {message}\n")

def store_log_in_memory(self, message, level):
    memory_log_path = './memory/truth/logs.txt'
    pathlib.Path(memory_log_path).parent.mkdir(parents=True, exist_ok=True)
    with open(memory_log_path, 'a') as file:
        file.write(f"{level.upper()}: {message}\n")

The logging methods ensure that messages are logged both to the general log file and the memory log file


Adding Variables and Expressions


def add_variable(self, var):
    if var not in self.variables:
        self.variables.append(var)
        self.log(f"Added variable: {var}")
        self.output_belief(f"Added variable: {var}")
    else:
        self.log(f"Variable {var} already exists.", level='warning')

def add_expression(self, expr):
    if expr not in self.expressions:
        self.expressions.append(expr)
        self.log(f"Added expression: {expr}")
        self.output_belief(f"Added expression: {expr}")
    else:
        self.log(f"Expression {expr} already exists.", level='warning')


These methods add new variables and expressions to their respective lists and log the additions.


Evaluating Expressions


def evaluate_expression(self, expr, values):
    allowed_operators = {
        'and': lambda x, y: x and y,
        'or': lambda x, y: x or y,
        'not': lambda x: not x,
        'xor': lambda x, y: x ^ y,
        'nand': lambda x, y: not (x and y),
        'nor': lambda x, y: not (x or y),
        'implication': lambda x, y: not x or y
    }

    try:
        result = eval(expr, {"__builtins__": None}, {**allowed_operators, **values})
        self.log(f"Evaluated expression '{expr}' with values {values}: {result}")
        return result
    except Exception as e:
        self.log(f"Error evaluating expression '{expr}': {e}", level='error')
        return False


This method evaluates a logical expression using the provided values and logs the results.

Generating and Displaying Truth Tables


def generate_truth_table(self):
    n = len(self.variables)
    combinations = list(itertools.product([True, False], repeat=n))
    truth_table = []

    for combo in combinations:
        values = {self.variables[i]: combo[i] for i in range(n)}
        result = values.copy()
        for expr in self.expressions:
            result[expr] = self.evaluate_expression(expr, values)
        truth_table.append(result)

    self.log(f"Generated truth table with {len(truth_table)} rows")
    self.output_belief(f"Generated truth table with {len(truth_table)} rows")
    return truth_table

def display_truth_table(self):
    truth_table = self.generate_truth_table()
    headers = self.variables + self.expressions
    print("\t".join(headers))
    for row in truth_table:
        print("\t".join(str(row[var]) for var in headers))


These methods generate and display truth tables based on the current variables and expressions


Validating Truths


def validate_truth(self, expression):
    if expression not in self.expressions:
        self.log(f"Expression '{expression}' is not in the list of expressions.", level='warning')
        return False

    truth_table = self.generate_truth_table()
    for row in truth_table:
        if not row[expression]:
            self.log(f"Expression '{expression}' is not valid.")
            return False
    # is valid expression
    self.log(f"Expression '{expression}'")
    self.save_valid_truth(expression)
    return True

def save_valid_truth(self, expression):
    timestamp = datetime.datetime.now().isoformat()
    valid_truth = {"expression": expression, "timestamp": timestamp}
    self.valid_truths.append(valid_truth)
    save_valid_truth(valid_truth)
    self.log(f"Saved valid truth: '{expression}' at {timestamp}")


These methods validate logical expressions and save them if they are valid


Additional Methods

    get_valid_truths: Retrieves all validated truths.
    tautology: Checks if an expression is a tautology.
    modus_ponens: Implements the modus ponens rule of inference.
    unify_variables: Unifies variables between facts and rules.

example use


if __name__ == '__main__':
    lt = LogicTables()
    lt.add_variable('A')
    lt.add_variable('B')
    lt.add_expression('A and B')
    lt.add_expression('A or B')
    lt.add_expression('not A')
    lt.add_expression('A xor B')
    lt.add_expression('A nand B')
    lt.add_expression('A nor B')
    lt.add_expression('A implication B')
    lt.display_truth_table()

    expression_to_validate = 'A and B'
    is_valid = lt.validate_truth(expression_to_validate)
    print(f"Is the expression '{expression_to_validate}' valid? {is_valid}")

    valid_truths = lt.get_valid_truths()
    print("Valid truths with timestamps:")
    for truth in valid_truths:
        print(truth)


demonstrates the LogicTables class to add variables and expressions, generate and display a truth table, and validate logical expressions.


logic.py is an essential component of fundamental AGI
funAGI fundamental augmented general intelligence framework


logic is an essential step towards drawing a conclusion or making a decision



#############################################################################

# logging
logic module with error handling explanation

from the perspective of funAGI logging is sometimes duplicated to both the 


executable
./mindx ./mindx/errors/log.txt


read_only
./memory ./memory/truth/logs.txt


folders allowing the machine to participate in self_healing from logic errors


self.log(f"Evaluated expression '{expr}' with values {values}: {result}")


# log add variable

        self.log(f"Added variable: {var}")
        self.output_belief(f"Added variable: {var}")
    else:
        self.log(f"Variable {var} already exists.", level='warning')


# log add expression

        self.log(f"Added expression: {expr}")
        self.output_belief(f"Added expression: {expr}")
    else:
        self.log(f"Expression {expr} already exists.", level='warning')


# log evaluated expression

        self.log(f"Evaluated expression '{expr}' with values {values}: {result}")
        return result
    except Exception as e:
        self.log(f"Error evaluating expression '{expr}': {e}", level='error')


# log truth_table generation

        self.log(f"Generated truth table with {len(truth_table)} rows")
    self.output_belief(f"Generated truth table with {len(truth_table)} rows")
    return truth_table

# display truth_table


        def display_truth_table(self):
    truth_table = self.generate_truth_table()
    headers = self.variables + self.expressions
    print("\t".join(headers))
    for row in truth_table:
        print("\t".join(str(row[var]) for var in headers))




# VALIDATING TRUTH #

# log if expression not in self.expressions:

        
    self.log(f"Expression '{expression}' is not in the list of expressions.", level='warning')



#  log if not row[expression]:

       
    self.log(f"Expression '{expression}' is not valid.")


# log self.save_valid_truth(expression)
    
            
    self.log(f"Expression '{expression}'")
    


# log save_valid_truth(valid_truth)
    
    self.log(f"Saved valid truth: '{expression}' at {timestamp}")


#############################################################################


Workflow for providing solution from AGI as a response from reasoning


#############################################################################

























Related articles

aGLM

aGLM, or Autonomous General Learning Model, is designed to operate as a core model for autonomous data parsing and learning from memory in the context of artificial intelligence systems. It’s a pivotal element within a broader system called RAGE (Retrieval Augmented Generative Engine). Key aspects and functionalities of aGLM: Autonomous Learning: aGLM is built to learn autonomously from interactions and data retrievals. It continuously updates its knowledge base, refining its capabilities based on new data […]

Learn More
ezAGI

ezAGI

Augmented Generative Intelligence Framework The ezAGI project is an advanced augmented generative intelligence system that combining various components to create a robust, flexible, and extensible framework for reasoning, decision-making, self-healing, and multi-model interaction. Core Components MASTERMIND Purpose:The mastermind module serves as the core orchestrator for the easyAGI system. It manages agent lifecycles, integrates various components, and ensures the overall health and performance of the system. Key Features: SimpleCoder Purpose:The SimpleCoder module defines a coding agent […]

Learn More

Hackathon Challenge:

OpenAI Assistants API Llama-Index/MongoDB In this hackathon, you will build and iterate on an LLM-based application using AI observability to validate the performance of your app. You can choose between two sets of tools for building your app: Tool set 1: The OpenAI Assistants API Tool set 2: Llama-Index, MongoDB and GPT-4. With either choice, you will use TruLens to validate and improve the performance of your application. By bringing together TruEra, OpenAI, Llama-Index, and […]

Learn More