arco 0.2.1

Automated Research into Computational Ontologies — a platform for discovering the conditions under which computation emerges
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! State trait and BinaryGraphState implementation.
//!
//! Per Constitution:
//!     A state space S is a set equipped with a canonical encoding function,
//!     a distance function, and a cardinality bound. States must be
//!     distinguishable via observation operators.

use bincode::Encode;
use rand::{Rng, RngExt};
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::fmt::{self, Debug, Write};
use std::hash::{Hash, Hasher};

// ===================================================================
// State trait
// ===================================================================

/// Trait for states in an Information Universe.
///
/// A state must provide:
/// - A **canonical encoding** that uniquely and deterministically identifies it
/// - A **distance metric** satisfying identity, symmetry, and triangle inequality
/// - **Mutation methods** that return new states rather than modifying in place
///
/// # Design contract
///
/// States are immutable. All mutation methods return new state objects.
/// The canonical encoding must be independent of runtime state (e.g., RNG seed,
/// memory address) and identical across runs.
pub trait State: Clone + Eq + Hash + Send + Sync + Serialize {
    /// The type of the canonical encoding.
    /// Must be hashable, comparable, and serializable.
    type Encoding: Clone + Eq + Hash + Send + Sync + Serialize + Debug + Encode;

    /// Return a deterministic, unique encoding of the complete state.
    ///
    /// This is the identity observation — the maximally dynamically
    /// sufficient observation operator (Arco Constitution).
    fn canonical_encoding(&self) -> Self::Encoding;

    /// Hamming distance between this state and another.
    ///
    /// Returns the number of bits that differ between the two states.
    /// Must satisfy the metric axioms: identity, symmetry, triangle inequality.
    fn distance(&self, other: &Self) -> u32;

    /// Return a stable digest of the state (SHA-256 of the canonical encoding).
    ///
    /// Useful for caching, distributed search, and cross-run reproducibility.
    /// Unlike Rust's default Hash, this is deterministic across runs.
    fn stable_digest(&self) -> String {
        let encoding = self.canonical_encoding();
        let bytes = bincode::encode_to_vec(&encoding, bincode::config::standard())
            .unwrap_or_else(|_| format!("{:?}", encoding).into_bytes());
        let hash = Sha256::digest(&bytes);
        let mut hex = String::new();
        for byte in hash.as_slice() {
            write!(&mut hex, "{:02x}", byte).unwrap();
        }
        hex
    }
}

// ===================================================================
// BinaryGraphState
// ===================================================================

/// A state in a graph-based Information Universe.
///
/// Represents a directed graph with `n` vertices, each vertex labeled
/// `{0, 1}`, each directed edge labeled `{0, 1}`.
///
/// # Encoding
///
/// The canonical encoding is `(adj_flat, labels)` where `adj_flat` is a
/// flattened adjacency matrix (length n²) and `labels` is the vertex label
/// vector (length n). Both are `Vec<u8>` with entries in `{0, 1}`.
///
/// # Vertex-order dependence
///
/// States are **vertex-order dependent**. Two isomorphic graphs with
/// permuted vertex labels are distinct states. Canonical graph isomorphism
/// reduction is deferred to the equivalence layer (Arco Constitution).
///
/// # Examples
///
/// ```
/// use ndarray::{arr2, arr1};
/// use arco::state::BinaryGraphState;
///
/// let adj = arr2(&[[0, 1], [0, 0]]);
/// let labels = arr1(&[1, 0]);
/// let state = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
///
/// assert_eq!(state.n_vertices(), 2);
/// assert_eq!(state.label(0), 1);
/// assert_eq!(state.edge(0, 1), 1);
/// ```
#[derive(Clone, Serialize, Encode)]
pub struct BinaryGraphState {
    /// Number of vertices.
    n: usize,
    /// Flattened adjacency matrix, length n*n, entries in {0, 1}.
    adj_flat: Vec<u8>,
    /// Vertex labels, length n, entries in {0, 1}.
    labels: Vec<u8>,
}

impl BinaryGraphState {
    /// Create a new BinaryGraphState with full validation.
    ///
    /// # Arguments
    /// * `n_vertices` — Number of vertices.
    /// * `adj_matrix` — Adjacency matrix of shape (n, n), entries in {0, 1}.
    /// * `vertex_labels` — Vertex labels of shape (n,), entries in {0, 1}.
    ///
    /// # Errors
    /// Returns `Err` if shapes are incorrect or entries are not in {0, 1}.
    pub fn new(
        n_vertices: usize,
        adj_matrix: ndarray::ArrayView2<'_, i8>,
        vertex_labels: ndarray::ArrayView1<'_, i8>,
    ) -> Result<Self, StateError> {
        // Shape validation
        if adj_matrix.shape() != [n_vertices, n_vertices] {
            return Err(StateError::InvalidShape {
                expected: (n_vertices, n_vertices),
                got: (adj_matrix.shape()[0], adj_matrix.shape()[1]),
            });
        }
        if vertex_labels.len() != n_vertices {
            return Err(StateError::InvalidLength {
                expected: n_vertices,
                got: vertex_labels.len(),
            });
        }

        // Binary value validation
        for &val in adj_matrix.iter() {
            if val != 0 && val != 1 {
                return Err(StateError::InvalidValue {
                    context: "adjacency matrix",
                    value: val as i64,
                });
            }
        }
        for &val in vertex_labels.iter() {
            if val != 0 && val != 1 {
                return Err(StateError::InvalidValue {
                    context: "vertex labels",
                    value: val as i64,
                });
            }
        }

        Ok(Self {
            n: n_vertices,
            adj_flat: adj_matrix.iter().map(|&x| x as u8).collect(),
            labels: vertex_labels.iter().map(|&x| x as u8).collect(),
        })
    }

