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
use super::{Instance, Sense};
use crate::{BinaryIdPair, BinaryIds, Evaluate};
use anyhow::{bail, Result};
use std::collections::BTreeMap;
impl Instance {
/// Create QUBO (Quadratic Unconstrained Binary Optimization) dictionary from the instance.
///
/// Before calling this method, you should check that this instance is suitable for QUBO:
///
/// - This instance has no constraints
/// - Use penalty method (TODO: ALM will be added) to convert into an unconstrained problem.
/// - The objective function uses only binary decision variables.
/// - TODO: Binary encoding will be added.
/// - The degree of the objective is at most 2.
///
/// # Postconditions
///
/// The returned QUBO encodes the active objective, while evaluation uses the output objective.
///
/// ```
/// use ommx::{
/// linear, v1::State, ATol, BinaryIdPair, DecisionVariable, Evaluate,
/// Function, Instance, Sense, VariableID,
/// };
/// use std::collections::BTreeMap;
///
/// let mut instance = Instance::builder()
/// .sense(Sense::Maximize)
/// .objective(Function::from(linear!(1)))
/// .decision_variables(BTreeMap::from([(
/// VariableID::from(1),
/// DecisionVariable::binary(),
/// )]))
/// .constraints(BTreeMap::new())
/// .build()
/// .unwrap();
/// assert!(instance.convert_active_objective(Sense::Minimize));
///
/// let (qubo, offset) = instance.as_qubo_format().unwrap();
/// assert_eq!(qubo.get(&BinaryIdPair(1, 1)), Some(&-1.0));
/// assert_eq!(offset, 0.0);
///
/// let solution = instance
/// .evaluate(&State::from_iter([(1, 1.0)]), ATol::default())
/// .unwrap();
/// assert_eq!(*solution.sense(), Some(Sense::Maximize));
/// assert_eq!(*solution.objective(), 1.0);
/// ```
#[tracing::instrument(skip_all)]
pub fn as_qubo_format(&self) -> Result<(BTreeMap<BinaryIdPair, f64>, f64)> {
if self.sense() == Sense::Maximize {
bail!("QUBO format is only for minimization problems.");
}
if !self.constraints().is_empty() {
bail!("The instance still has constraints. Use penalty method or other way to translate into unconstrained problem first.");
}
let special_constraint_kinds = self.active_special_constraint_kinds();
if !special_constraint_kinds.is_empty() {
bail!(
"QUBO format does not support these special constraint types: {special_constraint_kinds:?}. Lower or convert them via an appropriate method first."
);
}
if !self
.objective()
.required_ids()
.is_subset(&self.binary_ids())
{
bail!("The objective function uses non-binary decision variables.");
}
let mut constant = 0.0;
let mut quad: BTreeMap<BinaryIdPair, f64> = BTreeMap::new();
for (ids, coefficient) in self.objective().iter() {
let c = coefficient.into_inner();
if c.abs() <= f64::EPSILON {
continue;
}
if ids.is_empty() {
constant += c;
} else {
let key = BinaryIdPair::try_from(ids)?;
let value = quad.entry(key).and_modify(|v| *v += c).or_insert(c);
if value.abs() < f64::EPSILON {
quad.remove(&key);
}
}
}
Ok((quad, constant))
}
/// Create HUBO (Higher-Order Unconstrained Binary Optimization) dictionary from the instance.
///
/// Before calling this method, you should check that this instance is suitable for HUBO:
///
/// - This instance has no constraints
/// - Use penalty method (TODO: ALM will be added) to convert into an unconstrained problem.
/// - The objective function uses only binary decision variables.
/// - TODO: Binary encoding will be added.
///
/// # Postconditions
///
/// The returned HUBO encodes the active objective, while evaluation uses the output objective.
///
/// ```
/// use ommx::{
/// linear, v1::State, ATol, DecisionVariable, Evaluate, Function,
/// Instance, Sense, VariableID,
/// };
/// use std::collections::BTreeMap;
///
/// let mut instance = Instance::builder()
/// .sense(Sense::Maximize)
/// .objective(Function::from(linear!(1)))
/// .decision_variables(BTreeMap::from([(
/// VariableID::from(1),
/// DecisionVariable::binary(),
/// )]))
/// .constraints(BTreeMap::new())
/// .build()
/// .unwrap();
/// assert!(instance.convert_active_objective(Sense::Minimize));
///
/// let (hubo, offset) = instance.as_hubo_format().unwrap();
/// assert_eq!(hubo.len(), 1);
/// assert_eq!(hubo.values().next(), Some(&-1.0));
/// assert_eq!(offset, 0.0);
///
/// let solution = instance
/// .evaluate(&State::from_iter([(1, 1.0)]), ATol::default())
/// .unwrap();
/// assert_eq!(*solution.sense(), Some(Sense::Maximize));
/// assert_eq!(*solution.objective(), 1.0);
/// ```
#[tracing::instrument(skip_all)]
pub fn as_hubo_format(&self) -> Result<(BTreeMap<BinaryIds, f64>, f64)> {
if self.sense() == Sense::Maximize {
bail!("HUBO format is only for minimization problems.");
}
if !self.constraints().is_empty() {
bail!("The instance still has constraints. Use penalty method or other way to translate into unconstrained problem first.");
}
let special_constraint_kinds = self.active_special_constraint_kinds();
if !special_constraint_kinds.is_empty() {
bail!(
"HUBO format does not support these special constraint types: {special_constraint_kinds:?}. Lower or convert them via an appropriate method first."
);
}
if !self
.objective()
.required_ids()
.is_subset(&self.binary_ids())
{
bail!("The objective function uses non-binary decision variables.");
}
let mut constant = 0.0;
let mut hubo: BTreeMap<BinaryIds, f64> = BTreeMap::new();
for (ids, coefficient) in self.objective().iter() {
let c = coefficient.into_inner();
if c.abs() <= f64::EPSILON {
continue;
}
if ids.is_empty() {
constant += c;
} else {
let key = BinaryIds::from(ids);
let value = hubo.entry(key.clone()).and_modify(|v| *v += c).or_insert(c);
if value.abs() < f64::EPSILON {
hubo.remove(&key);
}
}
}
Ok((hubo, constant))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{coeff, linear, quadratic, DecisionVariable, Function, VariableID};
use maplit::btreemap;
use std::collections::BTreeMap;
fn binary_vars(ids: impl IntoIterator<Item = u64>) -> BTreeMap<VariableID, DecisionVariable> {
ids.into_iter()
.map(|i| {
let id = VariableID::from(i);
(id, DecisionVariable::binary())
})
.collect()
}
#[test]
fn qubo_from_quadratic_objective() {
// min x1 + 2*x2 + 3*x1*x2 with binary x1, x2
let objective =
(Function::from(linear!(1)) + Function::from(coeff!(2.0) * linear!(2))).unwrap();
let objective = (objective + Function::from(coeff!(3.0) * quadratic!(1, 2))).unwrap();
let instance = Instance::new(
Sense::Minimize,
objective,
binary_vars([1, 2]),
BTreeMap::new(),
)
.unwrap();
let (quad, constant) = instance.as_qubo_format().unwrap();
assert_eq!(constant, 0.0);
assert_eq!(quad.get(&BinaryIdPair(1, 1)), Some(&1.0));
assert_eq!(quad.get(&BinaryIdPair(2, 2)), Some(&2.0));
assert_eq!(quad.get(&BinaryIdPair(1, 2)), Some(&3.0));
}
#[test]
fn qubo_rejects_maximization() {
let instance = Instance::new(
Sense::Maximize,
linear!(1).into(),
binary_vars([1]),
BTreeMap::new(),
)
.unwrap();
let err = instance.as_qubo_format().unwrap_err();
assert!(err.to_string().contains("minimization"));
}
#[test]
fn qubo_rejects_instances_with_constraints() {
let constraints = btreemap! {
crate::ConstraintID::from(0) =>
crate::Constraint::equal_to_zero(linear!(1).into()),
};
let instance = Instance::new(
Sense::Minimize,
linear!(1).into(),
binary_vars([1]),
constraints,
)
.unwrap();
let err = instance.as_qubo_format().unwrap_err();
assert!(err.to_string().contains("constraints"));
}
#[test]
fn qubo_rejects_non_binary_decision_variables() {
let mut dv = binary_vars([1]);
let id = VariableID::from(2);
dv.insert(id, DecisionVariable::integer());
let instance = Instance::new(
Sense::Minimize,
(linear!(1) + linear!(2)).into(),
dv,
BTreeMap::new(),
)
.unwrap();
let err = instance.as_qubo_format().unwrap_err();
assert!(err.to_string().contains("non-binary"));
}
#[test]
fn qubo_rejects_instances_with_one_hot_constraints() {
use crate::{OneHotConstraint, OneHotConstraintID};
use std::collections::BTreeSet;
let mut instance = Instance::new(
Sense::Minimize,
linear!(1).into(),
binary_vars([1, 2]),
BTreeMap::new(),
)
.unwrap();
let one_hot = OneHotConstraint::new(
[VariableID::from(1), VariableID::from(2)]
.into_iter()
.collect::<BTreeSet<_>>(),
)
.unwrap();
instance
.one_hot_constraint_collection
.insert_active_with_context(
OneHotConstraintID::from(0),
one_hot,
crate::ConstraintContext::default(),
)
.unwrap();
let err = instance.as_qubo_format().unwrap_err();
let msg = err.to_string() + " " + &err.root_cause().to_string();
assert!(
msg.contains("QUBO") || msg.contains("Unsupported"),
"expected rejection message, got: {msg}"
);
}
#[test]
fn hubo_from_cubic_objective() {
// min x1*x2*x3 + x1 with binary x1, x2, x3
use crate::MonomialDyn;
let cubic = crate::Polynomial::single_term(
MonomialDyn::new(vec![
VariableID::from(1),
VariableID::from(2),
VariableID::from(3),
]),
coeff!(1.0),
);
let objective = (Function::from(linear!(1)) + Function::from(cubic)).unwrap();
let instance = Instance::new(
Sense::Minimize,
objective,
binary_vars([1, 2, 3]),
BTreeMap::new(),
)
.unwrap();
let (hubo, constant) = instance.as_hubo_format().unwrap();
assert_eq!(constant, 0.0);
// Cubic term
let cubic_key = BinaryIds::from(MonomialDyn::new(vec![
VariableID::from(1),
VariableID::from(2),
VariableID::from(3),
]));
assert_eq!(hubo.get(&cubic_key), Some(&1.0));
// Linear term
let linear_key = BinaryIds::from(MonomialDyn::new(vec![VariableID::from(1)]));
assert_eq!(hubo.get(&linear_key), Some(&1.0));
}
}