snow_spike / examples /integrated_example.py
psikosen's picture
Add files using upload-large-folder tool
1e12712 verified
Raw History Blame Contribute Delete
11.2 kB
"""
Integrated example showing the complete workflow using all modules.
"""
from src.entropy import (
count_spike_occurrences, calculate_empirical_probabilities,
compute_neuron_entropy, aggregate_network_entropy
)
from src.normalization import (
normalize_logic_check, normalize_cross_check, normalize_corroboration_signal,
calculate_trust_delta
)
from src.decay import (
apply_continuous_decay, DecayManager
)
from src.utils.common import (
SpikeState, CrossCheckType, DecayStrategy
)
import numpy as np
import time
import json
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
class NetworkSimulation:
"""
Simulation of a neural network with trust score calculation and decay.
"""
def __init__(self, config_path=None):
"""Initialize the simulation."""
# Load configuration
self.config = {
"neurons": 10,
"batch_size": 100,
"normalization": {
"corroboration": {"kappa": 0.5},
"weights": {"logic_check": 0.3, "cross_check": 0.4, "corroboration": 0.3}
},
"decay": {
"strategy": "CONTINUOUS_ON_READ",
"lambda": 0.01
}
}
if config_path:
try:
with open(config_path, 'r') as f:
self.config.update(json.load(f))
except Exception as e:
print(f"Warning: Could not load config from {config_path}: {e}")
# Initialize components
self.decay_manager = DecayManager(
strategy=DecayStrategy[self.config["decay"]["strategy"]],
decay_lambda=self.config["decay"]["lambda"]
)
# Initialize trust scores
self.trust_scores = {}
self.last_updated = {}
def generate_spike_data(self, distribution_type="random"):
"""Generate spike data based on the specified distribution."""
neurons = self.config["neurons"]
batch_size = self.config["batch_size"]
spike_data = []
for i in range(neurons):
if distribution_type == "uniform":
# Equal probability for all states
probs = [1/3, 1/3, 1/3]
elif distribution_type == "neutral":
# Mostly neutral
probs = [0.1, 0.8, 0.1]
elif distribution_type == "positive":
# Mostly positive
probs = [0.1, 0.2, 0.7]
elif distribution_type == "negative":
# Mostly negative
probs = [0.7, 0.2, 0.1]
elif distribution_type == "random":
# Random distribution
probs = np.random.dirichlet(np.ones(3))
else:
raise ValueError(f"Unknown distribution type: {distribution_type}")
# Generate spikes based on probabilities
spikes = np.random.choice([-1, 0, 1], size=batch_size, p=probs)
spike_data.append(spikes.tolist())
return spike_data
def calculate_entropy(self, spike_data):
"""Calculate entropy for the given spike data."""
neurons = len(spike_data)
batch_size = len(spike_data[0])
entropies = []
for i in range(neurons):
# Count spike occurrences
counts = count_spike_occurrences(i, spike_data[i], batch_size)
# Calculate probabilities
epsilon = 1e-9
probabilities = calculate_empirical_probabilities(counts, batch_size, epsilon)
# Compute entropy
entropy = compute_neuron_entropy(probabilities)
entropies.append(entropy)
# Aggregate entropy
network_entropy = aggregate_network_entropy(entropies)
return network_entropy, entropies
def calculate_trust_update(self, neuron_id, logic_check, cross_check, num_corroborators):
"""Calculate trust update for a neuron."""
# Normalize signals
L = normalize_logic_check(logic_check)
C = normalize_cross_check(
cross_check, CrossCheckType.COSINE_SIMILARITY
)
kappa = self.config["normalization"]["corroboration"]["kappa"]
R = normalize_corroboration_signal(num_corroborators, kappa)
# Get weights
alpha = self.config["normalization"]["weights"]["logic_check"]
beta = self.config["normalization"]["weights"]["cross_check"]
gamma = self.config["normalization"]["weights"]["corroboration"]
# Calculate trust delta
delta_t = calculate_trust_delta(L, C, R, alpha, beta, gamma)
return delta_t
def update_trust_score(self, neuron_id, delta_t):
"""Update trust score for a neuron."""
current_time = time.time()
# Get current trust score
if neuron_id in self.trust_scores:
# Apply decay
old_score = self.trust_scores[neuron_id]
old_timestamp = self.last_updated[neuron_id]
decayed_score = self.decay_manager.decay_value(
old_score, old_timestamp, current_time
)
else:
# Initialize
decayed_score = 0.0
# Update with new delta
new_score = min(1.0, decayed_score + delta_t)
# Store
self.trust_scores[neuron_id] = new_score
self.last_updated[neuron_id] = current_time
return new_score, decayed_score
def run_simulation(self, steps=10, distribution_type="random"):
"""Run the simulation for a number of steps."""
results = {
"entropy": [],
"trust_scores": [],
"deltas": []
}
for step in range(steps):
print(f"Simulation step {step+1}/{steps}")
# Generate spike data
spike_data = self.generate_spike_data(distribution_type)
# Calculate entropy
network_entropy, neuron_entropies = self.calculate_entropy(spike_data)
results["entropy"].append((step, network_entropy))
# For each neuron
step_trust_scores = []
step_deltas = []
for i in range(self.config["neurons"]):
# Simulate logic check (binary signal)
logic_check = np.random.choice([0, 1])
# Simulate cross-check (cosine similarity)
cross_check = np.random.uniform(-1, 1)
# Simulate corroborators
num_corroborators = np.random.randint(0, 10)
# Calculate trust update
delta_t = self.calculate_trust_update(
i, logic_check, cross_check, num_corroborators
)
# Update trust score
new_score, old_score = self.update_trust_score(i, delta_t)
step_trust_scores.append((i, new_score))
step_deltas.append((i, delta_t))
results["trust_scores"].append((step, step_trust_scores))
results["deltas"].append((step, step_deltas))
# Let some time pass for decay to have an effect
time.sleep(0.1)
return results
def visualize_results(self, results):
"""Visualize simulation results."""
try:
plt.figure(figsize=(15, 10))
# Plot 1: Network entropy over time
plt.subplot(2, 2, 1)
steps, entropies = zip(*results["entropy"])
plt.plot(steps, entropies)
plt.xlabel('Simulation Step')
plt.ylabel('Network Entropy')
plt.title('Network Entropy Over Time')
plt.grid(True)
# Plot 2: Trust scores over time
plt.subplot(2, 2, 2)
neurons = self.config["neurons"]
# Extract trust scores for each neuron
neuron_scores = [[] for _ in range(neurons)]
sim_steps = []
for step, scores in results["trust_scores"]:
sim_steps.append(step)
for neuron_id, score in scores:
neuron_scores[neuron_id].append(score)
# Plot for each neuron
for i in range(neurons):
plt.plot(sim_steps, neuron_scores[i], label=f'Neuron {i}')
plt.xlabel('Simulation Step')
plt.ylabel('Trust Score')
plt.title('Trust Scores Over Time')
plt.legend()
plt.grid(True)
# Plot 3: Trust deltas over time
plt.subplot(2, 2, 3)
# Extract deltas for each neuron
neuron_deltas = [[] for _ in range(neurons)]
for step, deltas in results["deltas"]:
for neuron_id, delta in deltas:
neuron_deltas[neuron_id].append(delta)
# Plot for each neuron
for i in range(neurons):
plt.plot(sim_steps, neuron_deltas[i], label=f'Neuron {i}')
plt.xlabel('Simulation Step')
plt.ylabel('Trust Delta')
plt.title('Trust Updates Over Time')
plt.legend()
plt.grid(True)
# Plot 4: Trust score distribution (final)
plt.subplot(2, 2, 4)
# Get final trust scores
final_scores = [score for neuron_id, score in results["trust_scores"][-1][1]]
plt.hist(final_scores, bins=10, alpha=0.7)
plt.xlabel('Trust Score')
plt.ylabel('Number of Neurons')
plt.title('Final Trust Score Distribution')
plt.grid(True)
plt.tight_layout()
plt.savefig('simulation_results.png')
print("\nVisualization saved as 'simulation_results.png'")
except Exception as e:
print(f"\nCould not create visualization: {e}")
def main():
print("Integrated Neural Network Simulation")
print("-----------------------------------")
# Seed for reproducibility
np.random.seed(42)
# Create simulation
sim = NetworkSimulation()
# Run simulation
results = sim.run_simulation(steps=20)
# Display results
max_entropy = np.log(3)
final_entropy = results["entropy"][-1][1]
print(f"\nFinal network entropy: {final_entropy:.4f} ({(final_entropy/max_entropy)*100:.2f}% of max)")
# Get final trust scores
final_scores = [score for neuron_id, score in results["trust_scores"][-1][1]]
avg_trust = np.mean(final_scores)
print(f"Average final trust score: {avg_trust:.4f}")
# Visualize
sim.visualize_results(results)
if __name__ == "__main__":
main()