ommx 2.5.2

Open Mathematical prograMming eXchange (OMMX)
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
use crate::{
    macros::*,
    v1::{Linear, Polynomial, Quadratic, SampledValues, Samples, State},
    Evaluate, MonomialDyn, VariableID, VariableIDSet,
};
use anyhow::{ensure, Context, Result};
use approx::AbsDiffEq;
use num::Zero;
use std::{
    collections::BTreeMap,
    fmt,
    ops::{Add, Mul},
};

use crate::format::format_polynomial;

impl Zero for Quadratic {
    fn zero() -> Self {
        Self {
            columns: vec![],
            rows: vec![],
            values: vec![],
            linear: Some(Linear::zero()),
        }
    }

    fn is_zero(&self) -> bool {
        self.columns.is_empty()
            && self.rows.is_empty()
            && self.values.is_empty()
            && self.linear.as_ref().is_none_or(|l| l.is_zero())
    }
}

impl Quadratic {
    pub fn quad_iter(&self) -> impl Iterator<Item = ((u64, u64), f64)> + '_ {
        assert_eq!(self.columns.len(), self.rows.len());
        assert_eq!(self.columns.len(), self.values.len());
        self.columns
            .iter()
            .zip(self.rows.iter())
            .zip(self.values.iter())
            .map(|((column, row), value)| ((*column, *row), *value))
    }

    /// Downcast to a linear function if the quadratic function is linear.
    pub fn as_linear(self) -> Option<Linear> {
        if self.values.iter().all(|v| v.abs() <= f64::EPSILON) {
            Some(self.linear.unwrap_or_default())
        } else {
            None
        }
    }

    /// Downcast to a constant if the quadratic function is constant.
    pub fn as_constant(self) -> Option<f64> {
        self.as_linear()?.as_constant()
    }

    pub fn degree(&self) -> u32 {
        if self.values.iter().any(|v| v.abs() > f64::EPSILON) {
            2
        } else {
            self.linear.as_ref().map_or(0, |l| l.degree())
        }
    }

    pub fn get_constant(&self) -> f64 {
        self.linear.as_ref().map_or(0.0, |l| l.constant)
    }
}

impl From<f64> for Quadratic {
    fn from(c: f64) -> Self {
        Self {
            columns: Vec::new(),
            rows: Vec::new(),
            values: Vec::new(),
            linear: Some(c.into()),
        }
    }
}

impl From<Linear> for Quadratic {
    fn from(l: Linear) -> Self {
        Self {
            columns: Vec::new(),
            rows: Vec::new(),
            values: Vec::new(),
            linear: Some(l),
        }
    }
}

impl FromIterator<((u64, u64), f64)> for Quadratic {
    fn from_iter<I: IntoIterator<Item = ((u64, u64), f64)>>(iter: I) -> Self {
        let mut terms = BTreeMap::new();
        for ((row, col), value) in iter {
            let id = if row < col { (row, col) } else { (col, row) };
            *terms.entry(id).or_default() += value;
        }
        let mut columns = Vec::new();
        let mut rows = Vec::new();
        let mut values = Vec::new();
        for ((row, col), value) in terms {
            columns.push(col);
            rows.push(row);
            values.push(value);
        }
        Self {
            columns,
            rows,
            values,
            linear: None,
        }
    }
}

impl<'a> IntoIterator for &'a Quadratic {
    type Item = (MonomialDyn, f64);
    type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;

    fn into_iter(self) -> Self::IntoIter {
        assert_eq!(self.columns.len(), self.rows.len());
        assert_eq!(self.columns.len(), self.values.len());
        let n = self.columns.len();
        let quad = (0..n).map(move |i| {
            (
                MonomialDyn::new(vec![self.columns[i].into(), self.rows[i].into()]),
                self.values[i],
            )
        });
        if let Some(linear) = &self.linear {
            Box::new(
                quad.chain(
                    linear
                        .into_iter()
                        .map(|(id, c)| (id.into_iter().map(VariableID::from).collect(), c)),
                ),
            )
        } else {
            Box::new(quad)
        }
    }
}

impl Add for Quadratic {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let mut map: BTreeMap<(u64, u64), f64> = self.quad_iter().collect();
        for (id, value) in rhs.quad_iter() {
            let v = map.entry(id).or_default();
            *v += value;
            if v.abs() <= f64::EPSILON {
                map.remove(&id);
            }
        }
        let mut out: Self = map.into_iter().collect();
        out.linear = match (self.linear, rhs.linear) {
            (Some(l), Some(r)) => {
                let out = l + r;
                if out.is_zero() {
                    None
                } else {
                    Some(out)
                }
            }
            (Some(l), None) | (None, Some(l)) => Some(l),
            (None, None) => None,
        };
        out
    }
}

impl Add<Linear> for Quadratic {
    type Output = Self;

    fn add(mut self, rhs: Linear) -> Self {
        if let Some(linear) = self.linear {
            self.linear = Some(linear + rhs);
        } else {
            self.linear = Some(rhs);
        }
        self
    }
}

impl Add<f64> for Quadratic {
    type Output = Self;

    fn add(mut self, rhs: f64) -> Self {
        if let Some(linear) = self.linear {
            self.linear = Some(linear + rhs);
        } else {
            self.linear = Some(rhs.into());
        }
        self
    }
}

impl_add_inverse!(Linear, Quadratic);
impl_add_inverse!(f64, Quadratic);
impl_sub_by_neg_add!(Quadratic, Linear);
impl_sub_by_neg_add!(Quadratic, f64);
impl_sub_by_neg_add!(Quadratic, Quadratic);

impl Mul for Quadratic {
    type Output = Polynomial;

