pumpkin_solver/engine/proof/
mod.rs

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
mod dimacs;
mod proof_literals;

use std::fs::File;
use std::num::NonZero;
use std::num::NonZeroU64;
use std::path::Path;
use std::path::PathBuf;

use drcp_format::writer::ProofWriter;
pub use drcp_format::Format;

use self::dimacs::DimacsProof;
use self::proof_literals::ProofLiterals;
use super::variables::Literal;
use super::VariableLiteralMappings;
use crate::variable_names::VariableNames;
#[cfg(doc)]
use crate::Solver;

/// A proof log which logs the proof steps necessary to prove unsatisfiability or optimality. We
/// allow the following types of proofs:
/// - A CP proof log - This can be created using [`ProofLog::cp`].
/// - A DIMACS proof log - This can be created using [`ProofLog::dimacs`].
///
/// When a proof log should not be generated, use the implementation of [`Default`].
#[derive(Debug, Default)]
pub struct ProofLog {
    internal_proof: Option<ProofImpl>,
}

/// A dummy proof step ID. Used when there is proof logging is not enabled.
// Safety: Unwrapping an option is not stable, so we cannot get a NonZero<T> safely in a const
// context.
const DUMMY_STEP_ID: NonZeroU64 = unsafe { NonZeroU64::new_unchecked(1) };

impl ProofLog {
    /// Create a CP proof logger.
    pub fn cp(
        file_path: &Path,
        format: Format,
        log_inferences: bool,
        log_hints: bool,
    ) -> std::io::Result<ProofLog> {
        let definitions_path = file_path.with_extension("lits");
        let file = File::create(file_path)?;

        let writer = ProofWriter::new(format, file, ProofLiterals::default());

        Ok(ProofLog {
            internal_proof: Some(ProofImpl::CpProof {
                writer,
                log_inferences,
                definitions_path,
                propagation_order_hint: if log_hints { Some(vec![]) } else { None },
            }),
        })
    }

    /// Create a dimacs proof logger.
    pub fn dimacs(file_path: &Path) -> std::io::Result<ProofLog> {
        let file = File::create(file_path)?;
        Ok(ProofLog {
            internal_proof: Some(ProofImpl::DimacsProof(DimacsProof::new(file))),
        })
    }

    /// Log an inference to the proof.
    pub(crate) fn log_inference(
        &mut self,
        constraint_tag: Option<NonZero<u32>>,
        premises: impl IntoIterator<Item = Literal>,
        propagated: Literal,
    ) -> std::io::Result<NonZeroU64> {
        let Some(ProofImpl::CpProof {
            writer,
            log_inferences: true,
            propagation_order_hint,
            ..
        }) = self.internal_proof.as_mut()
        else {
            return Ok(DUMMY_STEP_ID);
        };

        // TODO: Log the inference label.
        let id = writer.log_inference(constraint_tag, None, premises, propagated)?;

        if let Some(hints) = propagation_order_hint {
            hints.push(id);
        }

        Ok(id)
    }

    /// Record that a step has been used in the derivation of the next nogood.
    ///
    /// Inferences are automatically added as a propagation hint when they are logged, this is
    /// therefore only necessary when nogoods are used in a propagation.
    pub(crate) fn add_propagation(&mut self, step_id: NonZeroU64) {
        let Some(ProofImpl::CpProof {
            propagation_order_hint: Some(ref mut hints),
            ..
        }) = self.internal_proof.as_mut()
        else {
            return;
        };

        hints.push(step_id);
    }

    /// Log a learned clause to the proof.
    ///
    /// The inferences and marked propagations are assumed to be recorded in reverse-application
    /// order.
    pub(crate) fn log_learned_clause(
        &mut self,
        literals: impl IntoIterator<Item = Literal>,
    ) -> std::io::Result<NonZeroU64> {
        match &mut self.internal_proof {
            Some(ProofImpl::CpProof {
                writer,
                propagation_order_hint,
                ..
            }) => {
                let propagation_hints = propagation_order_hint
                    .as_ref()
                    .map(|vec| vec.iter().rev().copied());
                let id = writer.log_nogood_clause(literals, propagation_hints)?;

                // Clear the hints for the next nogood.
                if let Some(hints) = propagation_order_hint.as_mut() {
                    hints.clear();
                }

                Ok(id)
            }

            Some(ProofImpl::DimacsProof(writer)) => writer.learned_clause(literals),

            None => Ok(DUMMY_STEP_ID),
        }
    }

    pub(crate) fn unsat(
        self,
        variable_names: &VariableNames,
        variable_literal_mapping: &VariableLiteralMappings,
    ) -> std::io::Result<()> {
        match self.internal_proof {
            Some(ProofImpl::CpProof {
                writer,
                definitions_path,
                ..
            }) => {
                let literals = writer.unsat()?;
                let file = File::create(definitions_path)?;
                literals.write(file, variable_names, variable_literal_mapping)
            }
            Some(ProofImpl::DimacsProof(mut writer)) => {
                writer.learned_clause(std::iter::empty()).map(|_| ())
            }
            None => Ok(()),
        }
    }

    pub(crate) fn optimal(
        self,
        objective_bound: Literal,
        variable_names: &VariableNames,
        variable_literal_mapping: &VariableLiteralMappings,
    ) -> std::io::Result<()> {
        match self.internal_proof {
            Some(ProofImpl::CpProof {
                writer,
                definitions_path,
                ..
            }) => {
                let literals = writer.optimal(objective_bound)?;
                let file = File::create(definitions_path)?;
                literals.write(file, variable_names, variable_literal_mapping)
            }

            Some(ProofImpl::DimacsProof(_)) => {
                panic!("Cannot conclude optimality in DIMACS proof")
            }

            None => Ok(()),
        }
    }

    pub(crate) fn is_logging_inferences(&self) -> bool {
        matches!(
            self.internal_proof,
            Some(ProofImpl::CpProof {
                log_inferences: true,
                ..
            })
        )
    }
}

#[derive(Debug)]
enum ProofImpl {
    CpProof {
        writer: ProofWriter<File, ProofLiterals>,
        log_inferences: bool,
        definitions_path: PathBuf,
        // If propagation hints are enabled, this is a buffer used to record propagations in the
        // order they can be applied to derive the next nogood.
        propagation_order_hint: Option<Vec<NonZeroU64>>,
    },
    DimacsProof(DimacsProof<File>),
}