oxiz-proof 0.2.2

Proof generation and checking for OxiZ SMT solver
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
//! Proof diffing utilities for comparing two proofs.

use crate::proof::{Proof, ProofNodeId, ProofStep};
use std::fmt;

/// Represents a difference between two proofs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProofDiff {
    /// Node exists only in the first proof
    OnlyInFirst(ProofNodeId, String),
    /// Node exists only in the second proof
    OnlyInSecond(ProofNodeId, String),
    /// Node exists in both but with different steps
    Different {
        id1: ProofNodeId,
        id2: ProofNodeId,
        conclusion1: String,
        conclusion2: String,
    },
    /// Structural difference in proof shape
    StructuralDifference(String),
}

impl fmt::Display for ProofDiff {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProofDiff::OnlyInFirst(id, conclusion) => {
                write!(f, "- [{}] {}", id, conclusion)
            }
            ProofDiff::OnlyInSecond(id, conclusion) => {
                write!(f, "+ [{}] {}", id, conclusion)
            }
            ProofDiff::Different {
                id1,
                id2,
                conclusion1,
                conclusion2,
            } => {
                write!(f, "~ [{}] {} ≠ [{}] {}", id1, conclusion1, id2, conclusion2)
            }
            ProofDiff::StructuralDifference(msg) => {
                write!(f, "! {}", msg)
            }
        }
    }
}

/// Compare two proofs and return their differences.
///
/// This function compares two proofs node-by-node and identifies:
/// - Nodes that exist only in the first proof
/// - Nodes that exist only in the second proof
/// - Nodes with matching IDs but different content
/// - Structural differences
///
/// # Arguments
///
/// * `proof1` - The first proof
/// * `proof2` - The second proof
///
/// # Returns
///
/// A vector of differences found between the proofs
///
/// # Example
///
/// ```
/// use oxiz_proof::proof::Proof;
/// use oxiz_proof::diff::diff_proofs;
///
/// let mut proof1 = Proof::new();
/// proof1.add_axiom("p");
/// proof1.add_axiom("q");
///
/// let mut proof2 = Proof::new();
/// proof2.add_axiom("p");
/// proof2.add_axiom("r");
///
/// let diffs = diff_proofs(&proof1, &proof2);
/// assert!(!diffs.is_empty());
/// ```
pub fn diff_proofs(proof1: &Proof, proof2: &Proof) -> Vec<ProofDiff> {
    let mut diffs = Vec::new();

    // Check for size differences
    if proof1.len() != proof2.len() {
        diffs.push(ProofDiff::StructuralDifference(format!(
            "Size mismatch: {} vs {} nodes",
            proof1.len(),
            proof2.len()
        )));
    }

    // Check for root count differences
    if proof1.roots().len() != proof2.roots().len() {
        diffs.push(ProofDiff::StructuralDifference(format!(
            "Root count mismatch: {} vs {}",
            proof1.roots().len(),
            proof2.roots().len()
        )));
    }

    // Build conclusion maps for both proofs
    let mut conclusions1: std::collections::HashMap<String, ProofNodeId> =
        std::collections::HashMap::new();
    let mut conclusions2: std::collections::HashMap<String, ProofNodeId> =
        std::collections::HashMap::new();

    for node in proof1.nodes() {
        let conclusion = match &node.step {
            ProofStep::Axiom { conclusion } => conclusion.clone(),
            ProofStep::Inference { conclusion, .. } => conclusion.clone(),
        };
        conclusions1.insert(conclusion, node.id);
    }

    for node in proof2.nodes() {
        let conclusion = match &node.step {
            ProofStep::Axiom { conclusion } => conclusion.clone(),
            ProofStep::Inference { conclusion, .. } => conclusion.clone(),
        };
        conclusions2.insert(conclusion, node.id);
    }

    // Find conclusions only in proof1
    for (conclusion, id) in &conclusions1 {
        if !conclusions2.contains_key(conclusion) {
            diffs.push(ProofDiff::OnlyInFirst(*id, conclusion.clone()));
        }
    }

    // Find conclusions only in proof2
    for (conclusion, id) in &conclusions2 {
        if !conclusions1.contains_key(conclusion) {
            diffs.push(ProofDiff::OnlyInSecond(*id, conclusion.clone()));
        }
    }

    diffs
}

/// Compute similarity metrics between two proofs.
#[derive(Debug, Clone, Copy)]
pub struct ProofSimilarity {
    /// Jaccard similarity based on conclusions (0.0 to 1.0)
    pub jaccard_similarity: f64,
    /// Ratio of common nodes to total nodes (0.0 to 1.0)
    pub node_overlap: f64,
    /// Structural similarity based on depth and shape (0.0 to 1.0)
    pub structural_similarity: f64,
}

