consciousness_experiments 2.0.0

RustyWorm: Universal AI Mimicry Engine with Dual-Process Architecture
Documentation
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Physics-Grounded Ising Empathy Module (Rust)
// Companion to ising_empathy_module.py
// Implements empathy as coupling-mediated state correlation

#[derive(Clone, Debug)]
pub struct EmotionVector {
    pub valence: f64,   // Energy-based affect (positive/negative)
    pub arousal: f64,   // Order-based activation (calm/excited)
    pub tension: f64,   // Frustration level
    pub coherence: f64, // Internal alignment (magnetization magnitude)
}

impl EmotionVector {
    pub fn new(valence: f64, arousal: f64, tension: f64, coherence: f64) -> Self {
        EmotionVector {
            valence,
            arousal,
            tension,
            coherence,
        }
    }

    pub fn zero() -> Self {
        EmotionVector {
            valence: 0.0,
            arousal: 0.0,
            tension: 0.0,
            coherence: 0.0,
        }
    }
}

#[derive(Clone, Debug)]
pub struct IsingSystem {
    pub n: usize,
    pub spins: Vec<i8>,
    pub coupling: Vec<Vec<f64>>,
    pub field: Vec<f64>,
}

impl IsingSystem {
    pub fn new(n: usize, seed: u64) -> Self {
        use rand::Rng;
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(seed);

        let spins: Vec<i8> = (0..n)
            .map(|_| if rng.gen_bool(0.5) { 1 } else { -1 })
            .collect();

        let mut coupling = vec![vec![0.0; n]; n];
        #[allow(clippy::needless_range_loop)]
        for i in 0..n {
            for j in (i + 1)..n {
                let strength = if (i + j) % 3 == 0 { 1.0 } else { 0.5 };
                coupling[i][j] = strength;
                coupling[j][i] = strength;
            }
        }

        let field: Vec<f64> = (0..n).map(|i| 0.1 * (i as f64 / n as f64 - 0.5)).collect();

        IsingSystem {
            n,
            spins,
            coupling,
            field,
        }
    }

    pub fn energy(&self) -> f64 {
        let mut e = 0.0;
        for i in 0..self.n {
            for j in (i + 1)..self.n {
                e -= self.coupling[i][j] * (self.spins[i] * self.spins[j]) as f64;
            }
        }
        for i in 0..self.n {
            e -= self.field[i] * self.spins[i] as f64;
        }
        e
    }

    pub fn magnetization(&self) -> f64 {
        self.spins.iter().map(|&s| s as f64).sum::<f64>() / self.n as f64
    }

    pub fn frustration(&self) -> f64 {
        let mut frustrated = 0;
        let mut total = 0;
        for i in 0..self.n {
            for j in (i + 1)..self.n {
                if self.coupling[i][j].abs() > 1e-9 {
                    total += 1;
                    let product = ((self.spins[i] * self.spins[j]) as f64) * self.coupling[i][j];
                    if product < 0.0 {
                        frustrated += 1;
                    }
                }
            }
        }
        if total == 0 {
            0.0
        } else {
            frustrated as f64 / total as f64
        }
    }

    pub fn clone_system(&self) -> Self {
        IsingSystem {
            n: self.n,
            spins: self.spins.clone(),
            coupling: self.coupling.clone(),
            field: self.field.clone(),
        }
    }
}

pub struct IsingEmpathyModule {
    pub memory_buffer: Vec<Vec<f64>>, // [valence, arousal, tension, coherence, empathy_score]
    pub memory_pointer: usize,
    pub memory_count: usize,
    pub memory_size: usize,
}

impl IsingEmpathyModule {
    pub fn new(memory_size: usize) -> Self {
        IsingEmpathyModule {
            memory_buffer: vec![vec![0.0; 5]; memory_size],
            memory_pointer: 0,
            memory_count: 0,
            memory_size,
        }
    }

    /// Encode Ising observables to emotion vector (no learned weights)
    pub fn encode_emotion(&self, system: &IsingSystem) -> EmotionVector {
        let e = system.energy();
        let m = system.magnetization();
        let f = system.frustration();
        let n = system.n as f64;

        let valence = (-e / n).tanh();
        let arousal = 1.0 - m.abs();
        let tension = f;
        let coherence = m.abs();

        EmotionVector::new(valence, arousal, tension, coherence)
    }

