import numpy as np
from itertools import product

# Parameters
learning_rate = 0.1
max_iterations = 1000

# Sigmoid activation function
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def activation_function(weighted_sum):
    return sigmoid(weighted_sum)

# Inputs for the two-variable logic tables
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])

# Generate all 16 possible truth tables for 2 inputs
all_truth_tables = list(product([0, 1], repeat=4))  # 16 combinations of binary outputs

# Train the network for each truth table
for truth_table_idx, targets in enumerate(all_truth_tables):
    print(f"\nTraining for Truth Table {truth_table_idx + 1}: {targets}")

    # Initialize weights with smaller values
    weights_input_hidden = np.random.uniform(-0.5, 0.5, (2, 4))  # 2 input neurons to 4 hidden neurons
    weights_hidden_output = np.random.uniform(-0.5, 0.5, 4)      # 4 hidden neurons to 1 output neuron

    epoch = 0
    network_trained = False

    while epoch < max_iterations:
        epoch += 1
        all_correct = True  # Flag to track if all outputs are correct

        for input_vector, target in zip(inputs, targets):
            # Forward pass
            hidden_input = np.dot(input_vector, weights_input_hidden)  # Input -> Hidden
            hidden_output = activation_function(hidden_input)          # Hidden neuron activations
            
            final_input = np.dot(hidden_output, weights_hidden_output)  # Hidden -> Output
            output = activation_function(final_input)                  # Sigmoid activation
            output = 1 if output > 0.5 else 0  # Threshold for binary output

            # Error calculation
            error = target - output

            # Backpropagation and weight updates
            if error != 0:
                all_correct = False

                # Update weights for Hidden -> Output
                weights_hidden_output += learning_rate * error * hidden_output

                # Update weights for Input -> Hidden
                delta_hidden = weights_hidden_output * error * hidden_output * (1 - hidden_output)
                for i in range(4):  # Loop over hidden neurons
                    weights_input_hidden[:, i] += learning_rate * delta_hidden[i] * input_vector

        if all_correct:
            network_trained = True
            break  # Stop training if all outputs are correct

    # Print results for the truth table
    if network_trained:
        print(f"The network learned the truth table correctly after {epoch} iterations.")
    else:
        print(f"The network failed to learn the truth table after {epoch} iterations.")

    # Test the trained network
    print("\nTesting the trained network:")
    for input_vector, target in zip(inputs, targets):
        hidden_input = np.dot(input_vector, weights_input_hidden)  # Input -> Hidden
        hidden_output = activation_function(hidden_input)          # Hidden activations
        
        final_input = np.dot(hidden_output, weights_hidden_output)  # Hidden -> Output
        output = activation_function(final_input)                  # Output activation
        output = 1 if output > 0.5 else 0  # Threshold for binary output
        print(f"Input: {input_vector}, Target: {target}, Output: {output}")
    print("-----------------------------------------------------------")
