1
// https://conjure-cp.github.io/conjure-oxide/docs/conjure_core/representation/trait.Representation.html
2
use conjure_cp::ast::GroundDomain;
3
use conjure_cp::bug;
4
use conjure_cp::{
5
    ast::{Atom, DeclarationPtr, Domain, Expression, Literal, Metadata, Name, SymbolTable},
6
    register_representation,
7
    representation::Representation,
8
    rule_engine::ApplicationError,
9
};
10

            
11
register_representation!(SatDirectInt, "sat_direct_int");
12

            
13
#[derive(Clone, Debug)]
14
pub struct SatDirectInt {
15
    src_var: Name,
16
    upper_bound: i32,
17
    lower_bound: i32,
18
}
19

            
20
impl SatDirectInt {
21
    /// Returns the names of the boolean variables used in the direct encoding.
22
5280
    fn names(&self) -> impl Iterator<Item = Name> + '_ {
23
37266
        (self.lower_bound..=self.upper_bound).map(|index| self.index_to_name(index))
24
5280
    }
25

            
26
    /// Gets the representation variable name corresponding to a concrete integer value.
27
2058192
    fn index_to_name(&self, index: i32) -> Name {
28
2058192
        Name::Represented(Box::new((
29
2058192
            self.src_var.clone(),
30
2058192
            self.repr_name().into(),
31
2058192
            format!("{index}").into(), // stored as _00, _01, ...
32
2058192
        )))
33
2058192
    }
34
}
35

            
36
impl Representation for SatDirectInt {
37
    /// Creates a direct int representation object for the given name.
38
2010
    fn init(name: &Name, symtab: &SymbolTable) -> Option<Self> {
39
2010
        let domain = symtab.resolve_domain(name)?;
40

            
41
2010
        if !domain.is_finite() {
42
            return None;
43
2010
        }
44

            
45
2010
        let GroundDomain::Int(ranges) = domain.as_ref() else {
46
            return None;
47
        };
48

            
49
        // Determine min/max and return None if range is unbounded
50
2010
        let (min, max) =
51
2010
            ranges
52
2010
                .iter()
53
2130
                .try_fold((i32::MAX, i32::MIN), |(min_a, max_b), range| {
54
2130
                    let lb = range.low()?;
55
2130
                    let ub = range.high()?;
56
2130
                    Some((min_a.min(*lb), max_b.max(*ub)))
57
2130
                })?;
58

            
59
2010
        Some(SatDirectInt {
60
2010
            src_var: name.clone(),
61
2010
            lower_bound: min,
62
2010
            upper_bound: max,
63
2010
        })
64
2010
    }
65

            
66
    /// The variable being represented.
67
    fn variable_name(&self) -> &Name {
68
        &self.src_var
69
    }
70

            
71
    fn value_down(
72
        &self,
73
        _value: Literal,
74
    ) -> Result<std::collections::BTreeMap<Name, Literal>, ApplicationError> {
75
        // NOTE: It's unclear where and when `value_down` would be called for
76
        // direct encoding. This is also never called in log encoding, so we
77
        // deliberately fail here to surface unexpected usage.
78
        bug!("value_down is not implemented for direct encoding and should not be called")
79
    }
80

            
81
    /// Given the values for its boolean representation variables, creates an assignment for `self` - the integer form.
82
100782
    fn value_up(
83
100782
        &self,
84
100782
        values: &std::collections::BTreeMap<Name, Literal>,
85
100782
    ) -> Result<Literal, ApplicationError> {
86
100782
        let mut found_value: Option<i32> = None;
87

            
88
2020926
        for value_candidate in self.lower_bound..=self.upper_bound {
89
2020926
            let name = self.index_to_name(value_candidate);
90
2020926
            let value_literal = values
91
2020926
                .get(&name)
92
2020926
                .ok_or(ApplicationError::RuleNotApplicable)?;
93

            
94
2020926
            let is_true = match value_literal {
95
100782
                Literal::Int(1) | Literal::Bool(true) => true,
96
1920144
                Literal::Int(0) | Literal::Bool(false) => false,
97
                _ => return Err(ApplicationError::RuleNotApplicable),
98
            };
99

            
100
2020926
            if is_true {
101
100782
                if found_value.is_some() {
102
                    // More than one variable is true, which is an error for direct encoding
103
                    return Err(ApplicationError::RuleNotApplicable);
104
100782
                }
105
100782
                found_value = Some(value_candidate);
106
1920144
            }
107
        }
108

            
109
100782
        found_value
110
100782
            .map(Literal::Int)
111
100782
            .ok_or(ApplicationError::RuleNotApplicable)
112
100782
    }
113

            
114
    /// Returns [`Expression`]s representing each boolean representation variable.
115
3270
    fn expression_down(
116
3270
        &self,
117
3270
        st: &SymbolTable,
118
3270
    ) -> Result<std::collections::BTreeMap<Name, Expression>, ApplicationError> {
119
3270
        Ok(self
120
3270
            .names()
121
3270
            .enumerate()
122
21684
            .map(|(index, name)| {
123
21684
                let decl = st.lookup(&name).unwrap();
124
21684
                (
125
                    // Machine names are used so that the derived ordering matches the correct ordering of the representation variables
126
21684
                    Name::Machine(index as i32),
127
21684
                    Expression::Atomic(
128
21684
                        Metadata::new(),
129
21684
                        Atom::Reference(conjure_cp::ast::Reference { ptr: decl }),
130
21684
                    ),
131
21684
                )
132
21684
            })
133
3270
            .collect())
134
3270
    }
135

            
136
    /// Creates declarations for the boolean representation variables of `self`.
137
2010
    fn declaration_down(&self) -> Result<Vec<DeclarationPtr>, ApplicationError> {
138
2010
        let temp_a = self
139
2010
            .names()
140
15582
            .map(|name| DeclarationPtr::new_find(name, Domain::bool()))
141
2010
            .collect();
142

            
143
2010
        Ok(temp_a)
144
2010
    }
145

            
146
    /// The rule name for this representation.
147
2064732
    fn repr_name(&self) -> &str {
148
2064732
        "sat_direct_int"
149
2064732
    }
150

            
151
    /// Makes a clone of `self` into a `Representation` trait object.
152
135021
    fn box_clone(&self) -> Box<dyn Representation> {
153
135021
        Box::new(self.clone()) as _
154
135021
    }
155
}