    /// Simulate other's Hamiltonian to predict ground state
    pub fn simulate_other(
        &self,
        other: &IsingSystem,
        anneal_steps: usize,
        seed: u64,
    ) -> IsingSystem {
        use rand::Rng;
        use rand::SeedableRng;

        let mut sim = IsingSystem::new(other.n, seed);
        sim.coupling = other.coupling.clone();
        sim.field = other.field.clone();

        let mut rng = rand::rngs::StdRng::seed_from_u64(seed);

        for step in 0..anneal_steps {
            let beta = 0.1 * (10.0 * step as f64 / anneal_steps as f64).exp();

            for _ in 0..10 {
                let i = rng.gen_range(0..sim.n);
                let e_before = sim.energy();
                sim.spins[i] *= -1;
                let e_after = sim.energy();
                let delta_e = e_after - e_before;
                let p_accept = (-beta * delta_e).exp().max(0.1 / (1.0 + beta));

                if rng.gen::<f64>() >= p_accept {
                    sim.spins[i] *= -1;
                }
            }
        }

        sim
    }

    /// Measure how well prediction matches actual
    pub fn perspective_accuracy(
        &self,
        predicted: &IsingSystem,
        actual: &IsingSystem,
    ) -> (f64, f64, f64) {
        // State overlap (accounting for Z2 symmetry)
        let match_direct = predicted
            .spins
            .iter()
            .zip(actual.spins.iter())
            .filter(|&(&p, &a)| p == a)
            .count() as f64
            / predicted.n as f64;

        let match_flipped = predicted
            .spins
            .iter()
            .zip(actual.spins.iter())
            .filter(|&(&p, &a)| p == -a)
            .count() as f64
            / predicted.n as f64;

        let state_overlap = match_direct.max(match_flipped);

        // Energy prediction error
        let e_pred = predicted.energy();
        let e_actual = actual.energy();
        let denom = e_actual.abs().max(1.0);
        let energy_error = (e_pred - e_actual).abs() / denom;

        // Magnetization error
        let mag_err = (predicted.magnetization().abs() - actual.magnetization().abs()).abs();

        (state_overlap, energy_error, mag_err)
    }

    /// Coupling similarity (cosine similarity mapped to \[0,1\])
    pub fn coupling_similarity(&self, j1: &[Vec<f64>], j2: &[Vec<f64>]) -> f64 {
        let mut dot = 0.0;
        let mut norm1 = 0.0;
        let mut norm2 = 0.0;
        let n = j1.len();

        for i in 0..n {
            for j in (i + 1)..n {
                dot += j1[i][j] * j2[i][j];
                norm1 += j1[i][j] * j1[i][j];
                norm2 += j2[i][j] * j2[i][j];
            }
        }

        let cos_sim = if norm1 > 0.0 && norm2 > 0.0 {
            dot / (norm1.sqrt() * norm2.sqrt())
        } else {
            0.0
        };

        (cos_sim + 1.0) / 2.0 // Map [-1,1] to [0,1]
    }

    /// Compute physics-grounded empathy score
    pub fn compute_empathy(
        &self,
        self_system: &IsingSystem,
        other_system: &IsingSystem,
        anneal_steps: usize,
        seed: u64,
    ) -> f64 {
        // Simulate other's state
        let predicted = self.simulate_other(other_system, anneal_steps, seed);

        // Perspective accuracy
        let (state_overlap, energy_error, _mag_error) =
            self.perspective_accuracy(&predicted, other_system);

        // Coupling similarity
        let coupling_sim = self.coupling_similarity(&self_system.coupling, &other_system.coupling);

        // Combined empathy score (weighted average)
        (0.4 * state_overlap + 0.3 * (1.0 - energy_error.min(1.0)) + 0.3 * coupling_sim)
            .clamp(0.0, 1.0)
    }

    /// Modify self's coupling based on empathic understanding
    pub fn compassionate_response(
        &self,
        self_system: &mut IsingSystem,
        other_system: &IsingSystem,
        empathy_score: f64,
        coupling_strength: f64,
    ) {
        if empathy_score > 0.5 {
            // High empathy: blend coupling
            let blend = coupling_strength * empathy_score;
            for i in 0..self_system.n {
                for j in 0..self_system.n {
                    self_system.coupling[i][j] = (1.0 - blend) * self_system.coupling[i][j]
                        + blend * other_system.coupling[i][j];
                }
            }
        } else {
            // Low empathy: add thermal noise
            use rand::Rng;
            let temp = 0.1 * (1.0 - empathy_score);
            let mut rng = rand::thread_rng();
            for i in 0..self_system.n {
                if rng.gen::<f64>() < temp {
                    self_system.spins[i] *= -1;
                }
            }
        }
    }