    /// Create a state from already-validated internal data.
    ///
    /// Bypasses validation for performance. Only call with data known to be
    /// valid (e.g., from mutation methods that preserve binary constraints).
    pub(crate) fn from_internal(n_vertices: usize, adj_flat: Vec<u8>, labels: Vec<u8>) -> Self {
        debug_assert_eq!(adj_flat.len(), n_vertices * n_vertices);
        debug_assert_eq!(labels.len(), n_vertices);
        debug_assert!(adj_flat.iter().all(|&x| x <= 1));
        debug_assert!(labels.iter().all(|&x| x <= 1));

        Self {
            n: n_vertices,
            adj_flat,
            labels,
        }
    }

    // --- Accessors ---

    /// Number of vertices.
    pub fn n_vertices(&self) -> usize {
        self.n
    }

    /// Label of a vertex.
    pub fn label(&self, vertex: usize) -> u8 {
        self.labels[vertex]
    }

    /// Edge value from `src` to `dst`.
    pub fn edge(&self, src: usize, dst: usize) -> u8 {
        self.adj_flat[src * self.n + dst]
    }

    /// Total number of edges (sum of adjacency matrix entries).
    pub fn edge_count(&self) -> usize {
        self.adj_flat.iter().filter(|&&x| x == 1).count()
    }

    /// Sum of vertex labels.
    pub fn label_sum(&self) -> usize {
        self.labels.iter().filter(|&&x| x == 1).count()
    }

    // --- Mutation methods ---

    /// Return a new state with one vertex label changed.
    pub fn mutate_label(&self, vertex: usize, value: u8) -> Result<Self, StateError> {
        if vertex >= self.n {
            return Err(StateError::IndexOutOfRange {
                index: vertex,
                max: self.n,
            });
        }
        if value > 1 {
            return Err(StateError::InvalidValue {
                context: "label",
                value: value as i64,
            });
        }

        let mut new_labels = self.labels.clone();
        new_labels[vertex] = value;
        Ok(Self::from_internal(
            self.n,
            self.adj_flat.clone(),
            new_labels,
        ))
    }

    /// Return a new state with all vertex labels replaced.
    pub fn mutate_labels(&self, new_labels: &[u8]) -> Result<Self, StateError> {
        if new_labels.len() != self.n {
            return Err(StateError::InvalidLength {
                expected: self.n,
                got: new_labels.len(),
            });
        }
        if !new_labels.iter().all(|&x| x <= 1) {
            return Err(StateError::InvalidValue {
                context: "labels",
                value: -1, // sentinel
            });
        }

        Ok(Self::from_internal(
            self.n,
            self.adj_flat.clone(),
            new_labels.to_vec(),
        ))
    }

    /// Return a new state with one edge changed.
    pub fn mutate_adj(&self, src: usize, dst: usize, value: u8) -> Result<Self, StateError> {
        if src >= self.n || dst >= self.n {
            return Err(StateError::IndexOutOfRange {
                index: src.max(dst),
                max: self.n,
            });
        }
        if value > 1 {
            return Err(StateError::InvalidValue {
                context: "edge",
                value: value as i64,
            });
        }

        let mut new_adj = self.adj_flat.clone();
        new_adj[src * self.n + dst] = value;
        Ok(Self::from_internal(self.n, new_adj, self.labels.clone()))
    }

    // --- Random generation ---

    /// Generate a random state with the given number of vertices.
    pub fn random(n_vertices: usize, rng: &mut impl Rng) -> Self {
        let n_edges = n_vertices * n_vertices;
        let adj_flat: Vec<u8> = (0..n_edges).map(|_| rng.random_range(0..=1)).collect();
        let labels: Vec<u8> = (0..n_vertices).map(|_| rng.random_range(0..=1)).collect();
        Self::from_internal(n_vertices, adj_flat, labels)
    }
}

// ===================================================================
// Trait implementations
// ===================================================================

impl State for BinaryGraphState {
    type Encoding = (Vec<u8>, Vec<u8>);

    fn canonical_encoding(&self) -> Self::Encoding {
        (self.adj_flat.clone(), self.labels.clone())
    }

    fn distance(&self, other: &Self) -> u32 {
        if self.n != other.n {
            panic!(
                "Cannot compute distance between states with different vertex counts: {} vs {}",
                self.n, other.n
            );
        }

        let mut diff: u32 = 0;
        for (a, b) in self.adj_flat.iter().zip(other.adj_flat.iter()) {
            if a != b {
                diff += 1;
            }
        }
        for (a, b) in self.labels.iter().zip(other.labels.iter()) {
            if a != b {
                diff += 1;
            }
        }
        diff
    }
}

