Skip to content

Instantly share code, notes, and snippets.

@NeoVertex1
Created February 5, 2025 17:20
Show Gist options
  • Save NeoVertex1/4c770ee8196a339ba6d0eef8545ac460 to your computer and use it in GitHub Desktop.
Save NeoVertex1/4c770ee8196a339ba6d0eef8545ac460 to your computer and use it in GitHub Desktop.
import numpy as np
import h5py
import json
import csv
import pickle
from datetime import datetime
import logging
from pathlib import Path
import matplotlib.pyplot as plt
from scipy.integrate import odeint
class HybridPhysicalComputer:
def __init__(self, experiment_name):
self.experiment_name = experiment_name
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.setup_logging()
self.results = {
'light': [],
'vortex': [],
'heat': [],
'combined': []
}
def setup_logging(self):
"""Configure detailed logging system"""
log_dir = Path(f"logs/{self.experiment_name}/{self.timestamp}")
log_dir.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler(log_dir / 'experiment.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
self.log_dir = log_dir
def light_computation(self, input_value, wavelength=632.8e-9):
"""Optical computing using wave interference"""
angle = (input_value / 10) * np.pi / 4
intensity = np.cos(angle)**2
phase = np.exp(1j * 2 * np.pi * input_value * wavelength)
interference = np.abs(phase * np.cos(np.linspace(0, 2*np.pi, 100)))
result = {
'angle': float(angle),
'intensity': float(intensity),
'phase_real': float(phase.real),
'phase_imag': float(phase.imag),
'interference_pattern': interference.tolist()
}
self.results['light'].append(result)
self.logger.info(f"Light computation - Input: {input_value}, Intensity: {intensity:.4f}")
return result
def vortex_computation(self, input_values, grid_size=32):
"""Vortex-based fluid dynamic computation"""
x = np.linspace(-2, 2, grid_size)
y = np.linspace(-2, 2, grid_size)
X, Y = np.meshgrid(x, y)
strength = np.mean(input_values)
psi = strength * np.arctan2(Y, X)
u = -np.gradient(psi, y, axis=0)
v = np.gradient(psi, x, axis=1)
vorticity = np.gradient(v, x, axis=1) - np.gradient(u, y, axis=0)
result = {
'strength': float(strength),
'vorticity': vorticity.tolist(),
'velocity_u': u.tolist(),
'velocity_v': v.tolist(),
'grid_x': X.tolist(),
'grid_y': Y.tolist()
}
self.results['vortex'].append(result)
self.logger.info(f"Vortex computation - Strength: {strength:.4f}")
return result
def heat_computation(self, initial_temp, boundary_temp, timesteps=100):
"""Heat equation solver for computation"""
length = 50
dx = 1.0
dt = 0.5
alpha = 0.1 # thermal diffusivity
temp = np.ones(length) * initial_temp
temp[0] = boundary_temp
temp[-1] = boundary_temp
temp_history = [temp.copy()]
for t in range(timesteps):
temp_new = temp.copy()
for i in range(1, length-1):
temp_new[i] = temp[i] + alpha * dt/(dx**2) * \
(temp[i+1] - 2*temp[i] + temp[i-1])
temp = temp_new
temp_history.append(temp.copy())
result = {
'initial_temp': float(initial_temp),
'boundary_temp': float(boundary_temp),
'temperature_evolution': np.array(temp_history).tolist(),
'final_temperature': temp.tolist()
}
self.results['heat'].append(result)
self.logger.info(f"Heat computation completed - Final avg temp: {np.mean(temp):.4f}")
return result
def hybrid_computation(self, input1, input2, iterations=5):
"""Combined hybrid physical computation"""
light_result = self.light_computation(input1)
vortex_result = self.vortex_computation([input1, input2])
heat_result = self.heat_computation(light_result['intensity'] * 100,
vortex_result['strength'] * 50)
# Combine all effects
current_state = input1
evolution = []
for i in range(iterations):
phase = np.cos(current_state * np.pi / 4)
vortex_effect = phase * np.exp(-i/iterations)
heat_effect = vortex_effect * input2
current_state = (current_state + heat_effect) / 2
evolution.append(float(current_state))
result = {
'input1': float(input1),
'input2': float(input2),
'evolution': evolution,
'final_state': float(current_state)
}
self.results['combined'].append(result)
self.logger.info(f"Hybrid computation completed - Final state: {current_state:.4f}")
return result
def save_results(self):
"""Save results in multiple formats"""
base_path = self.log_dir / 'results'
base_path.mkdir(exist_ok=True)
# Save as NPZ
np.savez(base_path / 'results.npz', **self.results)
# Save as HDF5
with h5py.File(base_path / 'results.h5', 'w') as f:
for key, value in self.results.items():
f.create_dataset(key, data=str(value))
# Save as JSON
with open(base_path / 'results.json', 'w') as f:
json.dump(self.results, f, indent=2)
# Save as Pickle
with open(base_path / 'results.pkl', 'wb') as f:
pickle.dump(self.results, f)
# Save summaries as CSV
with open(base_path / 'summary.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Experiment', 'Timestamp', 'Type', 'Result'])
for comp_type, results in self.results.items():
for result in results:
writer.writerow([self.experiment_name, self.timestamp,
comp_type, str(result)])
self.logger.info(f"Results saved to {base_path}")
# Example usage:
computer = HybridPhysicalComputer("quantum_vortex_test")
# Run some computations
light_result = computer.light_computation(3.0)
vortex_result = computer.vortex_computation([3.0, 4.0])
heat_result = computer.heat_computation(100, 0)
hybrid_result = computer.hybrid_computation(3.0, 4.0)
# Save all results
computer.save_results()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment