LogicTables Class: Managing Logic and Beliefs

Symbolic Logic

The LogicTables class in logic.py is designed to handle logical expressions, evaluate their truth values, and manage beliefs as valid truths. It integrates with the SimpleMInd or similar neural network system to process and use truths effectively.


Key Features:

Variable and Expression Management: Allows adding logical variables and expressions.
Truth Table Generation: Generates truth tables for given variables and expressions.
Expression Evaluation: Evaluates expressions based on given values.
Logging: Logs operations and errors for debugging and auditing purposes.
Belief Management: Stores and validates beliefs (truths) and exports them for further processing.


Initialization and Logging

The LogicTables class initializes with logging configuration to capture debug information:

class LogicTables:
def init(self):
self.variables = []
self.expressions = []
self.valid_truths = []
self.logger = logging.getLogger('LogicTables')
self.logger.setLevel(logging.DEBUG)

    # Setup log files
    self._setup_logging()

def _setup_logging(self):
    # Configure logging for different log files
    ...

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')

Truth tables are generated to evaluate logical expressions:

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))

Expressions are evaluated using logical operators:

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

Validating and Storing Beliefs

Beliefs are validated and stored if they hold true across all cases in the truth table:

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

self.log(f"Expression '{expression}' is valid.")
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}")

The LogicTables class is used to validate beliefs, which are then fed into SimpleMind for further processing from belief preprocessed into truth:

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.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)

Exporting Beliefs to SimpleMind

Once validated, these truths (beliefs) can be used as input features or constraints in a SimpleMind neural network:

Assuming simple_mind is an instance of SimpleMind

for truth in valid_truths:
expression = truth['expression']
# Use this truth in SimpleMind's input or as part of the training process
# Example: Adding it as a feature or a constraint
simple_mind.add_feature(expression)

Example Truth Table

A truth table for variables A and B with expressions A and B, A or B, and not A might look like this:
A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

The LogicTables class in logic.py is a powerful tool for managing logical variables and expressions, generating truth tables, evaluating and validating expressions, and exporting beliefs. These beliefs once integrated into the SimpleMind neural network allowing for the processing of validated truths thereby enhancing SimpleMind decision-making capabilities.

SimpleMind neural network a study in efficiency from minimalism

Related articles

Professor Codephreak's binary clock — BinaryClock and binarytotext

Professor Codephreak Does It Again: a Binary Clock and a Text ↔ Binary Converter for the Curious Beginner

Two free open-source tools for the novice gaining a foothold in computer science: a 3D <binary-clock> Web Component (BIN/BCD/DEC, alarms, world clock, Ethereum blocktime) and a text-to-binary / binary-to-text converter — both embedded live on this page.

Learn More
concurrency

concurrency in Python with asyncio

Concurrency is a vital concept in modern programming, enabling systems to manage and execute multiple tasks simultaneously. This capability is crucial for improving the efficiency and responsiveness of applications, especially those dealing with I/O-bound operations such as web servers, database interactions, and network communications. In Python, concurrency can be achieved through several mechanisms, with the asyncio library being a prominent tool for asynchronous programming. What is Concurrency? Concurrency refers to the ability of a program […]

Learn More
Operational Transparency — the cypherpunk2048 standard

Operational Transparency — the cypherpunk2048 standard

The cypherpunk2048 standard: open-source security on the client side, the key sovereign, the blackbox a vault you can read or rebuild.

Learn More