    fn mul(self, rhs: Self) -> Self::Output {
        let mut terms = BTreeMap::new();
        for (id_l, value_l) in self.into_iter() {
            for (id_r, value_r) in rhs.clone().into_iter() {
                let ids = id_r * id_l.clone();
                *terms.entry(ids).or_default() += value_l * value_r;
            }
        }
        terms.into_iter().collect()
    }
}

impl_mul_from!(Quadratic, Linear, Polynomial);
impl_mul_inverse!(Linear, Quadratic);

impl Mul<f64> for Quadratic {
    type Output = Self;

    fn mul(mut self, rhs: f64) -> Self {
        if rhs.is_zero() {
            return Self::zero();
        }
        for value in self.values.iter_mut() {
            *value *= rhs;
        }
        if let Some(linear) = self.linear {
            self.linear = Some(linear * rhs);
        } // 0 * rhs = 0
        self
    }
}

impl_mul_inverse!(f64, Quadratic);
impl_neg_by_mul!(Quadratic);

/// Compare coefficients in sup-norm.
impl AbsDiffEq for Quadratic {
    type Epsilon = crate::ATol;

    fn default_epsilon() -> Self::Epsilon {
        crate::ATol::default()
    }

    fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
        match (&self.linear, &other.linear) {
            (Some(l), Some(r)) => {
                if !l.abs_diff_eq(r, epsilon) {
                    return false;
                }
            }
            (Some(l), None) | (None, Some(l)) => {
                if !l.abs_diff_eq(&Linear::zero(), epsilon) {
                    return false;
                }
            }
            (None, None) => {}
        }
        let sub = self.clone() - other.clone();
        for (_, value) in sub.into_iter() {
            if !value.abs_diff_eq(&0.0, epsilon.into_inner()) {
                return false;
            }
        }
        true
    }
}

impl fmt::Display for Quadratic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_zero() {
            return write!(f, "0");
        }
        format_polynomial(f, self.into_iter())
    }
}

impl Evaluate for Quadratic {
    type Output = f64;
    type SampledOutput = SampledValues;

    fn evaluate(&self, solution: &State, atol: crate::ATol) -> Result<f64> {
        let mut sum = if let Some(linear) = &self.linear {
            linear.evaluate(solution, atol)?
        } else {
            0.0
        };
        for (i, j, value) in
            itertools::multizip((self.rows.iter(), self.columns.iter(), self.values.iter()))
        {
            let u = solution
                .entries
                .get(i)
                .with_context(|| format!("Variable id ({i}) is not found in the solution"))?;
            let v = solution
                .entries
                .get(j)
                .with_context(|| format!("Variable id ({j}) is not found in the solution"))?;
            sum += value * u * v;
        }
        Ok(sum)
    }

    fn partial_evaluate(&mut self, state: &State, _atol: crate::ATol) -> Result<()> {
        let mut linear = BTreeMap::new();
        let mut constant = self.linear.as_ref().map_or(0.0, |l| l.constant);
        for term in self.linear.iter().flat_map(|l| l.terms.iter()) {
            if let Some(value) = state.entries.get(&term.id) {
                constant += term.coefficient * value;
            } else {
                *linear.entry(term.id).or_insert(0.0) += term.coefficient;
            }
        }

        ensure!(self.rows.len() == self.columns.len());
        ensure!(self.rows.len() == self.values.len());
        let mut i = 0;
        while i < self.rows.len() {
            let (row, column, value) = (self.rows[i], self.columns[i], self.values[i]);
            match (state.entries.get(&row), state.entries.get(&column)) {
                (Some(u), Some(v)) => {
                    constant += value * u * v;
                }
                (Some(u), None) => {
                    *linear.entry(column).or_insert(0.0) += value * u;
                }
                (None, Some(v)) => {
                    *linear.entry(row).or_insert(0.0) += value * v;
                }
                _ => {
                    i += 1;
                    continue;
                }
            }
            self.rows.swap_remove(i);
            self.columns.swap_remove(i);
            self.values.swap_remove(i);
        }
        if linear.is_empty() && constant == 0.0 {
            self.linear = None;
        } else {
            self.linear = Some(Linear::new(linear.into_iter(), constant));
        }
        Ok(())
    }

    fn evaluate_samples(
        &self,
        samples: &Samples,
        atol: crate::ATol,
    ) -> Result<Self::SampledOutput> {
        let out = samples.map(|s| {
            let value = self.evaluate(s, atol)?;
            Ok(value)
        })?;
        Ok(out)
    }

    fn required_ids(&self) -> VariableIDSet {
        self.linear
            .as_ref()
            .map_or_else(VariableIDSet::default, |l| l.required_ids())
            .into_iter()
            .chain(
                self.columns
                    .iter()
                    .chain(self.rows.iter())
                    .map(|id| VariableID::from(*id)),
            )
            .collect()
    }
}

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

    test_algebraic!(Quadratic);

    #[test]
    fn format() {
        let q = Quadratic::from_iter(vec![
            ((0, 1), 1.0),
            ((1, 2), -1.0),
            ((2, 0), -2.0),
            ((1, 3), 1.0 / 3.0),
        ]) + Linear::new(
            [(1, 1.0), (2, -1.0), (3, -2.0), (4, 1.0 / 3.0)].into_iter(),
            3.0,
        );
        assert_eq!(
            q.to_string(),
            "x0*x1 - 2*x0*x2 - x1*x2 + 0.3333333333333333*x1*x3 + x1 - x2 - 2*x3 + 0.3333333333333333*x4 + 3"
        );
        assert_eq!(
            format!("{q:.2}"),
            "x0*x1 - 2.00*x0*x2 - x1*x2 + 0.33*x1*x3 + x1 - x2 - 2.00*x3 + 0.33*x4 + 3.00"
        );
    }
}