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 with enhanced RAGE from MASTERMIND

aGLM, or Autonomous General Learning Model, is a sophisticated machine learning model that integrates aspects of both supervised and unsupervised learning to analyze and interpret data across various applications like natural language processing, image recognition, and financial forecasting. This model is designed to efficiently handle large volumes of data and is particularly effective as a foundational tool for building more complex models. Key features of aGLM include: Dynamic Learning: aGLM can process and learn from […]

Learn More
aGLM

draw_conclusion(self)

ezAGI fundamental Augmented General Intelligence draw_conclusion(self) method The draw_conclusion method is designed to synthesize a logical conclusion from a set of premises, validate this conclusion, and then save the input/response sequence to a short-term memory storage. This function is a critical component in the context of easy Augmented General Intelligence (AGI) system, as it demonstrates the ability to process information, generate responses, validate outputs, and maintain a record of interactions for future reference and learning. […]

Learn More
MASTERMIND

Innovative Approach: IA mode to AGI prompt template from Professor Codephreak

Professor-Codephreak is the first LLM that I developed. Professor-Codephreak is also a GPT4 agent designed to be a platform architect and software engineer. You know, the kind of solution oriented person you would gladly pay $1000 / hour to hang out with in the real world. The two parts of Professor-Codephreak have not “met” each other though the automindx engine in the GPT4 version uses automind to dynamically respond. automind was developed as codephreak’s first […]

Learn More