optimization_engine/constraints/
ball2.rs

1use super::Constraint;
2
3#[derive(Copy, Clone)]
4/// A Euclidean ball, that is, a set given by $B_2^r = \\{x \in \mathbb{R}^n {}:{} \Vert{}x{}\Vert \leq r\\}$
5/// or a Euclidean ball centered at a point $x_c$, that is, $B_2^{x_c, r} = \\{x \in \mathbb{R}^n {}:{} \Vert{}x-x_c{}\Vert \leq r\\}$
6pub struct Ball2<'a> {
7    center: Option<&'a [f64]>,
8    radius: f64,
9}
10
11impl<'a> Ball2<'a> {
12    /// Construct a new Euclidean ball with given center and radius
13    /// If no `center` is given, then it is assumed to be in the origin
14    pub fn new(center: Option<&'a [f64]>, radius: f64) -> Self {
15        assert!(radius > 0.0);
16
17        Ball2 { center, radius }
18    }
19}
20
21impl<'a> Constraint for Ball2<'a> {
22    fn project(&self, x: &mut [f64]) {
23        if let Some(center) = &self.center {
24            let mut norm_difference = 0.0;
25            x.iter().zip(center.iter()).for_each(|(a, b)| {
26                let diff_ = *a - *b;
27                norm_difference += diff_ * diff_
28            });
29
30            norm_difference = norm_difference.sqrt();
31
32            if norm_difference > self.radius {
33                x.iter_mut().zip(center.iter()).for_each(|(x, c)| {
34                    *x = *c + self.radius * (*x - *c) / norm_difference;
35                });
36            }
37        } else {
38            let norm_x = crate::matrix_operations::norm2(x);
39            if norm_x > self.radius {
40                let norm_over_radius = norm_x / self.radius;
41                x.iter_mut().for_each(|x_| *x_ /= norm_over_radius);
42            }
43        }
44    }
45
46    fn is_convex(&self) -> bool {
47        true
48    }
49}