================================================================================
# Architecture 1: Single-Layer Perceptron for AND and OR Gates
# Library: keres | Framework: NumPy / Matplotlib | Total Cells: 2
================================================================================


# --------------------------------------------------------------------------------
# [CELL 1 / 2] : Perceptron Class & AND Gate Decision Boundary Plot
# --------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

def step_function(x):
    return np.where(x >= 0, 1, 0)

class Perceptron:
    def __init__(self, input_size, learning_rate=0.1, epochs=10):
        self.weights = np.zeros(input_size + 1)  
        self.lr = learning_rate
        self.epochs = epochs

    def predict(self, x):
        x = np.insert(x, 0, 1)  
        return step_function(np.dot(self.weights, x))

    def train(self, X, y):
        for epoch in range(self.epochs):
            total_error = 0

            for xi, target in zip(X, y):
                xi_bias = np.insert(xi, 0, 1)

                output = step_function(np.dot(self.weights, xi_bias))
                error = target - output
                total_error += abs(error)

                self.weights += self.lr * error * xi_bias

            print(f"Epoch {epoch+1}: Error = {total_error}")

X = np.array([
    [0, 0],
    [0, 1],
    [1, 0],
    [1, 1]
])

y = np.array([0, 0, 0, 1])

p = Perceptron(input_size=2)
p.train(X, y)

print("\nFinal Weights:", p.weights)

print("\nPredictions:")
for sample in X:
    print(sample, "->", p.predict(sample))

def plot_decision_boundary(model, X, y):
    x_min, x_max = -0.2, 1.2
    y_min, y_max = -0.2, 1.2

    xx, yy = np.meshgrid(
        np.linspace(x_min, x_max, 100),
        np.linspace(y_min, y_max, 100)
    )

    Z = np.array([
        model.predict(np.array([x, y]))
        for x, y in zip(xx.ravel(), yy.ravel())
    ])

    Z = Z.reshape(xx.shape)

    plt.figure(figsize=(6,5))
    plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.coolwarm)
    plt.scatter(X[:,0], X[:,1], c=y, cmap=plt.cm.coolwarm,
                edgecolors='black', s=120)

    plt.title("Decision Boundary of Perceptron (AND Gate)")
    plt.xlabel("Input 1")
    plt.ylabel("Input 2")
    plt.grid(True)
    plt.show()

plot_decision_boundary(p, X, y)


# --------------------------------------------------------------------------------
# [CELL 2 / 2] : Perceptron Class & OR Gate Decision Boundary Plot
# --------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

def step_function(x):
    return np.where(x >= 0, 1, 0)

class Perceptron:
    def __init__(self, input_size, learning_rate=0.1, epochs=10):
        self.weights = np.zeros(input_size + 1) 
        self.lr = learning_rate
        self.epochs = epochs

    def predict(self, x):
        x = np.insert(x, 0, 1)  
        return step_function(np.dot(self.weights, x))

    def train(self, X, y):
        for epoch in range(self.epochs):
            total_error = 0

            for xi, target in zip(X, y):
                xi_bias = np.insert(xi, 0, 1)

                output = step_function(np.dot(self.weights, xi_bias))
                error = target - output
                total_error += abs(error)

                self.weights += self.lr * error * xi_bias

            print(f"Epoch {epoch+1}: Error = {total_error}")

X = np.array([
    [0, 0],
    [0, 1],
    [1, 0],
    [1, 1]
])

y = np.array([0, 1, 1, 1])

p = Perceptron(input_size=2)
p.train(X, y)

print("\nFinal Weights:", p.weights)

print("\nPredictions:")
for sample in X:
    print(sample, "->", p.predict(sample))

def plot_decision_boundary(model, X, y):
    x_min, x_max = -0.2, 1.2
    y_min, y_max = -0.2, 1.2

    xx, yy = np.meshgrid(
        np.linspace(x_min, x_max, 100),
        np.linspace(y_min, y_max, 100)
    )

    Z = np.array([
        model.predict(np.array([x, y]))
        for x, y in zip(xx.ravel(), yy.ravel())
    ])

    Z = Z.reshape(xx.shape)

    plt.figure(figsize=(6,5))
    plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.coolwarm)
    plt.scatter(X[:,0], X[:,1], c=y, cmap=plt.cm.coolwarm,
                edgecolors='black', s=120)

    plt.title("Decision Boundary of Perceptron (OR Gate)")
    plt.xlabel("Input 1")
    plt.ylabel("Input 2")
    plt.grid(True)
    plt.show()

plot_decision_boundary(p, X, y)

================================================================================
💡 CUSTOMIZATION & ADAPTATION RECIPES FOR ARCHITECTURE 1 (Perceptron for Logic Gates in NumPy):
================================================================================
1. SWITCH TO LOCAL CSV VIA PANDAS:
   import pandas as pd
   df = pd.read_csv('logic_gate.csv')  # CSV with columns: x1, x2, target
   X = df[['x1', 'x2']].values
   y = df['target'].values

2. SWITCH LOGIC GATES:
   # AND Gate (Default):
   y = np.array([0, 0, 0, 1])
   # OR Gate:
   y = np.array([0, 1, 1, 1])
   # NAND Gate:
   y = np.array([1, 1, 1, 0])
   # NOR Gate:
   y = np.array([1, 0, 0, 0])
   # XOR Gate (ARCHITECTURE NOTE: Single perceptron CANNOT solve XOR because XOR is non-linearly separable!):
   y = np.array([0, 1, 1, 0])

3. HYPERPARAMETER TWEAKS:
   # Slower, smoother learning:
   p = Perceptron(input_size=2, learning_rate=0.01, epochs=30)
   # Faster, aggressive updates:
   p = Perceptron(input_size=2, learning_rate=0.5, epochs=10)

4. SWITCH ACTIVATION FUNCTION:
   # Bipolar Step Function (-1 or +1 output):
   def step_function_bipolar(x):
       return np.where(x >= 0, 1, -1)
   # Sigmoid Perceptron (Continuous output [0, 1]):
   def sigmoid(x):
       return 1 / (1 + np.exp(-x))
================================================================================