impl fmt::Display for ProofSimilarity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Proof Similarity Metrics:")?;
        writeln!(
            f,
            "  Jaccard similarity: {:.2}%",
            self.jaccard_similarity * 100.0
        )?;
        writeln!(f, "  Node overlap: {:.2}%", self.node_overlap * 100.0)?;
        writeln!(
            f,
            "  Structural similarity: {:.2}%",
            self.structural_similarity * 100.0
        )
    }
}

/// Compute similarity metrics between two proofs.
///
/// # Arguments
///
/// * `proof1` - The first proof
/// * `proof2` - The second proof
///
/// # Returns
///
/// Similarity metrics comparing the two proofs
pub fn compute_similarity(proof1: &Proof, proof2: &Proof) -> ProofSimilarity {
    // Collect conclusions from both proofs
    let mut conclusions1 = std::collections::HashSet::new();
    let mut conclusions2 = std::collections::HashSet::new();

    for node in proof1.nodes() {
        let conclusion = match &node.step {
            ProofStep::Axiom { conclusion } => conclusion.clone(),
            ProofStep::Inference { conclusion, .. } => conclusion.clone(),
        };
        conclusions1.insert(conclusion);
    }

    for node in proof2.nodes() {
        let conclusion = match &node.step {
            ProofStep::Axiom { conclusion } => conclusion.clone(),
            ProofStep::Inference { conclusion, .. } => conclusion.clone(),
        };
        conclusions2.insert(conclusion);
    }

    // Compute Jaccard similarity
    let intersection = conclusions1.intersection(&conclusions2).count();
    let union = conclusions1.union(&conclusions2).count();
    let jaccard_similarity = if union == 0 {
        1.0
    } else {
        intersection as f64 / union as f64
    };

    // Compute node overlap
    let total_nodes = proof1.len() + proof2.len();
    let node_overlap = if total_nodes == 0 {
        1.0
    } else {
        (2 * intersection) as f64 / total_nodes as f64
    };

    // Compute structural similarity based on depth
    let stats1 = proof1.stats();
    let stats2 = proof2.stats();

    let depth_diff = (stats1.max_depth as f64 - stats2.max_depth as f64).abs();
    let max_depth = stats1.max_depth.max(stats2.max_depth) as f64;
    let depth_similarity = if max_depth == 0.0 {
        1.0
    } else {
        1.0 - (depth_diff / max_depth)
    };

    let root_diff = (stats1.root_count as f64 - stats2.root_count as f64).abs();
    let max_roots = stats1.root_count.max(stats2.root_count) as f64;
    let root_similarity = if max_roots == 0.0 {
        1.0
    } else {
        1.0 - (root_diff / max_roots)
    };

    let structural_similarity = (depth_similarity + root_similarity) / 2.0;

    ProofSimilarity {
        jaccard_similarity,
        node_overlap,
        structural_similarity,
    }
}

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

    #[test]
    fn test_diff_identical_proofs() {
        let mut proof1 = Proof::new();
        proof1.add_axiom("p");
        proof1.add_axiom("q");

        let mut proof2 = Proof::new();
        proof2.add_axiom("p");
        proof2.add_axiom("q");

        let diffs = diff_proofs(&proof1, &proof2);
        // Should have no content differences, only possibly ID differences
        assert!(
            diffs
                .iter()
                .all(|d| matches!(d, ProofDiff::StructuralDifference(_)))
                || diffs.is_empty()
        );
    }

    #[test]
    fn test_diff_different_proofs() {
        let mut proof1 = Proof::new();
        proof1.add_axiom("p");
        proof1.add_axiom("q");

        let mut proof2 = Proof::new();
        proof2.add_axiom("p");
        proof2.add_axiom("r");

        let diffs = diff_proofs(&proof1, &proof2);
        assert!(!diffs.is_empty());
    }

    #[test]
    fn test_similarity_identical() {
        let mut proof1 = Proof::new();
        proof1.add_axiom("p");
        proof1.add_axiom("q");

        let mut proof2 = Proof::new();
        proof2.add_axiom("p");
        proof2.add_axiom("q");

        let sim = compute_similarity(&proof1, &proof2);
        assert_eq!(sim.jaccard_similarity, 1.0);
        assert_eq!(sim.node_overlap, 1.0);
    }

    #[test]
    fn test_similarity_disjoint() {
        let mut proof1 = Proof::new();
        proof1.add_axiom("p");
        proof1.add_axiom("q");

        let mut proof2 = Proof::new();
        proof2.add_axiom("r");
        proof2.add_axiom("s");

        let sim = compute_similarity(&proof1, &proof2);
        assert_eq!(sim.jaccard_similarity, 0.0);
    }

    #[test]
    fn test_similarity_partial_overlap() {
        let mut proof1 = Proof::new();
        proof1.add_axiom("p");
        proof1.add_axiom("q");

        let mut proof2 = Proof::new();
        proof2.add_axiom("p");
        proof2.add_axiom("r");

        let sim = compute_similarity(&proof1, &proof2);
        assert!(sim.jaccard_similarity > 0.0 && sim.jaccard_similarity < 1.0);
    }

    #[test]
    fn test_diff_display() {
        let diff = ProofDiff::OnlyInFirst(ProofNodeId(0), "p".to_string());
        let display = format!("{}", diff);
        assert!(display.contains("p"));
    }

    #[test]
    fn test_similarity_display() {
        let sim = ProofSimilarity {
            jaccard_similarity: 0.75,
            node_overlap: 0.8,
            structural_similarity: 0.9,
        };
        let display = format!("{}", sim);
        assert!(display.contains("75"));
    }

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn prop_similarity_bounds(size in 1usize..20) {
                let mut proof1 = Proof::new();
                let mut proof2 = Proof::new();

                for i in 0..size {
                    proof1.add_axiom(format!("p{}", i));
                    proof2.add_axiom(format!("q{}", i));
                }

                let sim = compute_similarity(&proof1, &proof2);

                // All similarity metrics should be between 0 and 1
                prop_assert!(sim.jaccard_similarity >= 0.0 && sim.jaccard_similarity <= 1.0);
                prop_assert!(sim.node_overlap >= 0.0 && sim.node_overlap <= 1.0);
                prop_assert!(sim.structural_similarity >= 0.0 && sim.structural_similarity <= 1.0);
            }

            #[test]
            fn prop_identical_proofs_similarity(size in 1usize..20) {
                let mut proof1 = Proof::new();
                for i in 0..size {
                    proof1.add_axiom(format!("p{}", i));
                }

                let mut proof2 = Proof::new();
                for i in 0..size {
                    proof2.add_axiom(format!("p{}", i));
                }

                let sim = compute_similarity(&proof1, &proof2);

                // Identical proofs should have perfect similarity
                prop_assert_eq!(sim.jaccard_similarity, 1.0);
                prop_assert_eq!(sim.node_overlap, 1.0);
            }

            #[test]
            fn prop_disjoint_proofs_zero_jaccard(size1 in 1usize..10, size2 in 1usize..10) {
                let mut proof1 = Proof::new();
                for i in 0..size1 {
                    proof1.add_axiom(format!("p{}", i));
                }

                let mut proof2 = Proof::new();
                for i in 0..size2 {
                    proof2.add_axiom(format!("q{}", i));
                }

                let sim = compute_similarity(&proof1, &proof2);

                // Disjoint proofs should have zero Jaccard similarity
                prop_assert_eq!(sim.jaccard_similarity, 0.0);
            }

            #[test]
            fn prop_diff_empty_proofs(_n in 0usize..1) {
                let proof1 = Proof::new();
                let proof2 = Proof::new();

                let diffs = diff_proofs(&proof1, &proof2);

                // Empty proofs should have no differences
                prop_assert!(diffs.is_empty());
            }

            #[test]
            fn prop_diff_self_is_empty(size in 1usize..20) {
                let mut proof = Proof::new();
                for i in 0..size {
                    proof.add_axiom(format!("p{}", i));
                }

                let diffs = diff_proofs(&proof, &proof);

                // A proof compared with itself should only have structural diffs (if any)
                prop_assert!(diffs.iter().all(|d| matches!(d, ProofDiff::StructuralDifference(_))) || diffs.is_empty());
            }

            #[test]
            fn prop_similarity_symmetric(size in 1usize..15) {
                let mut proof1 = Proof::new();
                let mut proof2 = Proof::new();

                for i in 0..size {
                    proof1.add_axiom(format!("p{}", i));
                    if i % 2 == 0 {
                        proof2.add_axiom(format!("p{}", i));
                    } else {
                        proof2.add_axiom(format!("q{}", i));
                    }
                }

                let sim1 = compute_similarity(&proof1, &proof2);
                let sim2 = compute_similarity(&proof2, &proof1);

                // Similarity should be symmetric
                prop_assert_eq!(sim1.jaccard_similarity, sim2.jaccard_similarity);
                prop_assert_eq!(sim1.node_overlap, sim2.node_overlap);
            }
        }
    }
}