File size: 11,186 Bytes
1e12712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""
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()