Skip to content

fractal_engine_v6_full_adder.py #2

@Entropeepee

Description

@Entropeepee

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Circle, RegularPolygon
import re
import math

==============================================================================

The Core Unit: CoherenceCell v5.0 with Universal Gate Logic

==============================================================================

class CoherenceCell:
"""The universal computational cell, supporting a full suite of standard logic gates."""
def init(self, q, r):
self.q, self.r = q, r
self.phi = 0.0
self.theta = 0.0
self.gate_type = 'EMPTY'
self.gate_inputs = []
self.gate_threshold = 0.7

def update(self, all_states):
    """Updates the cell's state based on its programmed gate or diffusion physics."""
    if self.gate_type != 'EMPTY':
        if not self.gate_inputs: return
        input_states = [all_states.get((n.q, n.r)) for n in self.gate_inputs]
        input_states = [s for s in input_states if s is not None]
        high_inputs = [s for s in input_states if s['phi'] > self.gate_threshold]

        fired = False
        if self.gate_type == 'AND':
            if len(high_inputs) == len(self.gate_inputs) and self.gate_inputs:
                fired = True
        elif self.gate_type == 'OR':
            if len(high_inputs) > 0:
                fired = True
        elif self.gate_type == 'XOR':
            if len(high_inputs) == 2:
                # Fires on destructive interference of two high inputs
                phase_diff = (high_inputs[0]['theta'] - high_inputs[1]['theta'] + np.pi) % (2 * np.pi) - np.pi
                if abs(phase_diff) > 2.5:  # Check if phases are opposite
                    fired = True
        
        if fired:
            self.phi = 1.5
        else:
            self.phi *= 0.8
        return
    
    # Standard Diffusion for non-gate cells
    if not hasattr(self, 'neighbors') or not self.neighbors: return
    neighbor_phis = [all_states[(n.q, n.r)]['phi'] for n in self.neighbors]
    self.phi += 0.4 * (np.mean(neighbor_phis) - self.phi) - (self.phi * 0.1)
    self.phi = np.clip(self.phi, 0, 1.5)

==============================================================================

The Substrate: HexMembraneField

==============================================================================

class HexMembraneField:
"""The hexagonal grid that contains all CoherenceCells."""
def init(self, radius=50):
self.radius = radius
self.grid = {}
self.runtime_plan = None
for q in range(-radius, radius + 1):
r1, r2 = max(-radius, -q - radius), min(radius, -q + radius)
for r in range(r1, r2 + 1):
self.grid[(q, r)] = CoherenceCell(q, r)
# Pre-calculate neighbors for performance
for pos, cell in self.grid.items():
cell.neighbors = self._get_neighbors(pos[0], pos[1])

def update_step(self):
    """Executes a single time-step update for all cells."""
    old_states = {pos: {'phi': cell.phi, 'theta': cell.theta} for pos, cell in self.grid.items()}
    for cell in self.grid.values():
        cell.update(old_states)

def _get_neighbors(self, q, r):
    """Helper to get valid neighbors for a cell."""
    coords = [(q+1, r), (q-1, r), (q, r+1), (q, r-1), (q+1, r-1), (q-1, r+1)]
    return [self.grid[c] for c in coords if c in self.grid]

==============================================================================

The FOS v3.0 Logic Compiler

==============================================================================

class FOS_Compiler:
"""The FOS, upgraded to a full logic compiler with auto place-and-route."""
def init(self):
print("[FOS] FRACTAL Operating System v3.0 (Logic Compiler) Initialized.")

def _parse_netlist(self, netlist_string):
    """Parses a Verilog-like netlist into a structured plan."""
    plan = {'inputs': [], 'outputs': [], 'wires': []}
    for line in netlist_string.strip().split('\n'):
        line = line.strip()
        if not line or line.startswith('//'): continue
        
        match_input = re.match(r"DEFINE INPUT ([\w\s,]+)", line)
        match_output = re.match(r"DEFINE OUTPUT ([\w\s,]+)", line)
        match_wire = re.match(r"WIRE \(([\w\s,]+)\)\s+->\s+(\w+)\s+->\s+(\w+)", line)

        if match_input:
            plan['inputs'].extend([s.strip() for s in match_input.group(1).split(',')])
        elif match_output:
            plan['outputs'].extend([s.strip() for s in match_output.group(1).split(',')])
        elif match_wire:
            plan['wires'].append({
                'inputs': [s.strip() for s in match_wire.group(1).split(',')],
                'gate': match_wire.group(2),
                'output': match_wire.group(3)
            })
    return plan

