Skip to content

Instantly share code, notes, and snippets.

@NeoVertex1
Last active February 6, 2025 00:58
Show Gist options
  • Save NeoVertex1/a8c8ffa8d8ce1b40d8e74d81ba1e6aed to your computer and use it in GitHub Desktop.
Save NeoVertex1/a8c8ffa8d8ce1b40d8e74d81ba1e6aed to your computer and use it in GitHub Desktop.

Step 1: Build the Updated Docker Image (see Dockerfile)

docker build -t heat-kernel-vm .

Step 2: Run the Updated Heat-Logic VM

docker run -it --name heat-vm -v $(pwd)/data:/heatvm/data heat-kernel-vm

Step 3: Execute Heat-Based Programs Once inside the container, run:

python3 /heatvm/heat_kernel.py

# Base OS
FROM ubuntu:22.04
# Install dependencies
RUN apt-get update && apt-get install -y \
python3 python3-pip nodejs npm \
&& rm -rf /var/lib/apt/lists/*
# Install Python libraries
RUN pip3 install numpy numba jax jaxlib scipy matplotlib
# Install math.js
RUN npm install -g mathjs
# Set working directory
WORKDIR /heatvm
# Copy our updated heat computing kernel
COPY heat_kernel.py /heatvm/
# Make the script executable
RUN chmod +x /heatvm/heat_kernel.py
# Persistent volume for programs and data
VOLUME /heatvm/data
# Run interactive shell
CMD ["/bin/bash"]
import numpy as np
from heat_kernel import HeatLogicGates # Import our heat-based logic gates
class HeatFullAdder:
def __init__(self):
self.logic = HeatLogicGates()
def xor_gate(self, A, B):
"""Simulates XOR using NAND gates"""
nand1 = self.logic.nand_gate(A, B)
nand2 = self.logic.nand_gate(A, nand1)
nand3 = self.logic.nand_gate(B, nand1)
return self.logic.nand_gate(nand2, nand3)
def full_adder(self, A, B, Cin):
"""Implements a Full Adder using heat-based logic gates"""
xor1 = self.xor_gate(A, B)
Sum = self.xor_gate(xor1, Cin)
Carry = self.logic.or_gate(self.logic.and_gate(A, B), self.logic.and_gate(Cin, xor1))
return Sum, Carry
def multi_bit_adder(self, A_list, B_list):
"""Performs multi-bit binary addition using a series of Full Adders"""
Carry = 0
result = []
for A, B in zip(reversed(A_list), reversed(B_list)):
Sum, Carry = self.full_adder(A, B, Carry)
result.insert(0, Sum)
result.insert(0, Carry) # Final carry bit
return result
if __name__ == "__main__":
full_adder = HeatFullAdder()
# Test Single-Bit Full Adder
print("Single-bit Full Adder Tests:")
for A in [0, 1]:
for B in [0, 1]:
for Cin in [0, 1]:
Sum, Carry = full_adder.full_adder(A, B, Cin)
print(f" A={A}, B={B}, Cin={Cin} → Sum={Sum}, Carry={Carry}")
# Test Multi-Bit Adder (4-bit example: 1011 + 0110)
A_list = [1, 0, 1, 1]
B_list = [0, 1, 1, 0]
result = full_adder.multi_bit_adder(A_list, B_list)
print(f"\nMulti-bit Addition: {A_list} + {B_list} = {result}")
import numpy as np
import matplotlib.pyplot as plt
class HeatLogicGates:
def __init__(self, grid_size=50):
self.grid_size = grid_size
self.T = np.zeros((grid_size, grid_size)) # Initialize heat field
def apply_vortex(self, x, y, strength=1.0):
"""Create a vortex heat structure at a given location"""
for i in range(self.grid_size):
for j in range(self.grid_size):
dx, dy = i - x, j - y
self.T[i, j] += strength * np.exp(-0.1 * (dx**2 + dy**2)) # Gaussian decay
def nand_gate(self, A, B):
"""Implements a NAND gate using thermal diffusion"""
self.apply_vortex(10, 10, A)
self.apply_vortex(20, 20, B)
# Compute heat diffusion (simulating logical transition)
output = 1 - np.clip(self.T[15, 15] / max(A, B, 1), 0, 1)
return round(output)
def or_gate(self, A, B):
"""Implements an OR gate using heat flow"""
self.apply_vortex(10, 10, A)
self.apply_vortex(20, 20, B)
# OR logic: If either has heat, the output is 1
output = np.clip((self.T[15, 15] + self.T[25, 25]) / 2, 0, 1)
return round(output)
def and_gate(self, A, B):
"""Implements an AND gate using vortex interactions"""
self.apply_vortex(10, 10, A)
self.apply_vortex(20, 20, B)
# AND logic: If both have heat, the output is high
output = np.clip((self.T[15, 15] * self.T[25, 25]) / 2, 0, 1)
return round(output)
def visualize(self):
"""Plot the heatmap for logic gate processing"""
plt.imshow(self.T, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.show()
class HeatCompiler:
def __init__(self):
self.heat_logic = HeatLogicGates()
def parse_instruction(self, instruction):
"""Parses a single instruction and executes it"""
parts = instruction.strip().split()
if parts[0] == "LOAD":
self.heat_logic.apply_vortex(int(parts[1]), int(parts[2]), float(parts[3]))
elif parts[0] == "NAND":
return self.heat_logic.nand_gate(int(parts[1]), int(parts[2]))
elif parts[0] == "OR":
return self.heat_logic.or_gate(int(parts[1]), int(parts[2]))
elif parts[0] == "AND":
return self.heat_logic.and_gate(int(parts[1]), int(parts[2]))
elif parts[0] == "READ":
x, y = int(parts[1]), int(parts[2])
return self.heat_logic.T[x, y]
else:
raise ValueError(f"Unknown instruction: {instruction}")
def run_program(self, program):
"""Executes a list of instructions"""
results = []
for instruction in program:
result = self.parse_instruction(instruction)
if result is not None:
results.append(result)
self.heat_logic.visualize()
return results
# Example program
heat_program = [
"LOAD 10 10 1.0",
"LOAD 20 20 1.0",
"NAND 1 1",
"OR 0 1",
"AND 1 1"
]
compiler = HeatCompiler()
results = compiler.run_program(heat_program)
print("Program Results:", results)
# Example NAND, OR, AND Gate Execution
logic = HeatLogicGates()
print(f"NAND(1,1): {logic.nand_gate(1, 1)}")
print(f"OR(0,1): {logic.or_gate(0, 1)}")
print(f"AND(1,1): {logic.and_gate(1, 1)}")
logic.visualize()
import numpy as np
import pickle
import os
class HeatMemory:
def __init__(self, grid_size=10, memory_file="heat_memory.pkl"):
self.grid_size = grid_size
self.memory_file = memory_file
self.T = np.zeros((grid_size, grid_size)) # Memory initialized to zero
# Load previous memory state if available
if os.path.exists(memory_file):
with open(memory_file, "rb") as f:
self.T = pickle.load(f)
print("[INFO] Loaded previous memory state.")
def write(self, x, y, value):
"""Writes a heat value (0 or 1) to memory."""
if 0 <= x < self.grid_size and 0 <= y < self.grid_size:
self.T[x, y] = value
print(f"[MEMORY WRITE] ({x}, {y}) = {value}")
else:
print("[ERROR] Memory address out of bounds!")
def read(self, x, y):
"""Reads the stored heat value."""
if 0 <= x < self.grid_size and 0 <= y < self.grid_size:
value = self.T[x, y]
print(f"[MEMORY READ] ({x}, {y}) = {value}")
return value
else:
print("[ERROR] Memory address out of bounds!")
return None
def save(self):
"""Saves the memory state persistently."""
with open(self.memory_file, "wb") as f:
pickle.dump(self.T, f)
print("[INFO] Memory state saved.")
def display(self):
"""Visualize the memory storage as a heatmap."""
import matplotlib.pyplot as plt
plt.imshow(self.T, cmap="hot", interpolation="nearest")
plt.colorbar()
plt.show()
if __name__ == "__main__":
memory = HeatMemory()
# Write some data
memory.write(2, 3, 1)
memory.write(5, 5, 1)
# Read values
memory.read(2, 3)
memory.read(5, 5)
# Save memory state
memory.save()
# Display memory
memory.display()
import time
from heat_memory import HeatMemory
from heat_full_adder import HeatFullAdder
class HeatScheduler:
def __init__(self):
self.memory = HeatMemory(grid_size=10)
self.cpu = HeatFullAdder()
self.queue = []
def add_process(self, process):
"""Adds a heat-based program to the execution queue"""
self.queue.append(process)
def execute_process(self, process):
"""Executes a heat-based program"""
print(f"🔥 Executing: {process['name']}")
if process["type"] == "addition":
result = self.cpu.multi_bit_adder(process["A"], process["B"])
print(f"Result of Addition: {result}")
elif process["type"] == "memory_write":
x, y, value = process["x"], process["y"], process["value"]
self.memory.write(x, y, value)
elif process["type"] == "memory_read":
x, y = process["x"], process["y"]
self.memory.read(x, y)
time.sleep(1) # Simulate execution time
def run(self):
"""Runs the Heat OS scheduler loop"""
while self.queue:
process = self.queue.pop(0)
self.execute_process(process)
print("🔥 All processes completed.")
if __name__ == "__main__":
scheduler = HeatScheduler()
# Sample heat-based processes
scheduler.add_process({"name": "Heat Addition", "type": "addition", "A": [1, 0, 1], "B": [1, 1, 0]})
scheduler.add_process({"name": "Store in Memory", "type": "memory_write", "x": 3, "y": 3, "value": 1})
scheduler.add_process({"name": "Read from Memory", "type": "memory_read", "x": 3, "y": 3})
scheduler.run()
import matplotlib
matplotlib.use("Agg") # Use a backend that works in headless environments
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from heat_memory import HeatMemory
from heat_kernel import HeatLogicGates
class HeatVisualizer:
def __init__(self, grid_size=10, steps=50):
self.grid_size = grid_size
self.steps = steps
self.memory = HeatMemory(grid_size=grid_size)
self.logic = HeatLogicGates()
# Initialize heat grid
self.heat_grid = np.zeros((grid_size, grid_size))
# Create the plot
self.fig, self.ax = plt.subplots()
self.heatmap = self.ax.imshow(self.heat_grid, cmap='hot', interpolation='nearest')
def update_heatmap(self, frame):
"""Simulates heat diffusion and updates the heatmap"""
for i in range(self.grid_size):
for j in range(self.grid_size):
if frame % 10 == 0 and i == self.grid_size // 2 and j == self.grid_size // 2:
self.memory.write(i, j, 1)
if self.heat_grid[i, j] > 0:
self.heat_grid[i, j] *= 0.95 # Simulated cooling effect
for i in range(self.grid_size):
for j in range(self.grid_size):
self.heat_grid[i, j] = self.memory.read(i, j)
self.heatmap.set_data(self.heat_grid)
return [self.heatmap]
def run(self):
"""Runs the real-time heatmap animation and saves it"""
self.ani = animation.FuncAnimation(self.fig, self.update_heatmap, frames=self.steps, interval=100, blit=False)
self.ani.save("/heatvm/heat_visualization.mp4", fps=10, extra_args=['-vcodec', 'libx264']) # Save as a video
print("🔥 Animation saved as heat_visualization.mp4")
if __name__ == "__main__":
visualizer = HeatVisualizer(grid_size=10, steps=100)
visualizer.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment