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
//! Problem domain definition such as bound constraints for variables.

use std::iter::FromIterator;

use nalgebra::{storage::StorageMut, Dim, RealField, Vector};

/// [`Variable`] builder type.
#[derive(Debug, Clone, Copy)]
pub struct VariableBuilder<T: RealField + Copy>(Variable<T>);

impl<T: RealField + Copy> VariableBuilder<T> {
    fn new() -> Self {
        Self(Variable::new())
    }

    /// Set the variable bounds. See
    /// [`Variable::set_bounds`](Variable::set_bounds) for details.
    pub fn bounds(mut self, lower: T, upper: T) -> Self {
        self.0.set_bounds(lower, upper);
        self
    }

    /// Set the variable magnitude. See
    /// [`Variable::set_magnitude`](Variable::set_magnitude) for details.
    pub fn magnitude(mut self, magnitude: T) -> Self {
        self.0.set_magnitude(magnitude);
        self
    }

    /// Finalize the variable construction.
    pub fn finalize(self) -> Variable<T> {
        self.0
    }
}

/// Variable definition.
///
/// There are two pieces of information about each variable:
///
/// * [`Bounds`](Variable::set_bounds) are used as constraints during solving
/// * [`Magnitude`](Variable::set_magnitude) is used to compensate scaling
///   discrepancies between different variables.
#[derive(Debug, Clone, Copy)]
pub struct Variable<T: RealField + Copy> {
    bounds: (T, T),
    magnitude: T,
}

impl<T: RealField + Copy> Variable<T> {
    /// Creates new unconstrained variable with magnitude 1.
    pub fn new() -> Self {
        let inf = T::from_subset(&f64::INFINITY);

        Self {
            bounds: (-inf, inf),
            magnitude: T::one(),
        }
    }

    /// Returns variable builder which allows to add constraints and magnitude.
    pub fn builder() -> VariableBuilder<T> {
        VariableBuilder::new()
    }

    /// Set the variable bounds.
    ///
    /// If both bounds are finite value, the variable magnitude is automatically
    /// estimated by an internal heuristic.
    ///
    /// # Panics
    ///
    /// Panics if `lower > upper`.
    pub fn set_bounds(&mut self, lower: T, upper: T) -> &mut Self {
        assert!(lower <= upper, "invalid bounds");

        if lower.is_finite() && upper.is_finite() {
            self.magnitude = estimate_magnitude(lower, upper);
        }

        self.bounds = (lower, upper);
        self
    }

    /// Set the variable magnitude.
    ///
    /// # Panics
    ///
    /// Panics if `magnitude <= 0`.
    pub fn set_magnitude(&mut self, magnitude: T) -> &mut Self {
        assert!(magnitude > T::zero(), "magnitude must be positive");
        self.magnitude = magnitude;
        self
    }

    /// Get the lower bound.
    pub fn lower(&self) -> T {
        self.bounds.0
    }

    /// Get the upper bound.
    pub fn upper(&self) -> T {
        self.bounds.1
    }

    /// Get the magnitude.
    pub fn magnitude(&self) -> T {
        self.magnitude
    }

    /// Get the scale which is inverse of the magnitude.
    pub fn scale(&self) -> T {
        T::one() / self.magnitude
    }

    /// Check if a value is within the bounds.
    pub fn is_within(&self, value: &T) -> bool {
        value >= &self.lower() && value <= &self.upper()
    }

    /// Return value that is clamped to be in bounds.
    pub fn clamp(&self, value: T) -> T {
        if value < self.lower() {
            self.lower()
        } else if value > self.upper() {
            self.upper()
        } else {
            value
        }
    }
}

impl<T: RealField + Copy> Default for Variable<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: RealField + Copy> From<VariableBuilder<T>> for Variable<T> {
    fn from(def: VariableBuilder<T>) -> Self {
        def.finalize()
    }
}

fn estimate_magnitude<T: RealField + Copy>(lower: T, upper: T) -> T {
    let ten = T::from_subset(&10.0);
    let half = T::from_subset(&0.5);

    let avg = half * (lower.abs() + upper.abs());
    let magnitude = ten.powf(avg.abs().log10().trunc());

    // For [0, 0] range, the computed magnitude is undefined. We allow such
    // ranges to support fixing a variable to a value with existing API.
    if magnitude.is_finite() && magnitude > T::zero() {
        magnitude
    } else {
        T::one()
    }
}

/// A convenience macro over [`VariableBuilder`].
///
/// # Examples
///
/// ```rust
/// use gomez::prelude::*;
///
/// let x = var!(-10.0f64, 10.0);
/// assert_eq!(x.lower(), -10.0);
/// assert_eq!(x.upper(), 10.0);
///
/// let y = var!(5.0f64);
/// assert_eq!(y.magnitude(), 5.0);
///
/// let z = var!(-10.0f64, 10.0; 5.0);
/// assert_eq!(z.lower(), -10.0);
/// assert_eq!(z.upper(), 10.0);
/// assert_eq!(z.magnitude(), 5.0);
/// ```
#[macro_export]
macro_rules! var {
    ($lower:expr, $upper:expr; $magnitude:expr) => {
        $crate::core::Variable::builder()
            .bounds($lower, $upper)
            .magnitude($magnitude)
            .finalize()
    };
    ($lower:expr, $upper:expr) => {
        $crate::core::Variable::builder()
            .bounds($lower, $upper)
            .finalize()
    };
    ($magnitude:expr) => {
        $crate::core::Variable::builder()
            .magnitude($magnitude)
            .finalize()
    };
}

/// A set of [`Variable`] definitions.
// TODO: Add generic type for nalgebra dimension?
pub struct Domain<T: RealField + Copy> {
    vars: Vec<Variable<T>>,
}

impl<T: RealField + Copy> Domain<T> {
    /// Creates unconstrained domain with given dimension.
    pub fn with_dim(n: usize) -> Self {
        (0..n).map(|_| Variable::default()).collect()
    }

    /// Creates the domain from variable definitions.
    ///
    /// This should be used for constrained or with known magnitude variables.
    /// For unconstrained domains, use [`Domain::with_dim`] instead. Note that
    /// it is possible to create the domain from iterator over type [`Variable`]
    /// by calling [`collect`](Iterator::collect).
    pub fn with_vars(vars: Vec<Variable<T>>) -> Self {
        assert!(!vars.is_empty(), "empty domain");
        Self { vars }
    }

    /// Get the variable definitions.
    pub fn vars(&self) -> &[Variable<T>] {
        self.vars.as_slice()
    }
}

impl<T: RealField + Copy> FromIterator<Variable<T>> for Domain<T> {
    fn from_iter<I: IntoIterator<Item = Variable<T>>>(iter: I) -> Self {
        Self::with_vars(iter.into_iter().collect())
    }
}

impl<T: RealField + Copy> From<Vec<Variable<T>>> for Domain<T> {
    fn from(vars: Vec<Variable<T>>) -> Self {
        Self::with_vars(vars)
    }
}

/// Domain-related extension methods for [`Vector`], which is a common storage
/// for variable values.
pub trait VectorDomainExt<T: RealField + Copy, D: Dim> {
    /// Clamp all values within corresponding bounds and returns if the original
    /// value was outside of bounds (in other bounds, the point was not
    /// feasible).
    fn project(&mut self, dom: &Domain<T>) -> bool;
}

impl<T: RealField + Copy, D: Dim, S> VectorDomainExt<T, D> for Vector<T, D, S>
where
    S: StorageMut<T, D>,
{
    fn project(&mut self, dom: &Domain<T>) -> bool {
        let not_feasible = self
            .iter()
            .zip(dom.vars().iter())
            .any(|(xi, vi)| !vi.is_within(xi));

        if not_feasible {
            // The point is outside the feasible domain. We need to do the
            // projection.
            self.iter_mut()
                .zip(dom.vars().iter())
                .for_each(|(xi, vi)| *xi = vi.clamp(*xi));
        }

        not_feasible
    }
}

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

    macro_rules! magnitude_of {
        ($lower:expr, $upper:expr) => {
            Variable::builder()
                .bounds($lower, $upper)
                .finalize()
                .magnitude()
        };
    }

    #[test]
    fn magnitude() {
        assert_eq!(magnitude_of!(-1e10f64, 1e10).log10(), 10.0);
        assert_eq!(magnitude_of!(-1e4f64, -1e2).log10(), 3.0);
        assert_eq!(magnitude_of!(-6e-6f64, 9e-6).log10().trunc(), -5.0);

        assert_eq!(magnitude_of!(-6e-6f64, 9e-6) / 1e-5, 1.0);
    }

    #[test]
    fn magnitude_when_bound_is_zero() {
        assert_eq!(magnitude_of!(0f64, 1e2).log10(), 1.0);
        assert_eq!(magnitude_of!(-1e2f64, 0.0).log10(), 1.0);
    }

    #[test]
    fn edge_cases() {
        assert_eq!(magnitude_of!(0.0f64, 0.0), 1.0);
    }
}