def compile(self, netlist_string):
    """Compiles a netlist into a fully laid-out and wired physical circuit."""
    plan = self._parse_netlist(netlist_string)
    membrane = HexMembraneField()
    layout = {}  # Will store name -> position mapping
    node_layers = {}  # Will store name -> layer mapping

    # 1. Topological Analysis: Determine logic layers to deduce data flow
    node_layers.update({name: 0 for name in plan['inputs']})
    unresolved_wires = list(plan['wires'])
    current_layer = 1
    while unresolved_wires:
        resolved_this_pass = []
        for wire in unresolved_wires:
            if all(inp in node_layers for inp in wire['inputs']):
                node_layers[wire['output']] = current_layer
                resolved_this_pass.append(wire)
        if not resolved_this_pass:
            raise ValueError("Circuit has circular dependency or undefined inputs.")
        unresolved_wires = [w for w in unresolved_wires if w not in resolved_this_pass]
        current_layer += 1
    
    # 2. Auto Place-and-Route: Assign physical locations based on layers
    max_layer = max(node_layers.values()) if node_layers else 0
    layer_counts = {i: 0 for i in range(max_layer + 2)} # Add buffer for outputs
    
    # Add outputs to the layering system for placement
    for name in plan['outputs']:
        if name not in node_layers: # If output is just a passthrough or final gate
            # Find its source to determine its layer
            source_wire = next((w for w in plan['wires'] if w['output'] == name), None)
            if source_wire:
                source_layer = max(node_layers[inp] for inp in source_wire['inputs'])
                node_layers[name] = source_layer + 1
            else: # It might be a direct alias of an input
                node_layers[name] = max_layer + 1
    
    max_layer = max(node_layers.values()) if node_layers else 0
    sorted_nodes = sorted(node_layers.keys(), key=lambda k: node_layers[k])
    
    for node_name in sorted_nodes:
        layer = node_layers[node_name]
        q = -40 + int(80 * layer / max_layer) if max_layer > 0 else 0
        r = -20 + layer_counts[layer] * 15
        layout[node_name] = (q, r)
        layer_counts[layer] += 1
    
    # 3. Gate Programming and Wiring
    node_map = {name: membrane.grid[pos] for name, pos in layout.items()}
    for wire in plan['wires']:
        output_cell = node_map[wire['output']]
        output_cell.gate_type = wire['gate']
        output_cell.gate_inputs = [node_map[inp_name] for inp_name in wire['inputs']]

    print("--- FOS Auto Place-and-Route Complete ---")
    return membrane, layout

==============================================================================

Main Execution Block to run the Full-Adder simulation

==============================================================================

if name == 'main':
# Define the Full-Adder circuit using the Verilog-like SIF
full_adder_netlist = """
// A 1-bit Full-Adder Circuit to be compiled by the FOS
DEFINE INPUT A, B, CARRY_IN
DEFINE OUTPUT SUM, CARRY_OUT

// Logic for SUM = (A XOR B) XOR CARRY_IN
WIRE (A, B) -> XOR -> TEMP_XOR
WIRE (TEMP_XOR, CARRY_IN) -> XOR -> SUM

// Logic for CARRY_OUT = (A AND B) OR (CARRY_IN AND (A XOR B))
WIRE (A, B) -> AND -> TEMP_AND1
WIRE (CARRY_IN, TEMP_XOR) -> AND -> TEMP_AND2
WIRE (TEMP_AND1, TEMP_AND2) -> OR -> CARRY_OUT
"""

# Compile the circuit with the FOS
fos = FOS_Compiler()
programmed_membrane, layout = fos.compile(full_adder_netlist)

# --- Visualization Setup ---
fig, ax = plt.subplots(figsize=(16, 12))
ax.set_facecolor('black')
ax.set_aspect('equal')
ax.axis('off')

patches = {pos: RegularPolygon((pos[0]*1.5*0.866, pos[1]*1.5 + (pos[0]%2)*0.75), 6, radius=1.0, ec='#333', lw=0.5) for pos in programmed_membrane.grid.keys()}
for patch in patches.values():
    ax.add_patch(patch)

# Add persistent labels for all nodes in the layout
for name, pos in layout.items():
    x, y = pos[0]*1.5*0.866, pos[1]*1.5 + (pos[0]%2)*0.75
    ax.text(x, y + 2.5, name, color='white', ha='center', va='center', fontsize=8, weight='bold')

def animate(frame):
    # Test Case: 1 + 1 + 1. Expected result: Sum=1, Carry_Out=1
    if frame == 5:
        print("--- RUNTIME: Pulsing inputs A=1, B=1, CARRY_IN=1 ---")
        # For XOR gates to work correctly, their direct inputs need opposing phases
        membrane.grid[layout['A']].phi = 1.5; membrane.grid[layout['A']].theta = 0
        membrane.grid[layout['B']].phi = 1.5; membrane.grid[layout['B']].theta = math.pi
        membrane.grid[layout['CARRY_IN']].phi = 1.5; membrane.grid[layout['CARRY_IN']].theta = 0
    
    programmed_membrane.update_step()

    sum_phi = programmed_membrane.grid[layout['SUM']].phi
    carry_phi = programmed_membrane.grid[layout['CARRY_OUT']].phi
    ax.set_title(f"Executing Full-Adder: A=1, B=1, Cin=1\nSUM Output: {sum_phi:.2f} | CARRY_OUT Output: {carry_phi:.2f}", color='white')
    
    norm = plt.Normalize(vmin=0, vmax=1.5)
    for pos, cell in programmed_membrane.grid.items():
        patches[pos].set_facecolor(plt.cm.magma(norm(cell.phi)))
    
    return list(patches.values())

ani = animation.FuncAnimation(fig, animate, frames=150, interval=60, blit=True, repeat=False)
plt.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions