xcsp3_rust/objectives/
xobjective_element.rs

1/*=============================================================================
2* parser for CSP instances represented in XCSP3 Format
3*
4* Copyright (c) 2023 xcsp.org (contact @ xcsp.org)
5*
6* Permission is hereby granted, free of charge, to any person obtaining a copy
7* of this software and associated documentation files (the "Software"), to deal
8* in the Software without restriction, including without limitation the rights
9* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10* copies of the Software, and to permit persons to whom the Software is
11* furnished to do so, subject to the following conditions:
12*
13* The above copyright notice and this permission notice shall be included in
14* all copies or substantial portions of the Software.
15*
16* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22* THE SOFTWARE.
23*=============================================================================
24*/
25
26/*
27 * <p>@project_name: xcsp3-rust
28 * </p>
29 * <p>@author: luhan zhen
30 * </p>
31 * <p>@date:  2023/7/23 15:36
32 * </p>
33 * <p>@email: zhenlh20@mails.jlu.edu.cn
34 * </p>
35 * <p>@version: 1.0
36 * </p>
37 * <p>@description:
38 * </p>
39 */
40
41pub mod xcsp3_core {
42    use crate::data_structs::xint_val_var::xcsp3_core::XVarVal;
43    use crate::errors::xcsp3error::xcsp3_core::Xcsp3Error;
44    use std::collections::HashMap;
45
46    use crate::utils::utils_functions::xcsp3_utils::list_to_vec_var_val;
47    use crate::variables::xdomain::xcsp3_core::XDomainInteger;
48    use crate::variables::xvariable_set::xcsp3_core::XVariableSet;
49    use std::fmt::{Display, Formatter};
50
51    #[derive(Clone, Debug)]
52    pub enum XElementOperator {
53        Sum,
54        Product,
55        Minimum,
56        Maximum,
57        NValues,
58        Lex,
59    }
60
61    impl XElementOperator {
62        pub fn get_objectives_operator_by_str(op: &str) -> Option<Self> {
63            match op {
64                "sum" => Some(Self::Sum),
65                "product" => Some(Self::Product),
66                "minimum" => Some(Self::Minimum),
67                "maximum" => Some(Self::Maximum),
68                "nValues" => Some(Self::NValues),
69                "lex" => Some(Self::Lex),
70                _ => None,
71            }
72        }
73    }
74
75    #[derive(Clone)]
76    pub struct XObjectiveElement<'a> {
77        operator: XElementOperator,
78        scope: Vec<XVarVal>,
79        coeffs: Vec<XVarVal>,
80        set: &'a XVariableSet,
81        map: HashMap<String, &'a XDomainInteger>,
82    }
83
84    impl<'a> XObjectiveElement<'a> {
85        pub fn get_scope_string(&self) -> &Vec<XVarVal> {
86            &self.scope
87        }
88
89        pub fn get_scope(&mut self) -> Vec<(&String, &XDomainInteger)> {
90            for e in &self.scope {
91                if let XVarVal::IntVar(s) = e {
92                    if !self.map.contains_key(s) {
93                        if let Ok(vec) = self.set.construct_scope(&[s]) {
94                            for (vs, vv) in vec.into_iter() {
95                                self.map.insert(vs, vv);
96                            }
97                        }
98                    }
99                }
100            }
101            let mut scope_vec_var: Vec<(&String, &XDomainInteger)> = vec![];
102            for e in self.map.iter() {
103                scope_vec_var.push((e.0, e.1))
104            }
105            scope_vec_var
106        }
107
108        pub fn new(
109            operator: XElementOperator,
110            scope: Vec<XVarVal>,
111            coeffs: Vec<XVarVal>,
112            set: &'a XVariableSet,
113        ) -> Self {
114            Self {
115                operator,
116                scope,
117                coeffs,
118                set,
119                map: Default::default(),
120            }
121        }
122
123        pub fn from_str(
124            list_str: &str,
125            coeffs_str: &str,
126            ope_str: &str,
127            set: &'a XVariableSet,
128        ) -> Result<Self, Xcsp3Error> {
129            match list_to_vec_var_val(list_str) {
130                Ok(scope_vec_str) => match list_to_vec_var_val(coeffs_str) {
131                    Ok(coef_vec_str) => {
132                        match XElementOperator::get_objectives_operator_by_str(ope_str) {
133                            None => Err(Xcsp3Error::get_objective_target_error(
134                                "parse objective type error, ",
135                            )),
136                            Some(v) => Ok(Self::new(v, scope_vec_str, coef_vec_str, set)),
137                        }
138                    }
139                    Err(e) => Err(e),
140                },
141                Err(e) => Err(e),
142            }
143            // Err(Xcsp3Error::get_objective_target_error("e"))
144        }
145
146        pub fn get_operator(&self) -> &XElementOperator {
147            &self.operator
148        }
149        pub fn get_coeffs(&self) -> &Vec<XVarVal> {
150            &self.coeffs
151        }
152    }
153
154    impl Display for XObjectiveElement<'_> {
155        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
156            let mut ret1 = String::default();
157            for e in self.scope.iter() {
158                ret1.push('(');
159                ret1.push_str(&e.to_string());
160                ret1.push_str("), ")
161            }
162            let mut ret2 = String::default();
163            for e in self.coeffs.iter() {
164                ret2.push('(');
165                ret2.push_str(&e.to_string());
166                ret2.push_str("), ")
167            }
168            write!(
169                f,
170                "operator = {:?}, list =  {}, coeffs = {}",
171                self.operator, ret1, ret2
172            )
173        }
174    }
175}