    /// Store emotional state in memory buffer
    pub fn store_memory(&mut self, emotion: &EmotionVector, empathy_score: f64) {
        self.memory_buffer[self.memory_pointer] = vec![
            emotion.valence,
            emotion.arousal,
            emotion.tension,
            emotion.coherence,
            empathy_score,
        ];
        self.memory_pointer = (self.memory_pointer + 1) % self.memory_size;
        self.memory_count = (self.memory_count + 1).min(self.memory_size);
    }

    /// Recall emotional statistics
    pub fn recall_memory(&self) -> (f64, f64, f64, f64, f64, f64) {
        if self.memory_count == 0 {
            return (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
        }

        let mut sum = [0.0; 5];
        for i in 0..self.memory_count {
            for (j, s) in sum.iter_mut().enumerate() {
                *s += self.memory_buffer[i][j];
            }
        }

        let count = self.memory_count as f64;
        let avg_valence = sum[0] / count;
        let avg_arousal = sum[1] / count;
        let avg_tension = sum[2] / count;
        let avg_coherence = sum[3] / count;
        let avg_empathy = sum[4] / count;

        // Empathy trend
        let trend = if self.memory_count >= 4 {
            let half = self.memory_count / 2;
            let recent_avg: f64 = (half..self.memory_count)
                .map(|i| self.memory_buffer[i][4])
                .sum::<f64>()
                / (self.memory_count - half) as f64;
            let older_avg: f64 =
                (0..half).map(|i| self.memory_buffer[i][4]).sum::<f64>() / half as f64;
            recent_avg - older_avg
        } else {
            0.0
        };

        (
            avg_valence,
            avg_arousal,
            avg_tension,
            avg_coherence,
            avg_empathy,
            trend,
        )
    }

    /// Multi-agent social attention
    pub fn social_attention(
        &mut self,
        self_system: &IsingSystem,
        others: &[IsingSystem],
    ) -> Vec<f64> {
        let mut empathy_scores = Vec::new();

        for (idx, other) in others.iter().enumerate() {
            let empathy = self.compute_empathy(self_system, other, 80, 7777 + idx as u64);
            empathy_scores.push(empathy);
        }

        // Normalize to attention weights
        let total: f64 = empathy_scores.iter().sum();
        if total > 1e-9 {
            empathy_scores.iter().map(|&e| e / total).collect()
        } else {
            vec![1.0 / empathy_scores.len() as f64; empathy_scores.len()]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_emotion_encoding() {
        let sys = IsingSystem::new(20, 42);
        let module = IsingEmpathyModule::new(32);
        let emo = module.encode_emotion(&sys);

        assert!(emo.valence >= -1.0 && emo.valence <= 1.0);
        assert!(emo.arousal >= 0.0 && emo.arousal <= 1.0);
        assert!(emo.tension >= 0.0 && emo.tension <= 1.0);
        assert!(emo.coherence >= 0.0 && emo.coherence <= 1.0);
    }

    #[test]
    fn test_energy_conservation() {
        let sys = IsingSystem::new(20, 42);
        let e1 = sys.energy();
        let e2 = sys.energy();
        assert!((e1 - e2).abs() < 1e-10);
    }

    #[test]
    fn test_coupling_similarity() {
        let sys1 = IsingSystem::new(20, 42);
        let sys2 = IsingSystem::new(20, 42);
        let module = IsingEmpathyModule::new(32);

        let sim = module.coupling_similarity(&sys1.coupling, &sys2.coupling);
        assert!((sim - 1.0).abs() < 1e-6); // Same seed => same coupling
    }

    #[test]
    fn test_memory_storage() {
        let mut module = IsingEmpathyModule::new(16);
        for i in 0..10 {
            let emo =
                EmotionVector::new(0.1 * i as f64, 1.0 - 0.1 * i as f64, 0.05, 0.1 * i as f64);
            module.store_memory(&emo, 0.1 * i as f64);
        }

        let (_v, _a, _t, _c, avg_emp, trend) = module.recall_memory();
        assert!(trend > 0.0); // Increasing empathy
    }
}