impl PartialEq for BinaryGraphState {
    fn eq(&self, other: &Self) -> bool {
        self.n == other.n && self.adj_flat == other.adj_flat && self.labels == other.labels
    }
}

impl Eq for BinaryGraphState {}

impl Hash for BinaryGraphState {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.n.hash(state);
        self.adj_flat.hash(state);
        self.labels.hash(state);
    }
}

impl fmt::Debug for BinaryGraphState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "BinaryGraphState(n={}, labels={:?}, edges={})",
            self.n,
            self.labels,
            self.edge_count()
        )
    }
}

impl fmt::Display for BinaryGraphState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

// ===================================================================
// Error type
// ===================================================================

/// Errors that can occur when creating or mutating a state.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum StateError {
    #[error("invalid shape: expected {expected:?}, got {got:?}")]
    InvalidShape {
        expected: (usize, usize),
        got: (usize, usize),
    },

    #[error("invalid length: expected {expected}, got {got}")]
    InvalidLength { expected: usize, got: usize },

    #[error("invalid value in {context}: {value}")]
    InvalidValue { context: &'static str, value: i64 },

    #[error("index {index} out of range [0, {max})")]
    IndexOutOfRange { index: usize, max: usize },
}

// ===================================================================
// Tests
// ===================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::{arr1, arr2};
    use rand::SeedableRng;

    #[test]
    fn test_new_valid_state() {
        let adj = arr2(&[[0, 1], [0, 0]]);
        let labels = arr1(&[1, 0]);
        let state = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        assert_eq!(state.n_vertices(), 2);
        assert_eq!(state.label(0), 1);
        assert_eq!(state.label(1), 0);
        assert_eq!(state.edge(0, 1), 1);
        assert_eq!(state.edge(1, 0), 0);
    }

    #[test]
    fn test_new_invalid_shape() {
        let adj = arr2(&[[0, 1]]); // wrong shape
        let labels = arr1(&[1, 0]);
        let result = BinaryGraphState::new(2, adj.view(), labels.view());
        assert!(result.is_err());
    }

    #[test]
    fn test_new_invalid_values() {
        let adj = arr2(&[[0, 2], [0, 0]]); // 2 is invalid
        let labels = arr1(&[1, 0]);
        let result = BinaryGraphState::new(2, adj.view(), labels.view());
        assert!(result.is_err());
    }

    #[test]
    fn test_canonical_encoding_deterministic() {
        let adj = arr2(&[[1, 0], [0, 1]]);
        let labels = arr1(&[0, 1]);
        let state = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        let enc1 = state.canonical_encoding();
        let enc2 = state.canonical_encoding();
        assert_eq!(enc1, enc2);
    }

    #[test]
    fn test_distance_same_state_is_zero() {
        let adj = arr2(&[[0, 0], [0, 0]]);
        let labels = arr1(&[0, 0]);
        let s1 = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        let s2 = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        assert_eq!(s1.distance(&s2), 0);
    }

    #[test]
    fn test_distance_different_labels() {
        let adj = arr2(&[[0, 0], [0, 0]]);
        let s1 = BinaryGraphState::new(2, adj.view(), arr1(&[0, 0]).view()).unwrap();
        let s2 = BinaryGraphState::new(2, adj.view(), arr1(&[1, 0]).view()).unwrap();
        assert_eq!(s1.distance(&s2), 1);
    }

    #[test]
    fn test_mutate_label() {
        let adj = arr2(&[[0, 0], [0, 0]]);
        let labels = arr1(&[0, 0]);
        let state = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        let new_state = state.mutate_label(0, 1).unwrap();
        assert_eq!(new_state.label(0), 1);
        // Original unchanged
        assert_eq!(state.label(0), 0);
    }

    #[test]
    fn test_stable_digest_deterministic() {
        let adj = arr2(&[[1, 0], [0, 1]]);
        let labels = arr1(&[0, 1]);
        let state = BinaryGraphState::new(2, adj.view(), labels.view()).unwrap();
        let d1 = state.stable_digest();
        let d2 = state.stable_digest();
        assert_eq!(d1, d2);
    }

    #[test]
    fn test_stable_digest_different_for_different_states() {
        let adj = arr2(&[[0, 0], [0, 0]]);
        let s1 = BinaryGraphState::new(2, adj.view(), arr1(&[0, 0]).view()).unwrap();
        let s2 = BinaryGraphState::new(2, adj.view(), arr1(&[1, 0]).view()).unwrap();
        assert_ne!(s1.stable_digest(), s2.stable_digest());
    }

    #[test]
    fn test_random_state_generation() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let state = BinaryGraphState::random(3, &mut rng);
        assert_eq!(state.n_vertices(), 3);
        // All labels should be 0 or 1
        for i in 0..3 {
            assert!(state.label(i) <= 1);
        }
        // All edges should be 0 or 1
        for i in 0..3 {
            for j in 0..3 {
                assert!(state.edge(i, j) <= 1);
            }
        }
    }
}